[技術] 在Linux上用C撰寫RS-232通訊程式

Written on 12:41 下午 by Yu Lai

最近工作上玩到的,總結一下當Note吧。
主要是Ref: Serial Programming Guide for POSIX Operating Systems
配合pthread把收跟送的部份分開,
以下是收的部份。

struct tty_q {
int len;
unsigned char buff[TTY_Q_SZ]; /* TTY_Q_SZ=1024 */
} tty_q;

int tty_fd;
pthread_mutex_t tty_mutex;

void * rs232com(void *arg) {

int c=0, len;
struct termios oldtio, newtio;
char buf[256];

pthread_detach(pthread_self());
pthread_mutex_init(&tty_mutex, NULL);

/* Open the rs232 port */
tty_fd = open(TTYDEVICE, O_RDWR|O_NOCTTY);
if (tty_fd < 0) {
perror(TTYDEVICE);
exit(1);
}

/* Get the current options */
tcgetattr(tty_fd, &oldtio);

/* Set new options */
bzero(&newtio, sizeof(newtio));
newtio.c_cflag = BAUDRATE|CS8|CLOCAL|CREAD;
newtio.c_iflag = IGNPAR;
newtio.c_oflag = 0;
newtio.c_lflag = ICANON;

/* Set the options */
tcflush(tty_fd, TCIFLUSH);
tcsetattr(tty_fd, TCSANOW, &newtio);

while(1) {
len = read(tty_fd, buf, 255);
buf[len]=0;

MCP_LOG("RS-232 recv, len=%03d, buf=%s\n", len, buf);

pthread_mutex_lock(&tty_mutex);

if(tty_q.len + len > TTY_Q_SZ) {
memset(tty_q.buff, 0, TTY_Q_SZ);
tty_q.len = 0;
}

memcpy(&tty_q.buff[tty_q.len], buf, len);
tty_q.len += len;

pthread_mutex_unlock(&tty_mutex);
}
}

而送的部份在這裡。
int rs232send(U8 * buf) {

pthread_mutex_lock(&tty_mutex);

memset(tty_q.buff, 0, TTY_Q_SZ);
tty_q.len = 0;

pthread_mutex_unlock(&tty_mutex);

return write(tty_fd, buf, strlen(buf));

}

If you enjoyed this post Subscribe to our feed

No Comment

張貼留言