wiringOP-master/examples/serialTest.c中,wiringPi库中自带的串口程序:
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <wiringPi.h>
#include <wiringSerial.h>
int main ()
{
int fd ;
int count ;
unsigned int nextTime ;
if ((fd = serialOpen ("/dev/ttyS2", 115200)) < 0)//打开在/dev.ttyS2路径下的文件,波特率配置成115200,如果返回值为-1说明打开失败
{
fprintf (stderr, "Unable to open serial device: %s\n", strerror (errno)) ;
return 1 ;
}
if (wiringPiSetup () == -1)//初始化wiringPi库
{
fprintf (stdout, "Unable to start wiringPi: %s\n", strerror (errno)) ;
return 1 ;
}
nextTime = millis () + 300 //这个函数返回 一个 从你的程序执行 wiringPiSetup 初始化函数(或者wiringPiSetupGpio ) 到 当前时间 经过的 毫秒数。返回类型是unsigned int,最大可记录 大约49天的毫秒时长。
for (count = 0 ; count < 256 ; )
{
if (millis () > nextTime)
{
printf ("\nOut: %3d: ", count) ;
fflush (stdout) ;//fflush(stdout)刷新标准输出缓冲区,把输出缓冲区里的东西打印到标准输出设备上。
serialPutchar (fd, count) ;//将字符输出到串口
nextTime += 300 ;
++count ;
}
delay (3) ;
while (serialDataAvail (fd))
{
printf (" -> %3d", serialGetchar (fd)) ;//获取串口的数据
fflush (stdout) ;
}
}
printf ("\n") ;
return 0 ;
(90条消息) fflush(stdio)、fflush(stdout)详解_hanxp001的博客-CSDN博客
根据官方的wiringPi库修改接收和发送串口数据
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
#include <wiringPi.h>
#include <wiringSerial.h>
#include <stdlib.h>
#include <unistd.h>
int fd ;
void* SendHandler()
{
char *SendBuf;
SendBuf = (char *)malloc(32*sizeof(32));
while(1)
{
memset(SendBuf,'\0',32);
scanf("%s",SendBuf);
while(*SendBuf != NULL)
{
serialPutchar(fd, *SendBuf++);
}
}
}
void* RevHandler()
{
while(1)
{
while (serialDataAvail(fd))
{
printf ("%c", serialGetchar(fd)) ;
fflush (stdout) ;
}
}
}
int main ()
{
int count ;
unsigned int nextTime ;
pthread_t idsend;//定义线程标识符
pthread_t idrev;//定义线程标识符
if ((fd = serialOpen ("/dev/ttyS5", 115200)) < 0)
{
fprintf (stderr, "Unable to open serial device: %s\n", strerror (errno)) ;
return 1 ;
}
pthread_create(&idsend,NULL,SendHandler,NULL);//创建线程1发送数据
pthread_create(&idrev,NULL,RevHandler,NULL);//创建线程2接收数据
if (wiringPiSetup () == -1)
{
fprintf (stdout, "Unable to start wiringPi: %s\n", strerror (errno)) ;
return 1 ;
}
while(1)
{
sleep(10);
}
printf ("\n") ;
return 0 ;
}
修改过后通过创建线程来接收和发送串口数据
pthread_create(&idse