Created
November 11, 2014 04:09
-
-
Save maripiyoko/c6e56759e7c30e5497b1 to your computer and use it in GitHub Desktop.
serial port read by c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <fcntl.h> | |
#include <string.h> | |
#include <termios.h> | |
#include <time.h> | |
#define DEV_NAME "/dev/tty.usbmodem621" | |
#define BAUD_RATE B9600 | |
#define BUFF_SIZE 4096 | |
void serial_init(int fd) { | |
struct termios tio; | |
memset(&tio, 0, sizeof(tio)); | |
tio.c_cflag = CS8 | CLOCAL | CREAD; | |
tio.c_cc[VTIME] = 100; | |
// ボーレートの設定 | |
cfsetispeed(&tio, BAUD_RATE); | |
cfsetospeed(&tio, BAUD_RATE); | |
// デバイスに設定を行う | |
tcsetattr(fd, TCSANOW, &tio); | |
} | |
int main(int argc, char **argv) { | |
int fd; | |
int i,j; | |
int len; // データ数(バイト) | |
unsigned char buffer[BUFF_SIZE], in_data[BUFF_SIZE]; | |
printf("start serial port read example..\n"); | |
// デバイスファイル(シリアルポート)オープン | |
//fd = open(DEV_NAME, O_RDWR); // この書き方だとopenできない | |
fd = open(DEV_NAME, O_RDWR | O_NONBLOCK ); | |
if(fd<0) { // デバイスオープンに失敗 | |
printf("ERROR on device open\n"); | |
exit(1); | |
} | |
printf("init serial port\n"); | |
serial_init(fd); // シリアルポートの初期化 | |
printf("start main loop...\n"); | |
j=0; | |
// メインの無限ループ | |
while(1) { | |
len = read(fd, buffer, BUFF_SIZE); // 受信待ち | |
if(len==0) { | |
continue; | |
} | |
if(len<0) { // I/Oエラー | |
printf("%s: ERROR\n", argv[0]); | |
perror(""); | |
exit(2); | |
} | |
for(i=0; i<len; i++) { | |
printf("%02X", buffer[i]); // 受信データを16進数で表示 | |
i++; | |
in_data[i] = buffer[i]; | |
} | |
if((in_data[j - 1] == 0x0a) || (in_data[j - 1] == 0)) { | |
in_data[j - 1] = 0x0a; | |
in_data[j] = 0; | |
printf("\n read-data=%s\n",&in_data[0]); | |
write(fd,&in_data[0],strlen(&in_data[0])); | |
j = 0; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment