简体   繁体   English

Raspberry Pi 到 Arduino 连续串行通信

[英]Raspberry Pi to Arduino Continuous Serial Communication

I want to send data from my Raspberry Pi to Arduino using the pyserial library from the side of Raspberry Pi.我想使用 Raspberry Pi 旁边的 pyserial 库将数据从我的 Raspberry Pi 发送到 Arduino。 I just used a USB to connect the two devices.我只是用 USB 连接两个设备。 First I uploaded a program to the Arduino that checks if there is an available serial data then I am going to read it and compare the received data using if else statements.首先,我将一个程序上传到 Arduino,检查是否有可用的串行数据,然后我将读取它并使用 if else 语句比较接收到的数据。 It works properly if I set the delay between writing to the serial port every 5 seconds in the Python program but if I set the delay to 1 second, it reads it at random times.如果我在 Python 程序中设置每 5 秒写入串行端口之间的延迟,它会正常工作,但如果我将延迟设置为 1 秒,它会随机读取它。 I just use Windows for now to test it before I run on it on the Raspberry Pi.在我在 Raspberry Pi 上运行它之前,我现在只是使用 Windows 来测试它。 Is there any way I can make the sending of data faster rather than adding a 5 seconds delay?有什么办法可以加快数据发送速度而不是增加 5 秒的延迟? Below is the sample code I wrote.下面是我写的示例代码。

Python Python

import serial
import time

port=serial.Serial('COM8',9600)
time.sleep(5)

try:

    while True:
        port.write(b'Hi\n')
        time.sleep(5)
except:
    port.close()

Arduino阿杜诺

String dataIn;
int led = 13;

void setup()
{
  Serial.begin(9600);

  pinMode(led, OUTPUT);
  digitalWrite(led, LOW);

  Serial.flush();
}

void loop()
{
  if (Serial.available())
  {
    dataIn = Serial.readStringUntil("\n");

    if (dataIn == "Hi\n")
    {
      digitalWrite(led, HIGH);
      delay(1000);
      digitalWrite(led, LOW);
      delay(1000);
    }

    Serial.flush();
    dataIn = "";
  }
}

i would recommend using String lib like the below我会推荐像下面这样使用 String lib

  String command;


  void loop() { 
  if (Serial.available()) 
  {
    command = Serial.readStringUntil('\n');
    command.trim();
    command.equals("something");
    /*your Implementation here*/
  }
}

it works well for me这对我来说很有效

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

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