Interfacing of Raspberry pi with Motors:
Now ready
to write code to motor. Turn on your Raspberry Pi and Open the terminal
window.
1)
Write a program to Motor move
Forward and Backward while switch is pressed.
Create a
new text file “motor1.py” by typing the following:
Sudo nano motor1.py
After
that write following code to the Text editer page:
import os
import RPi.GPIO as GPIO
from time import sleep
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD) #board usage gpio pin , bcm usasge pin mnumber
GPIO.setup(3,GPIO.IN)
GPIO.setup(4,GPIO.IN)
GPIO.setup(5,GPIO.OUT)
GPIO.setup(6,GPIO.OUT)
print(" interfacing of
Switch and Motor")
while True:
if( GPIO.input(3)== False):
print("Switch is Pressed then
motor move Forward")
GPIO.output(5,GPIO.HIGH)
GPIO.output(6,GPIO.LOW)
sleep(1)
elsif( GPIO.input(4)== False):
print("Switch is Pressed then motor
move Backward")
GPIO.output(5,GPIO.LOW)
GPIO.output(6,GPIO.HIGH)
sleep(2)
After
writing the code we checked it, save and exit the text editor with
“Ctrl +
x” then “y” then “enter”.
To
Running this Code Type:
sudo python motor1.py
then
You will
see the Motor moved Forward or Backward when we pressed the switch.
Circuit
Diagram:
1)
Write a program for Moving Robot.
Create a
new text file “motor2.py” by typing the following:
Sudo nano motor2.py
After
that write following code to the Text editer page:
import os
import RPi.GPIO as GPIO
from time import sleep
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD) #board usage gpio pin , bcm usasge pin mnumber
GPIO.setup(1,GPIO.IN)
GPIO.setup(2,GPIO.IN)
GPIO.setup(3,GPIO.IN)
GPIO.setup(4,GPIO.IN)
GPIO.setup(5,GPIO.OUT)
GPIO.setup(6,GPIO.OUT)
GPIO.setup(7,GPIO.OUT)
GPIO.setup(8,GPIO.OUT)
print(" interfacing of
Switch and Motor")
while True:
if( GPIO.input(1)== False):
print("Switch is Pressed then
Motor move Forward")
GPIO.output(5,GPIO.HIGH)
GPIO.output(6,GPIO.LOW)
GPIO.output(7,GPIO.HIGH)
GPIO.output(8,GPIO.LOW)
sleep(1)
elsif( GPIO.input(2)== False):
print("Switch is Pressed then Motor
move Backward")
GPIO.output(5,GPIO.LOW)
GPIO.output(6,GPIO.HIGH)
GPIO.output(5,GPIO.LOW)
GPIO.output(6,GPIO.HIGH)
sleep(2)
elsif( GPIO.input(3)== False):
print("Switch is Pressed the Motor
move Left")
GPIO.output(5,GPIO.HIGH)
GPIO.output(6,GPIO.LOW)
GPIO.output(5,GPIO.LOW)
GPIO.output(6,GPIO.LOW)
sleep(2)
elsif( GPIO.input(4)== False):
print("Switch is Pressed then Motor
move Right")
GPIO.output(5,GPIO.LOW)
GPIO.output(6,GPIO.LOW)
GPIO.output(5,GPIO.HIGH)
GPIO.output(6,GPIO.LOW)
sleep(2)
After
writing the code we checked it, save and exit the text editor with
“Ctrl +
x” then “y” then “enter”.
To
Running this Code Type:
sudo python motor2.py
then
You will
see Robot move when switch is pressed.
Circuit
Diagram: