Linux监控串口数据并写入文件-C语言demo

  • Post author:
  • Post category:linux


程序是基于Linux操作系统,监控串口是否有数据,如果有数据就写入到文件系统中。Demo涉及串口初始化,poll函数监控,以及文件读写操作。

#include <termios.h>
#include <stdio.h>
#include <poll.h>
#include <fcntl.h>
#include <signal.h>
#include <stdlib.h>

#define MAX_MSG_SIZE 1024*1024+1
#define NEW_FILE "/mnt/userdata/uart_data_%s"

char buf[MAX_MSG_SIZE + 1]={0};
FILE *fp = NULL;

void exit_handle(int signo) 
{
	int fd = -1;
    printf("kill app!!!\n");
	fflush(fp);
    fd = fileno(fp);
    fsync(fd);
    fclose(fp);
    exit(0);
}


void main(char argc, char *argv[])
{
	int uart_fd                   = -1;
	int num_read                  = 0;
	int ret                       = 0;
	struct termios option;
	struct pollfd pollinfo        = {0};
    char a[100];

	signal(SIGINT, exit_handle);
	snprintf(a, 90, NEW_FILE, argv[1]);

    fp = fopen(a, "w+");
	if(fp == NULL)
	{
	  printf("new file error\n");
	  return;
	}
	
	
	pollinfo.events = POLLIN | POLLPRI | POLLERR | POLLHUP;
	
	uart_fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
	
	if (uart_fd < 0)
	{
	  printf("open uart_fd file error\n");
	  return;
	}
	
	pollinfo.fd = uart_fd;

	if (tcgetattr(uart_fd, &option) < 0)
	{
	  printf("Attempt to get attr error\n");
	}
	else
	{
	  printf("get attr ok\n");

	  option.c_cc[VTIME] = 0;    //set timeout
	  option.c_cc[VMIN] = 1;     // define the minimum bytes data to be readed

	  option.c_cflag &= ~CSIZE;
	  option.c_cflag |= (CS8 | CLOCAL | CREAD);
	  option.c_cflag &= ~PARENB;
	  option.c_cflag &= ~CSTOPB;
	  option.c_iflag = IGNPAR;
	  option.c_cflag &= ~PARODD;
	  option.c_iflag &= ~INPCK; /* Enable parity checking */
	  option.c_oflag = 0;
	  option.c_lflag = 0;

	  option.c_cflag &= ~(IXOFF | IXON | IXANY);
	  option.c_cflag &= ~CRTSCTS;

	  cfsetospeed(&option, B460800);
	  cfsetispeed(&option, B460800);
	  
	  tcflush(uart_fd, TCIOFLUSH);
	  if (tcsetattr(uart_fd, TCSANOW, &option) < 0)
	  {
		  printf("Attempt to set attr error\n");
	  }
	}
	
	while(1)
	{
		pollinfo.revents = 0;
		ret = poll(&pollinfo, 1, -1);
		
		if (pollinfo.revents & POLLIN)
		{
		  num_read = read(uart_fd, buf, MAX_MSG_SIZE);
		  printf("read uart_fd num %d\n", num_read);

		  if (num_read > 0)
		  {
			fwrite(buf, num_read, 1, fp);
		  }
		}
	}
}



版权声明:本文为lihuan680680原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。