简体   繁体   English

Raspberry和Arduino来回交谈

[英]Raspberry and Arduino talking back and forth

I'm working on a project in which I am using an Arduino to simulate another device that will be connected to the Raspberry. 我正在一个项目中,我正在使用Arduino模拟将连接到Raspberry的另一台设备。 I have managed to do get the Raspberry to control the Arduino (by blinking some LED's in a pattern the Pi controlled). 我设法做到了让Raspberry控制Arduino(通过以Pi控制的模式闪烁一些LED)。 Now I'm looking to exchange data back and forth and have written programs for the Pi and Arduino that should have them receiving a number and then adding 1 to that number and send it back. 现在,我正在寻找来回交换数据的方法,并为Pi和Arduino编写了程序,应该让它们接收一个数字,然后在该数字上加1并发送回去。

Raspberry Pi: 树莓派:

import serial
import time 
ser = serial.Serial('/dev/ttyACM0',9600)
time.sleep(1)
var = b'0'
var2 = b'1'
while 1:
    time.sleep(0.5)
    ser.write(var)
    var = ser.read(ser.inWaiting()) #Wait for Arduino to respond
    print(var)
    var = var + var2
    print('2') #Check print

Arduino: 的Arduino:

const int ledPin = 12;
const int ledPin2 = 11;
int n;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  digitalWrite(ledPin2, LOW);
  Serial.begin(9600);
  n = 0;
}

void loop() {
  while(Serial.available() == 0){
    digitalWrite(ledPin, HIGH); //Check LED
  }
  n = Serial.read() - '0';
  digitalWrite(ledPin, LOW);
  n = n + 1;
  Serial.print(n);
}

The resulting print out in python is: 在python中输出的结果是:

b''
2
b'1'
2
b'2'
2
b'22'
2
b'32'
2
b'332'
2
b'432'
2

And so on. 等等。 This is not really the sequence I was expecting (1,3,5,7,9,11... Because we start at 0 and print when Arduino have added). 这并不是我期望的顺序(1,3,5,7,9,11 ...因为我们从0开始并在Arduino添加后打印)。

Hope that someone can help. 希望有人能帮忙。 Thank you in advance ^^ 预先谢谢^^

ser.read presumably returns a string, which results in (for example) "1" + "2" (aka "12" ). ser.read可能会返回一个字符串,该字符串将导致(例如) "1" + "2" (也称为"12" )。 Wrap it in int(): var = int(ser.read(ser.inWaiting())) 将其包装在int()中: var = int(ser.read(ser.inWaiting()))

The Arduino code will also choke on a number longer than one digit; Arduino代码也会阻塞超过一位的数字; see https://www.arduino.cc/en/Tutorial.StringToIntExample for how to read an int from serial. 有关如何从序列读取int的信息,请参见https://www.arduino.cc/en/Tutorial.StringToIntExample Basically keep reading and adding it onto the end of the string until you hit a terminator (the example uses a newline), then call .toInt() on that string. 基本上,继续阅读并将其添加到字符串的末尾,直到您碰到终止符(本示例使用换行符),然后对该字符串调用.toInt()

You could also use something like the following, which is probably more efficient, but certainly less readable: 您还可以使用如下所示的方法,它可能会更有效,但可读性肯定较低:

while (Serial.available() > 0) {
    int inChar = Serial.read();
    if (isDigit(inChar)) {
        int inNum = inChar - '0';
        n = n*10 + inNum;
    } else {
        // if inChar is NOT a digit
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM