アキラのITメモ:シリアルポートの通信

IT関係、技術関係のメモです。

シリアルポートの通信

Windows上にてシリアルポートを使った通信をしようと思い、JAVAやPerl、Cなどいろいろな言語で試してみたのですがなかなかうまくいかず、結局cygwin+C言語で書きました。以下はその時のメモです。ここのプログラムを参考にしました。

単純にシリアルポート(COM1)から読み込んできたバイナリデータを出力するのはこんな感じに書けばOKです。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <termios.h>
#include <time.h>

void main() {
  int fd;
  struct termios tio;

  // open and set port
  fd = open("/dev/COM1", O_RDWR);
  memset(&tio, 0, sizeof(tio));
  tio.c_cflag = CS8 | CLOCAL | CREAD;
  tio.c_cc[VTIME] = 100;
  cfsetispeed(&tio, B57600);
  cfsetospeed(&tio, B57600);
  tcsetattr(fd, TCSANOW, &tio);

  // read from serial port
  while(1){
    int i;
    int len;
    unsigned char buffer[256];
    if ((len = read(fd, buffer, 256)) < 0) {
      exit(0);
    }
    for(i=0; i<len; i++){
       printf("%02X ",buffer[i]);
    }
  }
}

カテゴリ: C言語 投稿日: 2007年04月06日 20:36
Trackback URL: http://akira-site.net/cgi-bin/mt/mt-tb.cgi/464

コメント

コメントを投稿





カテゴリ「C言語」内の記事

サイト内検索

カテゴリ

最近のエントリ

関連商品

アバウト

Atom RSS
Powered by MT3.33-ja
合計:total
今日:today 昨日:yesterday