linux 系统下串口大多数读写都是字符流模式。如果要读取二进制数据时就需要特殊配置。如读取雷达上报的数据,数据就是二进制格式的。不能用字符流的形式去读取。
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <netdb.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <time.h>
#include <linux/types.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <asm/types.h>
#include <stdarg.h>
#include <sys/file.h>
#include <pthread.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <net/ethernet.h>
#include <signal.h>
#include <netinet/ip.h>
#include <signal.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <termios.h>
#define UART_DEV "/dev/ttyS5"
int uart_fd = -1;
void usart_init(void)
{
char command[256];
struct flock sharedLock;
int wrt;
struct termios s_opts;
uart_fd = open(UART_DEV, O_RDWR | O_NOCTTY | O_NDELAY);
if (uart_fd == -1) {
printf("Can't Open Serial %s\n", UART_DEV);
return ;
}
fcntl(uart_fd, F_SETFL, 0);
if (tcgetattr(uart_fd, &s_opts) != 0) {
printf("Get serial failed for %s!\n", UART_DEV);
close(uart_fd);
return ;
}
//cfmakeraw(&s_opts);
cfsetispeed(&s_opts, B115200);
cfsetospeed(&s_opts, B115200);
#if 1
s_opts.c_cflag &= ~(CSIZE);
s_opts.c_cflag |= CS8;/* 8位数据位 */
s_opts.c_cflag &= ~CSTOPB;/* 1位停止位 */
s_opts.c_cflag &= ~PARENB;/* 无奇偶校验 */
s_opts.c_iflag &= ~INPCK;/*禁用输入奇偶检测*/
s_opts.c_cflag |= (CLOCAL | CREAD);/* 启用接受,忽略modem 控制线 */
s_opts.c_cflag &= ~CRTSCTS;/* 禁用流控 */
s_opts.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
s_opts.c_oflag &= ~OPOST;
s_opts.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
#endif
tcflush(uart_fd, TCIOFLUSH);
if (tcsetattr(uart_fd, TCSANOW, &s_opts) != 0) {
printf("Setup serial failed for %s!\n",UART_DEV);
close(uart_fd);
return ;
}
}
int uart_recive_datas(uint8_t *buf_data,uint32_t buf_len)
{
int len = 0;
int i = 0;
len = read(uart_fd,buf_data,buf_len);
#if 1
printf("uart recive data: ");
for (i = 0; i < len; i++) {
printf("%02x ",buf_data[i]);
}
printf("\n");
#endif
return len;
}
void usart_send_datas(uint8_t *data,uint16_t length)
{
int ret = 0;
int i = 0;
ret = write(uart_fd,data,length);
#if 1
printf("uart send data: ",ret);
for (i = 0; i < ret; i++) {
printf("%02x ",data[i]);
}
printf("sucess\n");
#endif
}
int main(int argc , char **argv)
{
char data[4096] = {0};
usart_init();
while (1) {
memset(data,0,4096);
uart_recive_datas(data,4096);
}
}