利用WiringPi库进行十六进制串口通信
WiringPi库适用于树莓派、香橙派等开发板,这里记录一下利用WiringPi库进行十六进制串口通信的案例,具体如下:
代码功能简述
发送:在代码中sendBuf会存储特定的十六进制命令,执行程序后输入y,即会向串口发送sendBuf中的内容;
接收:若串口向开发板发送内容,开发板也会以十六进制的形式接收;
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
#include <wiringPi.h>
#include <wiringSerial.h>
#include <stdlib.h>
int fd;
void * Sendhandler()
{
char ch;
//这里数组中的内容可以改为自己需要发送的
unsigned char sendBuf[] = {
0xFD,0xFD,0xFB,0x01,0xDF};
int len = sizeof(sendBuf);
int i = 0;
while(1)
{
printf("\ninput y:");
ch = getchar();
if (ch =='y')
{
i = 0;
while(i != len)
{
serialPutchar(fd,sendBuf[i]);
i++;
}
}
}
}
void * Revhandler()
{
while(1)
while (serialDataAvail (fd))
{
//十六进制接收
printf ("%x\n", serialGetchar (fd)) ;
fflush (stdout) ;
}
}
int main ()
{
int count ;
unsigned int nextTime ;
pthread_t idSend;
pthread_t idRev;
//这里根据实际情况修改波特率和串口设备名
if ((fd = serialOpen ("/dev/ttyS5", 9600)) < 0)
{
fprintf (stderr, "Unable to open serial device: %s\n", strerror (errno)) ;
return 1 ;
}
if (wiringPiSetup () == -1)
{
fprintf (stdout, "Unable to start wiringPi: %s\n", strerror (errno)) ;
return 1 ;
}
//创建发送和接收两个线程
pthread_create(&idSend,NULL,Sendhandler,NULL);
pthread_create(&idRev,NULL,Revhandler,NULL);
while(1){
sleep(10);};
printf("\n");
return 0 ;
}