编程Linux下多串口编程技术实现(linux多串口)
多串口编程是指在Linux操作系统下对多个串口进行编程,实现多串口并发通信的目的,这一技术广泛应用在无线通信、机器人控制、测试调试等领域中。下面以Linux下的多个串口编程技术的实现进行阐述。
为实现Linux下的多串口编程,第一步需要调查多串口框架,比如TMUX,它支持Linux下的多个串口通信。第二步,构建多串口的驱动代码,对每个串口的硬件进行配置,例如设置波特率、校验位、字长等等,可以通过ioctl()函数来完成。第三步,编写多线程应用程序,不同线程分别用于收发数据,或者可以用单线程,调用select函数来监视指定的串口是否有数据来,以此来实现多串口的并发收发。
下面简单给出一段示例代码,来实现多串口并发通信。
“`cpp
//*****************************************************
// Name: Multi-Port Communication Application
// Purpose: simple multi-port communication in Linux
// Developed By: Your Name
// Created On: Date
//*****************************************************
#include
#include
#include
#include
#include
#include
#include
#include
//Setbaudrate参数
#define B115200 5
//考虑最多N个串口
#define MAX_PORT 30
#define frame_length 40
unsigned char buffer[frame_length];
//全局变量,默认串口数量
int nPort=0;
int ports[MAX_PORT];
//初始化函数
int init(void);
//多线程(也可以是单线程)读取多个串口数据
void *readThreadFunc(void* args);
int main(void)
{
int retval=0;
int i=0;
pthread_t th_read[nPort];
//初始化,打开串口,设置串口参数,准备工作
retval = init();
if(retval
{
printf(“Error initializing serial ports\n”);
return -1;
}
//创建读线程
for(i=0;i
{
retval = pthread_create(&th_read[i],NULL,readThreadFunc,(void*)(&ports[i]));
if(retval != 0)
{
printf(“Cannot create read thread %d\n”,i);
return -1;
}
}
for(i= 0;i
{
pthread_join(th_read[i],NULL);
}
close_serial_port();
return 0;
}
int init(void)
{
//初始化,打开串口,设置串口参数,准备工作
char buf[128];
int fd,i;
nPort = 0;
while( nPort
{
sprintf(buf,”/dev/ttyS%d”,nPort);
if((fd=open(buf,O_RDWR))
break;
i = fcntl(fd, F_GETFL);
fcntl(fd, F_SETFL, i | O_NONBLOCK);
//设置波特率
if (SetBaudRate(fd,B115200)
{
break;
}
ports[nPort] = fd;
nPort ++;
}
return 0;
}
//将一个字节的数据发送到指定串口
int write_byte(int fd,unsigned char send_byte)
{
unsigned char buffer[2];
int num_written;
memset(&buffer, 0, sizeof(buffer));
buffer[0] = send_byte;
num_written = write(fd, buffer, 1);
if (num_written != 1) //其实可以省略
return -1;
return num_written;
}
//设置串口的波特率
int SetBaudRate(int fd,int baudrate)
{
intbrate;
int flg_brate;
struct termios options;
cfmakeraw(&options);
switch (baudrate) {
case 0:
flg_brate = B0;
intbrate = 0;
break;
case 50:
flg_brate = B50;
intbrate = 50;
break;
case 75:
flg_brate =B75;
intbrate =75;
break;
case 110:
flg_brate = B110;
intbrate = 110;
break;
case 134:
flg_brate = B134;
intbrate = 134;
break;
case 150:
flg_brate = B150;
intbrate = 150;
break;
case 200:
flg_brate = B200;
intbrate = 200;
break;
case 300:
flg_brate = B300;
intbrate = 300;
break;
case 600:
flg_brate = B600;
intbrate = 600;
break;
case 1200:
flg_brate = B1200;
intbrate = 1200;
break;
case 1800:
flg_brate = B1800;
intbrate = 1800;
break;
case 2400:
flg_brate = B2400;
intbrate=2400;
break;
case 4800:
flg_brate = B4800;
intbrate =