[英]wrong data in Serial comunication Arduino-Raspberry with C and sysfs library
我正在尝试使Arduino和Raspberry通信。 我在Raspberry上有一个使用sysfs库的C程序和一个C-Arduino程序。
我该做什么:Arduino已经在板子上拥有了自己的编译程序(在同一Raspberry上),而不是在Raspberry上编译该程序并启动它。
问题:我从Raspberry上获取数据,但延迟了一个Raspberry输入,如下面的代码所示。
Type: a
OFFXX
Type: s
ONFXX
Type: a
OFFXX
Type: s
ONFXX
Type: s
OFFXX
Type: a
OFFXX
我第一次总是得到OFFXX
arduino代码:
int led = 13;
void setup() {
pinMode(led, OUTPUT);
Serial.begin(57600);
}
void loop() {
if (Serial.available() > 0) {
char comando = toLowerCase(Serial.read());
if (comando == 'a') {
digitalWrite(led, HIGH);
Serial.print("ON");
}
else {
digitalWrite(led, LOW);
Serial.print("OFF");
}
}
}
和树莓代码:
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(){
int fd = open("/dev/ttyS0", O_RDWR);
if (fd == -1) {
perror("/dev/ttyS0");
return 1;
}
char msg[] = "a";
char rx[] = "XXXXX";
struct termios tios;
tcgetattr(fd, &tios);
// disable flow control and all that, and ignore break and parity errors
tios.c_iflag = IGNBRK | IGNPAR;
tios.c_oflag = 0;
tios.c_lflag = 0;
cfsetspeed(&tios, B57600);
tcsetattr(fd, TCSAFLUSH, &tios);
// the serial port has a brief glitch once we turn it on which generates a
// start bit; sleep for 1ms to let it settle
usleep(1000);
// output to serial port
while(1){
printf("Type: ");
scanf("%s", msg);
write(fd, msg, strlen(msg));
read(fd, rx, strlen(rx));
printf("%s\n", rx);
}
}
USB电缆和GPIO都存在此问题
编辑:另一个问题:为什么输出记得以前初始化的最后一个字符?
在RAW模式下打开Raspberry端的串行端口。 使用以下代码段以RAW模式打开端口:
int fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
if(fd == -1)
{
return -1;
}
else
{
struct termios new_termios;
struct termios orig_termios;
tcgetattr(fd, &orig_termios);
memcpy(&new_termios, &orig_termios, sizeof(new_termios));
cfmakeraw(&new_termios);
cfsetispeed(&new_termios, B57600);
cfsetospeed(&new_termios, B57600);
tcsetattr(fd, TCSANOW, &new_termios);
}
希望这对您来说是完美的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.