linux 串口驱动与应用(二)

后面回来补充的很重要的一句话,串口是流的方式发送,读取数据,不是包,这很重要,当去读取1000个字节所谓一包时,如果是非阻塞的,不一定能读到1000个,如果是阻塞的,需要一种等待。
一般读取传感器,不会去阻塞,如果读取固定字节,可能读不到这么多,这时候容易犯错,判断字节没有那么长,而丢弃,这是非常愚蠢的,没有搞清串口是流,不是包,如一个gsensor一直在发数据,以0x63开头,64个字节为一包发送出来,这时去读100个字节,如果能读到大于64个字节一包的数据,则去找63开头的一包,如果不能小于64个,则丢弃,这样效率是非常低的,
所以,需要把数据读到缓存器,一个也不能丢,读取多少个,就扔进缓存区,去找一包数据,其实和tcp一样,是流的方式,tcp一样,按流的方式发送,读取,不一定能读到想要的数据长度,不能丢弃,需拼接起来。udp是可以按包发送读取的,面向报文的。tcp,uart是面向流的。

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <linux/fs.h>
#include <linux/gpio.h>
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <string.h>

#define bufsize 202
#define filename “/dev/ttyAMA2”

#define Ture 1
#define False 0

#if 1
typedef struct // 60 bytes
{
unsigned int time;
int pose_translation[3];
unsigned short int pose_rotation[9];
unsigned short int frameNo;
short int accelData[3];
short int gyroData[3];
short int magData[3];
unsigned char device_map_state;
unsigned char confidence_level;
unsigned char reserved[4];
} HIDInfoStruct;
#endif

int g_fd1 = -1;
static unsigned char g_device_status = False;
int Reinitialize_HeadDisplay = False;

int pitch=0,yaw=0,roll=0;

unsigned short int pitch_high=0,pitch_low=0;
unsigned short int yaw_high=0,yaw_low=0;
unsigned short int roll_high=0,roll_low=0;

int Start_Read_Head_Display_Commond();
int Find_Valid_Data(char *buf_source ,char *buf_destine);
int Stop_Head_Display();

int open_Uart2()
{
g_fd1 = open(filename, O_RDWR);
if (g_fd1 < 0) {
printf(“app open %s fail \r\n”, filename);
return -1;
} else {
printf(“app open %s success\r\n”,filename);
}
return 1;
}

int Uart2_Init()
{
struct termios options;

if(tcgetattr(g_fd1,&options)  !=  0) {  
	printf("get serial attibute fail\r\n");
	close(g_fd1);     
	return(-1);   
}	

cfsetispeed(&options, B115200);   
cfsetospeed(&options, B115200);   

//set control model 
	options.c_cflag |= CLOCAL;  
	options.c_cflag |= CREAD;
options.c_cflag &= ~CRTSCTS;  

	//select data bit   
	options.c_cflag &= ~CSIZE; 	
options.c_cflag |= CS8;  

//select parity bit   
    options.c_cflag &= ~PARENB;   
    options.c_iflag &= ~INPCK;

// set stopbit  
options.c_cflag &= ~CSTOPB;  

//set raw data output 
options.c_oflag &= ~OP
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值