Jmccart
Posts: 17
Joined: Sun Mar 17, 2019 4:57 pm

Control Arduino with Raspberry pi

Sun Mar 24, 2019 9:25 pm

Hi, I am working on a robotics project and I want to control servos connected to my Arduino, from my raspberry pi, how would I go about doing this??

gordon77
Posts: 4116
Joined: Sun Aug 05, 2012 3:12 pm

Re: Control Arduino with Raspberry pi

Sun Mar 24, 2019 9:35 pm

You can connect the pi and Arduino Uno with a usb cable and send and receive serial data.

Here's a simple example to show the principle.


viewtopic.php?f=91&t=186364&hilit=Uno#p1177157

Jmccart
Posts: 17
Joined: Sun Mar 17, 2019 4:57 pm

Re: Control Arduino with Raspberry pi

Sun Mar 31, 2019 8:01 pm

Sorry, but which code do I upload to my arduino, and which code do i run on my raspberry pi to control the arduino? these directions are very vague

gordon77
Posts: 4116
Joined: Sun Aug 05, 2012 3:12 pm

Re: Control Arduino with Raspberry pi

Sun Mar 31, 2019 8:23 pm

For the Pi...

Code: Select all

#! /usr/bin/env python
import serial
import time
ser = serial.Serial(port='/dev/ttyACM0',baudrate = 9600,parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_ONE,bytesize=serial.EIGHTBITS,timeout=1)
# Wait to read from Arduino
while 1:
   try:
       time.sleep(10)
       # send an R to the arduino
       ser.write("R")
       #read data from arduino
       myData = ser.readline()
       print myData
   except KeyboardInterrupt:
       exit()     
For the Arduino Uno...

Code: Select all

       float flow = 500.06;
    void setup() {
      Serial.begin( 9600 );}
    void loop() {
        if (Serial.available()>0) {
            if (Serial.read() == 'R') {
                 Serial.print(flow)
                 Serial.write("\n");
            }
        }
    }  

gordon77
Posts: 4116
Joined: Sun Aug 05, 2012 3:12 pm

Re: Control Arduino with Raspberry pi

Tue Apr 02, 2019 3:45 pm

This will control 2 servos connected to an Arduino Uno, connected to pins 3 & 4, and 5v and gnd.
It uses 2 sliders to set their positions. It sends commands like A1000, range A0500 to A2500, which the Arduino code will decode.

Raspberry Pi python script..

Code: Select all

#!/usr/bin/python3
import os
import pygame, sys
from pygame.locals import *
import serial
import time

# open serial port
if os.path.exists('/dev/ttyACM0') == True:
   ser = serial.Serial(port='/dev/ttyACM0',baudrate = 115200,parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_ONE,bytesize=serial.EIGHTBITS,timeout=1)
elif os.path.exists('/dev/ttyACM1') == True:
   ser = serial.Serial(port='/dev/ttyACM1',baudrate = 115200,parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_ONE,bytesize=serial.EIGHTBITS,timeout=1)
time.sleep(2)

# initilaise pygame
pygame.init()
windowSurfaceObj = pygame.display.set_mode((600,100),1,16)
redColor = pygame.Color(255,0,0)
blackColor = pygame.Color(0,0,0)
whiteColor = pygame.Color(255,255,255)

#starting position
pygame.draw.line(windowSurfaceObj, whiteColor, (0,50),   (600,50))
for m in range (2,600,35):
    pygame.draw.line(windowSurfaceObj, whiteColor, (m,48),   (m,52))
xA = 312
pygame.draw.rect(windowSurfaceObj,redColor,Rect(xA,5,10,40))
xB = 312
pygame.draw.rect(windowSurfaceObj,redColor,Rect(xB,55,10,40))
pygame.display.update(pygame.Rect(0,0,600,100))

s = 0
while s == 0:
    # read mouse button and position
    button = pygame.mouse.get_pressed()
    if button[0] != 0:
       pos = pygame.mouse.get_pos()
       x = pos[0]
       y = pos[1]
       a = x - 5
       if a < 0:
          a = 0
       # control servo A
       if y < 50:
          xA = a
          pygame.draw.rect(windowSurfaceObj,blackColor,Rect(0,0,600,100/2))
          pygame.draw.rect(windowSurfaceObj,redColor,Rect(xA,5,10,40))
          j = "A" + str(500 + int(xA * 3.368)).zfill(4)
          b = j.encode()
          # send to the Arduino eg. A1000
          ser.write(b)
          pygame.display.update(pygame.Rect(0,0,600,45))
          time.sleep(.1)
          # read from Arduino
          myData = (ser.readline()).strip().decode("utf-8")
          print ("A" + myData)
       # control servo B
       else:
          xB = a
          pygame.draw.rect(windowSurfaceObj,blackColor,Rect(0,50,600,100))
          pygame.draw.rect(windowSurfaceObj,redColor,Rect(xB,55,10,40))
          j = "B" + str(500 + int(xB * 3.368)).zfill(4)
          b = j.encode()
          # send to the Arduino eg. B1000
          ser.write(b)
          pygame.display.update(pygame.Rect(0,55,600,100))
          time.sleep(.1)
          # read from Arduino
          myData = (ser.readline()).strip().decode("utf-8")
          print ("B" + myData)


       
   # check for ESC key pressed, or pygame window closed, to quit
    for event in pygame.event.get():
       if event.type == QUIT:
          pygame.quit()
          sys.exit()
       elif event.type == KEYDOWN:
          if event.key == K_ESCAPE:
             pygame.quit()
             sys.exit()

Arduino Uno code...

Code: Select all

int servopinA = 3;
int servopinB = 4;
int pulseA = 1500;
int pulseB = 1500;
int valByte = 1500;
int inByte1 = 'a';
int inByte2 = 'a';
int inByte3 = 'a';
int inByte4 = 'a';
int inByte5 = 'a';
int Byte = 'a';
void setup()
{
  pinMode(servopinA, OUTPUT);
  pinMode(servopinB, OUTPUT);
  Serial.begin(115200);
  delay (1);
}

void loop()
{
  if (Serial.available() > 4) 
       { inByte1 = Serial.read();
         // check for valid commamd eg. A1000
         if (inByte1 == 'A' or inByte1 == 'B')
          {
            // read the next 4 characters
             inByte2 = Serial.read();
             inByte3 = Serial.read();
             inByte4 = Serial.read();
             inByte5 = Serial.read();
             valByte = (1000 * int(inByte2 - 48) +  100 * int(inByte3 - 48) + 10 * int(inByte4 - 48) + int(inByte5 - 48));
             Serial.print(valByte);
             Serial.write("\n");
             if (valByte > 499 and valByte < 2501 and inByte1 == 'A') {pulseA = valByte;}
             if (valByte > 499 and valByte < 2501 and inByte1 == 'B') {pulseB = valByte;}
           } 
          // empty serial buffer if not valid
         if (inByte1 != 'A' && inByte1 != 'B')
            { while (Serial.available()>0){
              Byte = Serial.read();}}
       }

  digitalWrite(servopinA,HIGH);
  delayMicroseconds(int(pulseA));
  digitalWrite(servopinA, LOW);
  digitalWrite(servopinB,HIGH);
  delayMicroseconds(int(pulseB));
  digitalWrite(servopinB, LOW);
  delay(20);
}

Return to “General discussion”