项目场景:
树莓派串口通信及数据丢失串口配置修改问题
问题描述
最近在用树莓派做智能家居,那必然是逃不过LD3320语音模块与树莓派之间的通讯问题,首先用串口助手和树莓派连接,写了一份代码开始测试
树莓派按照此图连接号:
写一份串口通信代码
#include<wiringPi.h>
#include<wiringSerial.h>
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>
#include<string.h>
void serialSetup()
{
if (-1 == wiringPiSetup())
{
printf("openSerial error\n");
exit(-1);
}
}
int main()
{
char buf[128] = {'\0'};
int serialDataCount = 0;
int fd;
if ((fd = serialOpen("/dev/ttyAMA0", 9600)) == -1)
{
exit(-1);
}
while (1)
{
serialDataCount = read(fd, buf, sizeof(buf));
if (serialDataCount == 0)
{
printf("no datas\n");
}
else{
printf("getDatas:%s\n",buf);
memset(buf, '\0', sizeof(buf));
serialDataCount = 0;
}
}
}
写好了确认代码没有问题,开始测试,却发现getDatas出现问题:
向树莓派发送 "keld",发现有时收不到data 排除代码中空格符问题后,发现串口助手中树莓派收到的login incorrect,这应该导致了获得数据与所发数据不同
原因分析:
不知道是不是login incorrect是不是问题的原因,查了好多资料,没有找到原因,后来问老师,说哪个是系统自己发的指令,需要修改串口配置,于是在网上一篇博文找到了答案 https://www.cnblogs.com/lulipro/p/5992172.html 修改串口配置
解决方案:
/* 修改 cmdline.txt文件 */
>cd /boot/
>sudo vim cmdline.txt
删除【】之间的部分
dwc_otg.lpm_enable=0 【console=ttyAMA0,115200】 kgdboc=ttyAMA0,115200 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline rootwait
/*修改 inittab文件 */
>cd /etc/
>sudo vim inittab
注释掉最后一行内容:,在前面加上 # 号
#T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100
sudo reboot 重启
完美解决啦!
串口可用,下一步语音模块发数据树莓派控制点灯搞起........