tony1812
Posts: 200
Joined: Sat Jul 15, 2017 12:40 pm
Location: Boston MA.

usb serial from Pi to Arduino

Tue Nov 14, 2017 11:31 pm

Hello, there are plenty of posts online that sending data from Arduino to Pi via the usb serial, But few does the other way around, ( send data from the Pi to Arduino.) I came up with a code like this, It doesn't do exactly what I want, but I think with some modification, It may work.
But I am not sure how.

The sender is the Pi. Here is the python code:

Code: Select all

#!/usr/bin/python3
import serial
import time
ser = serial.Serial('/dev/ttyUSB0', 9600)
time.sleep(5)
ser.write(b'1')
The receiver is the Arduino, the sketch looks like this:

Code: Select all

int incomingByte = 0;   // for incoming serial data

void setup() {
        Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
        pinMode(10,OUTPUT);
        pinMode(11,OUTPUT);
        pinMode(12,OUTPUT);
}

void loop() {

        // receive data:
        if (Serial.available() > 0) {
                // read the incoming byte:
                incomingByte = Serial.read();
                switch ((char)incomingByte) {
                 case '0':
                  	my_blink(10);
                  break;
                  
                 case '1':
                  	my_blink(11);
                  break;
                  
                 case '2':
                  	my_blink(12);
                  break;
                  
                 default:
                  break;
                }                
        }
}
void my_blink(int pin) {
  digitalWrite(pin, HIGH);
  delay(1000);
  digitalWrite(pin, LOW);
  delay(1000);
}
There are few issues about this code, On the Pi side, as is now I can only send a single byte in ser.write(b'0'), ser.write(b'1')...etc. On the Arduino, the switch statement response to the switch statement to turn on the corresponding pins. Turn on pin 10.11 or 12.

But how can I make the Pi to send a integer or a string like 45,90,120... to control servo position on the Arduino? Thanks.

asandford
Posts: 1719
Joined: Mon Dec 31, 2012 12:54 pm
Location: Ealing

Re: usb serial from Pi to Arduino

Tue Nov 14, 2017 11:53 pm

There are many protocols available to control Arduinos over serial, the best known is firmata.

Return to “Beginners”

Who is online

Users browsing this forum: No registered users and 31 guests