6: Raspberry Pi controls L293D motor via Arduino

In this tutorial, you are going to learn how to use Raspberry Pi 4B to control Arduino Uno via serial port.



You need Raspberry Pi 4B + Arduino Uno + Jumper wires + LED + 3V DC motor + L293D Driver module in order to complete this tutorial.

To install arduino software on Raspberry Pi, type "sudo apt-get update && sudo apt-get install arduino" in the Pi terminal.

After installation, you should see arduino IDE in "Electronics"



Then open arduino software in Pi computer. Load the "Blink.ino"  under "Examples". This code aims at turning the LED-13 on and off repeatedly. Connect the LED to arduino pin 13(+) and ground pin (-).

Next, connect Raspberry Pi and arduino via USB port. The default port is dev/ttyASM0. However, there are many USB ports in Raspberry Pi. You may need to change port number as follows.



After the code is uploaded, you should see a flashing LED-13 on arduino

To establish a remote platform between Arduino and Raspberry Pi, you need to build a simple electronic circuit on arduino board.

After that, connect Raspberry Pi to arduino via serial USB port again.



Create Pi_example.py in Pi computer. The yellow line in the following code reminds you to find the right port number again. If the delay time is too short, your motor cannot respond when the rotational direction is reversed. Here I set 5 seconds.

If command '1' is sent, the motor rotates in clockwise direction.
If command '0' is sent, the motor rotates in anti-clockwise direction.
If command '2' is sent, the motor stops rotation.

import serial
import time

ser = serial.Serial('/dev/ttyACM1', 9600)

ser.write(str.encode('2'))    # ser.write('2') is also fine 
time.sleep(5)
ser.write(str.encode('1'))
time.sleep(5)
ser.write(str.encode('2'))
time.sleep(5)
ser.write(str.encode('0'))
time.sleep(5)
ser.write(str.encode('2'))


Now we build arduino code to receive the commands '0', '1'  and '2'. accordingly.

int in1Pin=5;
int in2Pin=6;
int data;

void setup()
{
    pinMode(in1Pin,OUTPUT);
    pinMode(in2Pin,OUTPUT);
  
}

void loop()
{
    while (Serial.available())  
    { 
        data = Serial.read();
    }

   if(data=='0')
   {
       digitalWrite(in1Pin,HIGH);
       digitalWrite(in2Pin,LOW);
       delay(5000);
    }
    if(data=='1')
    {
        digitalWrite(in1Pin,LOW);
        digitalWrite(in2Pin,HIGH);
        delay(5000);
    }
    if(data=='2')
    {
        digitalWrite(in1Pin,LOW);
        digitalWrite(in2Pin,LOW);
        delay(5000);
    }   
}​



*The above code are modified from open source platform

Comments