作者brianpapa (^__^)
看板LinuxDev
标题[问题] RS232
时间Thu Nov 8 09:07:04 2007
小弟现在写了一支,利用RS232让两块板子互相沟通的程式
下面是我的程式码
#include <stdlib.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <limits.h>
#define SERIAL_PORT "/dev/ttyS1"
#define BAUD_RATE B115200
int main()
{
int fd, end_of_comm=1;
struct termios termios_current, termios_new;
/* Open Serial Port */
if( (fd = open(SERIAL_PORT, O_RDWR | O_NOCTTY | O_NONBLOCK)) < 0 ) {
/* Check Port Name */
printf("Error when open serial port file:%s\n", SERIAL_PORT);
return 0;
}
tcgetattr(fd, &termios_current);
/* Setup Serial Port */
bzero(&termios_new, sizeof(termios_new)); // Clear Setting
cfmakeraw(&termios_new);
termios_new.c_cflag = BAUD_RATE; // Baud Rate
termios_new.c_cflag |= CLOCAL | CREAD;
termios_new.c_cflag &= ~CSIZE;
termios_new.c_cflag |= CS8; //
8bit
termios_new.c_cflag &= ~PARENB; // no parity
bit
termios_new.c_cflag &= ~CSTOPB; // no stop
bit
tcflush(fd, TCIFLUSH);
/* Set to Hardware Register */
tcsetattr(fd, TCSANOW, &termios_new);
/* Start Communication */
while (end_of_comm) {
int rec;
char buf[129];
rec = read(fd, buf, 128);
buf[rec] = '\0';
printf("Recv: %s\nSent: ", buf);
scanf("%s", buf);
rec = write(fd, buf, strlen(buf));
if ( buf[0] == '%' ) end_of_comm = 0;
}
tcsetattr(fd, TCSANOW, &termios_current);
return 0;
}
但是,两块板子用跳线连接後,并不如预期中的能互相传送东西
请问各位大大们,能帮帮我吗??我不知道问题是出在哪
两块板子都是执行这支程式!!
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.129.20.96
1F:推 yhuiyang:nonblocking的read在没读到东西时,return -1,设定EAGAIN 11/08 23:39
2F:→ yhuiyang:所以buf[rec]会segmentation fault吗? 11/08 23:42
3F:→ yhuiyang:另外baud rate是否仍须用cfset[io]speed()来设定? 11/08 23:43