【发布时间】:2014-02-26 10:27:06
【问题描述】:
我正在尝试创建一个 linux ubuntu 程序,该程序将从 tty 串行端口(Windows 中的 COM 端口)读取数据。我没有使用 USB 适配器,而是使用实际的 COM 端口。到目前为止,这是我的通信代码:
int OpenPort(void)
{
int fd; // file description for sp
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_SYNC);
if(fd == -1) // port not opened
{
printf("Error:\n%s.\n", strerror(errno));
}
else
{
fcntl(fd, F_SETFL, 0);
printf("Success.\n");
}
return(fd);
} // Open sp
void Communicate(void)
{
struct termios settings;
tcgetattr( fd, &settings );
cfsetispeed(&settings, B9600); // Set bouds
cfsetospeed(&settings, B9600);
settings.c_cflag &= ~PARENB; // set no parity, stop bits, data bits
settings.c_cflag &= ~CSTOPB;
settings.c_cflag &= ~CSIZE;
settings.c_cflag |= CS8;
tcflush( fd, TCIFLUSH );
if (tcsetattr(fd, TCSAFLUSH, &settings)!= 0)
{
printf("Error message");
}
//Create byte array
unsigned char send_bytes[] = { 0x1, 0x6, 0x2, 0xAA, 0x2, 0x3, 0xB8, 0x4 };
write(fd, send_bytes, sizeof(send_bytes)); // Send data
printf("Data sent. \n");
char buffer[64]; // buffer to receive data
printf("I'm reading data...\n");
int n = read(fd, buffer, sizeof(buffer));
if (n < 0)
printf("Failed to read\n");
int i;
printf("Showing data...\n");
for(i=0; i<sizeof(buffer); i++)
{
printf("Hex: %x\n", buffer[i]);
}
printf("Closing...\n");
close(fd);
printf("All done!\n");
}
我这里有几个问题:
- 在我运行程序后,一旦它正确执行,但当我尝试再次运行它时,它会在“我正在读取数据...”处停止,并且即使在我重新启动计算机后也不会启动。一段时间后,它允许我再次执行程序。
- 程序返回数据后,它应该向我发送十六进制数据,例如 A7、9F 等,但这会给我整数值。
- 我应该以及如何清除缓冲区数组以释放内存
谁能帮助解决这些问题?
【问题讨论】:
标签: c linux serial-port tty