Deo
Deo

Reputation: 59

Why is the communication between arduino and raspberry pi through serial so slow

I'm trying to send some data from raspberry pi to arduino through the serial connection but the speed seems too slow. All I'm trying to do is turn on and off a light on the arduino board and the signal to toggle the light is sent over the serial connection.

The light is turned on and off at some time interval as shown in the code below. When the delay is greater than 1, it works fine, the light turns on and off but when i change the delay to less than 1, the light does not blink at all. I tried changing the baud rate but that doesnt help. The baud rate on both boards are same. The code below is on the raspberry pi.

import serial
import time

serial_light = serial.Serial('/dev/ttyACM0', 250000)

delay = float (2)

while(1):
    inp = "60"
    print ("On\n")
    serial_light.write(inp.encode())
    time.sleep(float (delay))
    inp = "61"
    print ("Off\n")
    serial_light.write(inp.encode())
    time.sleep(float (delay))

//Arduino Code

int light = 13;

void setup()
{
    Serial.begin(250000);
    pinMode(light, OUTPUT);
}

void loop()
{
    int in = 0;
    while(Serial.available() == 0);
    in = Serial.parseInt();

    if(in == 60)
    {
        digitalWrite(light, HIGH);
    }
    else if(in == 61)
    {
        digitalWrite(light, LOW);
    }
}

Once again, it works for delay values >= 1 but not between 0 and 1.

Upvotes: 0

Views: 391

Answers (1)

Masoud Rahimi
Masoud Rahimi

Reputation: 6051

I prefer to use String or int, not a String of int for the type of commands.

You just need to create a loop with the desired delay in your Python script to send on/off actions, then on Arduino side just receive the command and take proper action.

Python script:

import serial
import time

delay = 2
serial_light = serial.Serial('/dev/ttyACM0', 9600)
serial_light.open()
# flush serial for unprocessed data
serial_light.flushInput()
while(1):
    print("On")
    serial_light.write(b"on")
    time.sleep(delay)
    print("Off")
    serial_light.write(b"off")
    time.sleep(delay)

Arduino code:

int light = 13;

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

void loop()
{
    // check if we have input command
    if (Serial.available())
    {
        // read input
        String command = Serial.readString();
        if (command == "on")
        {
            digitalWrite(light, HIGH);
        }
        else if (command == "off")
        {
            digitalWrite(light, LOW);
        }
    }
}

Upvotes: 1

Related Questions