简体   繁体   中英

How send messages from Raspberry Pi to Arduino via USB cable

I'm trying to send a number from the Raspberry Pi to an Arduino Uno connected via USB. I followed this tutorial which is pretty straightforward.

I can find the port to which the Arduino is connected, and I've written the code so that whenever the Arduino receives something through the serial port (anything), it flashes the default led a few times. The problem is that it never receives anything.

When I run the python script from the Raspberry, the led on the arduino flashes randomly (like it just got attached to the power supply), but then it stops and nothing happens.

The code is this:

void setup() {
  Serial.begin(9600);
  pinMode(13, OUTPUT);
}

void loop() {
 if (Serial.available() > 0) {
    blinkLED(3);
  }
} 

void blinkLED(int count) {
  for (int i=0; i< count; i++) {
    digitalWrite(13, HIGH);
    delay(1000);
    digitalWrite(13, LOW);
    delay(1000);
  } 
}

While the python code is:

 import serial
 ser = serial.Serial('/dev/ttyACM0', 9600)
 ser.write('3')

What am I doing wrong?

I found out the problem. Basically when I opened the port from python the Arduino reset itself, so the stuff I was sending after the port was opened was discarded by the Arduino (since it was still resetting).

I resolved for now by simply adding a sleep after I open the port, so meanwhile Arduino finishes resetting.

The python code now looks like this:

import serial
import time
ser = serial.Serial('/dev/ttyACM0', 9600)
time.sleep(5)
ser.write('3')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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