2008年9月10日水曜日

シリアル通信プログラム

Linuxでシリアル(RS-232C)通信が必要な場合
リダイレクトで済むことも結構多いですが、
やはりCで処理したいことだってあるんです。
というわけで下記のようなCのサンプルソースを書いてみました。
今回はシリアルからの読み込みしかしていません。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <termios.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>

static char device[16]="/dev/ttyS0";

int main(int arc,char *arg[])
{
int i,fd;
FILE *f;
struct termios tty;
char *c,buff[256];

if(arc>1)
strncpy(device,arg[1],sizeof(device));
if((fd=open(device,O_RDWR|O_NOCTTY))==-1){
fprintf(stdout,"can't open %s.\n",device);
exit(EXIT_FAILURE);
}
memset(&tty,0,sizeof(tty));
tty.c_cflag=CS8|CLOCAL|CREAD;
tty.c_cc[VMIN]=1;
tty.c_cc[VTIME]=0;
cfsetospeed(&tty,B38400);
cfsetispeed(&tty,B38400);
tcflush(fd,TCIFLUSH);
tcsetattr(fd,TCSANOW,&tty);

while((i=read(fd,buff,sizeof(buff)-1))>0){
buff[i]='';
printf("%s",buff);
fflush(stdout);
}

close(fd);
exit(EXIT_SUCCESS);
}


ところで、これはLinuxだけでなくcygwinでもそのまま実行可能です。
cygwinでは/devの下をみてもデバイスファイルが見えないのですが、
実は存在しています。
com1が/dev/ttyS0にエミュレートされています。
cygwinおそるべし。

0 件のコメント:

コメントを投稿