我有一个Arduino电路板,想要以自定义baud速率读取使用USB进行吐出的数据。黑客攻击Arduino建议的一些代码,我得到了这个C代码:
int serialport_init(const char* serialport, int baud)
{
struct termios toptions;
int fd;
printf("init_serialport: opening port %s @ %d bps\n", serialport,baud);
fd = open(serialport, O_RDWR | O_NOCTTY | O_NDELAY);
serialPortPointer = fd;
if (fd == -1)
{
printf("Unable to open port when initialising hardware'n");
return -1;
}
if (tcgetattr(fd, &toptions) < 0)
{
printf("Couldn't get term attributes when initialising hardware\n");
return -1;
}
speed_t brate = baud; // let you override switch below if needed
switch(baud) {
case 4800: brate=B4800; break;
case 9600: brate=B9600; break;
case 14400: brate=B14400; break;
case 19200: brate=B19200; break;
case 28800: brate=B28800; break;
case 38400: brate=B38400; break;
case 57600: brate=B57600; break;
case 115200: brate=B115200; break;
}
cfsetispeed(&toptions, EXTA);
cfsetospeed(&toptions, EXTA);
// 8N1
toptions.c_cflag &= ~PARENB;
toptions.c_cflag &= ~CSTOPB;
toptions.c_cflag &= ~CSIZE;
toptions.c_cflag |= CS8;
// no flow control
toptions.c_cflag &= ~CRTSCTS;
toptions.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines
toptions.c_iflag &= ~(IXON | IXOFF | IXANY); // turn off s/w flow ctrl
toptions.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // make raw
toptions.c_oflag &= ~OPOST; // make raw
// see: http://unixwiz.net/techtips/termios-vmin-vtime.html
toptions.c_cc[VMIN] = 0;
toptions.c_cc[VTIME] = 20;
if(tcsetattr(fd, TCSANOW, &toptions) < 0)
{
printf("Couldn't set term attributes when initialising hardware\n");
return -1;
}
return fd;
}
问题是termios.h
文件不支持31250(MIDI)波特率...如果我尝试输入31250作为波特率,此函数返回-1并说“无法设置术语初始化硬件时的属性“(它在最后失败)。
那么 - 我怎么能用C语言或任何其他语言编写一个以我想要的波特率读取数据的程序? termios.h是否支持自定义波特率?
我真的只想读取串口上的数据 - 没有别的。