之前,利用RXD,TXD回环来读取发送的数据,原先的初始化有问题(见异常版),经常中间夹杂莫名的数据,改用下面的初始化和发送、接收函数,一切正常了。两个还未进行对比,等有空闲的时候做下对比。
#include <termios.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <assert.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
/* the maximum number of ports we are willing to open */
#define MAX_PORTS 4
/*this array hold information about each port we have opened */
struct PortInfo{
int busy;
char name[32];
int handle;
};
struct PortInfo ports[MAX_PORTS];
/*
** Function: OpenCom
**
** Description:
** Opens a serial port with default parameters
**
** Arguments:
** portNo - handle used for further access
** deviceName - the name of the device to open
**
** Returns:
** -1 on failure
*/
int OpenCom(int portNo, const char deviceName[],long baudRate)
{
return OpenComConfig(portNo, deviceName, baudRate, 1, 8, 1, 0, 0);
}
/*
*/
long GetBaudRate(long baudRate)
{
long BaudR;
switch(baudRate)
{
case 115200:
BaudR=B115200;
break;
case 57600:
BaudR=B57600;
break;
case 19200:
BaudR=B19200;
break;
case 9600:
BaudR=B9600;
break;
case 8777:
BaudR = B8777;
break;
default:
BaudR=B0;
}
return BaudR;
}
/*
** Function: OpenComConfig
**
** Description:
** Opens a serial port with the specified parameters
**
** Arguments:
** portNo - handle used for further access
** deviceName - the name of the device to open
** baudRate - rate to open (57600 for example)
** parity - 0 for no parity
** dataBits - 7 or 8
** stopBits - 1 or 2
** iqSize - ignored
** oqSize - ignored
**
** Returns

本文介绍了一种在ARM Linux环境下实现串口通信的正确方法,包括串口初始化、发送和接收函数,解决了之前存在的数据错误问题。通过示例代码展示了如何打开、配置、关闭串口,并进行数据读写操作。
最低0.47元/天 解锁文章
1121

被折叠的 条评论
为什么被折叠?



