vs上写一段c语言编写的串口线程接收例程
时间: 2023-05-31 11:05:43 浏览: 262
基于VC的串口收发文件例程
5星 · 资源好评率100%
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <pthread.h>
#define BAUDRATE B9600
#define SERIAL_PORT "/dev/ttyUSB0"
#define BUFFER_SIZE 256
//串口文件描述符
int serial_fd;
//接收缓冲区
char recv_buffer[BUFFER_SIZE];
//线程退出标志
int thread_exit_flag = 0;
//串口接收线程函数
void *serial_recv_thread(void *arg) {
while(!thread_exit_flag) {
int recv_len = read(serial_fd, recv_buffer, BUFFER_SIZE);
if(recv_len > 0) {
printf("Received data: %s", recv_buffer);
memset(recv_buffer, 0, BUFFER_SIZE);
}
}
pthread_exit(NULL);
}
int main() {
//打开串口
serial_fd = open(SERIAL_PORT, O_RDWR | O_NOCTTY | O_NDELAY);
if(serial_fd < 0) {
perror("open serial port failed");
return -1;
}
//配置串口
struct termios options;
tcgetattr(serial_fd, &options);
cfsetispeed(&options, BAUDRATE);
cfsetospeed(&options, BAUDRATE);
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CRTSCTS;
tcsetattr(serial_fd, TCSANOW, &options);
//创建串口接收线程
pthread_t recv_thread;
if(pthread_create(&recv_thread, NULL, serial_recv_thread, NULL)) {
perror("create serial recv thread failed");
return -1;
}
//主线程等待串口接收线程退出
pthread_join(recv_thread, NULL);
//关闭串口
close(serial_fd);
return 0;
}
阅读全文