前面了解过如何利用串口进行定时输出helloworld,下面我们利用串口进行读取。我们要区分下载用的控制串口和调试用的串口3,他们功能是不一样的。首先我们要用的是void
memset(void *s,int c,size_t
n)函数,这个函数时对指针的空间进行初始化为某一个数值的,因为我们新开的空间内容有可能是不确定的。因此需要全部初始化为0.读取串口主要是用read函数,返回的值表示读取的内容的大小读取完了之后就可以进行输出了,但是从中我们也用到了sprintf函数进行格式化输出。
#include
#include
#include
#include
#include
#include
#include
#include
int
set_opt(int,int,int,char,int);//进行串口的波特率,停止位等的设置,该函数的内容前面有,就不重复了
int main()
{
int fd;
const char* uart3="/dev/ttySAC3";//确定控制哪个串口
char buffer[1024];
if((fd=open(uart3,O_RDWR|O_NOCTTY|O_NDELAY))<0)
{
printf("open uart 3 fail");
}
else
{
set_opt(fd,115200,8,'N',1);//对串口进行设置
write(fd,"Please input some words",strlen("Please input some
words"));
int num;
while(1)
{
memset(buffer,0,1024);
num=read(fd,buffer,1024);//读取串口的内容
if(num!=0)
{
printf(buffer);//输出到控制台
printf("\r\n");
write(fd,"\n\r",strlen("\r\n"));
sprintf(buffer,"input char num is %d",num);//进行格式化输出
write(fd,buffer,strlen(buffer));
write(fd,"\n\r",strlen("\r\n"));//输出到串口
}
}
}
return 0;
}
运行结果如下,完成串口的读取或者输出,但是目前有bug,就是一次读只能读取4个字符,因为他不断的循环,而且字符不是一次到达,因此他会读取4个立马就进行显示,从而产生截断。