Linux 下串口编程实例
如下代码实现了uart配置,同时封装了初始化函数、串口读、串口写以便移植,直接看代码吧
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#define TRUE 0
#define FALSE -1
unsigned char CharToHex(unsigned char bHex)
{
if((bHex>=0)&&(bHex<=9))
{
bHex += 0x30;
}
else if((bHex>=10)&&(bHex<=15))//Capital
{
bHex += 0x37;
}
else
{
bHex = 0xff;
}
return bHex;
}
unsigned char HexToChar(unsigned char bChar)
{
if((bChar>=0x30)&&(bChar<=0x39))
{
bChar -= 0x30;
}
else if((bChar>=0x41)&&(bChar<=0x46)) // Capital
{
bChar -= 0x37;
}
else if((bChar>=0x61)&&(bChar<=0x66)) //littlecase
{
bChar -= 0x57;
}
else
{
bChar = 0xff;
}
return bChar;
}
/**
*@brief 设置串口通信速率
*@param fd 类型 int 打开串口的文件句柄
*@param speed 类型 int 串口速度
*@return void*/
int speed_arr[] = { B38400, B19200, B9600, B4800, B2400, B1200, B300,
B38400, B19200, B9600, B4800, B2400, B1200, B300, };
int name_arr[] = {38400, 19200, 9600, 4800, 2400, 1200, 300,
38400, 19200, 9600, 4800, 2400, 1200, 300, };
void set_speed(int fd, int speed)
{
int i;
int status;
struct termios Opt;
tcgetattr(fd, &Opt);
for ( i= 0; i < sizeof(speed_arr) / sizeo

本文提供了一个Linux下串口编程的实例,包括uart配置、初始化函数、串口读写等功能的封装,便于移植。文中详细介绍了如何设置串口通信速率、数据位、停止位和校验位,并附带完整的代码示例。
最低0.47元/天 解锁文章
4419

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



