int open_port(int port) { int fd = -1; /* File descriptor for the port, we return it. */ int ret; char device[13] = {0}; /* ??? sizeof("/dev/ttyUSB0")=12 */
if (port < 1 || port > 4) error_ret("Sorry, the port number must be 1~4."); if (USB_SERIAL) sprintf(device, "/dev/ttyUSB%d", port-1); else sprintf(device, "/dev/ttyS%d", port-1); //printf("%s %d\n", device, sizeof(device));
fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY); if (fd == -1) unix_error_ret("Unable to open the port");
/* block */ ret = fcntl(fd, F_SETFL, 0); if (ret < 0) unix_error_ret("fcntl"); ret = isatty(STDIN_FILENO); if (ret == 0) error_ret("Standard input is not a terminal device."); debug_msg("Open the port success!\n"); return fd; }
int setup_port(int fd, int speed, int data_bits, int parity, int stop_bits) { int speed_arr[] = {B115200, B9600, B38400, B19200, B4800}; int name_arr[] = {115200, 9600, 38400, 19200, 4800}; struct termios opt; int ret=-1; int i=0; int len=0;
ret = tcgetattr(fd, &opt); /* get the port attr */ if (ret < 0) unix_error_ret("Unable to get the attribute");
opt.c_cflag |= (CLOCAL | CREAD); /* enable the receiver, set local mode */ opt.c_cflag &= ~CSIZE; /* mask the character size bits*/
/* baud rate */ len = sizeof(speed_arr) / sizeof(int); for (i = 0; i < len; i++) { if (speed == name_arr[i]) { cfsetispeed(&opt, speed_arr[i]); cfsetospeed(&opt, speed_arr[i]); } if (i == len) error_ret("Unsupported baud rate."); } /* data bits */ switch (data_bits) { case 8: opt.c_cflag |= CS8; break; case 7: opt.c_cflag |= CS7; break; default: error_ret("Unsupported data bits."); }
int main(void) { int fd; int ret; //signal(SIGINT, sig_handle); fd = open_port(1); /* open the port(com1) */ if (fd < 0) exit(0); ret = setup_port(fd, 115200, 8, 'N', 1); if (ret<0) exit(0);
ret = pthread_create(&write_tid, NULL, write_port_thread, (void*)fd); if (ret < 0) unix_error_exit("Create write thread error.");
#if 0 ret = pthread_create(&read_tid, NULL, read_port_thread, (void*)fd); if (ret < 0) unix_error_exit("Create read thread error."); #endif
下面是测试图示。图1为发送数据,22表示已发送字符串的长度。 图2为minicom接收数据,“Are you going to die?”没别的意思,它是《豪门夜宴》中曾志伟、刘嘉玲、张曼玉唱英文版《香夭》时嘉玲姐唱的第一句歌词,由beyond伴奏。 (接收的第4行出现了乱码,说明用镊子短接串口不太稳定)