0% found this document useful (0 votes)
8 views17 pages

2.controlling Hardware

This document provides instructions for controlling various hardware components using a Raspberry Pi, including LEDs, buzzers, high-power devices with transistors, AC power devices with relays, servo motors, and DC motors. It includes detailed wiring diagrams, Python code examples for controlling these devices, and safety precautions for using GPIO pins. The document emphasizes the importance of using resistors, external power supplies, and proper components to avoid damaging the Raspberry Pi.

Uploaded by

vinayak457
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views17 pages

2.controlling Hardware

This document provides instructions for controlling various hardware components using a Raspberry Pi, including LEDs, buzzers, high-power devices with transistors, AC power devices with relays, servo motors, and DC motors. It includes detailed wiring diagrams, Python code examples for controlling these devices, and safety precautions for using GPIO pins. The document emphasizes the importance of using resistors, external power supplies, and proper components to avoid damaging the Raspberry Pi.

Uploaded by

vinayak457
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Controlling Hardware UNIT-IV

4.1 CONTROLLING HARDWARE

4.1.1 Connecting an LED:


LEDs are a very useful, cheap, and efficient way of producing light, but you do have
to be careful how you use them. If they are connected directly to a voltage source (such as a
GPIO output) that is greater than about 1.7 volts, they will draw a very large current. This can
often be enough to either destroy the LED or whatever is providing the current which is not
good if your Raspberry Pi is providing the current. You should always use a series resistor
with an LED because the series resistor is placed between the LED and the voltage source,
which limits the amount of current flowing through the LED to a level that is safe for both the
LED and the GPIO pin driving it. Raspberry Pi GPIO pins can only provide about 3 mA of
current. LEDs will generally illuminate with any current greater than 1 mA, but will be
brighter with more current. Use Table 4.1 as a guide to selecting a series resistor based on the
type of LED; the table also indicates the approximate current that will be drawn from the
GPIO pin. If you want to play it safe, use 1kΩ.
Table 4.1: Selecting series resistors for LEDs and a 3.3V GPIO pin
LED TYPE RESISTOR CURRENT (mA)
Red 470Ω 3.5
Red 1KΩ 1.5
Orange, Yellow, Green 470Ω 2
Orange, Yellow, Green 1KΩ 1
Blue, White 100Ω 3
Blue, White 270Ω 1

Figure 4.1: Connecting LED to Raspberry Pi

MRITS/II-II/CSE-IoT/Sensors and Devices 1


Controlling Hardware UNIT-IV

Connect an LED to one of the GPIO pins using a 470Ω or 1kΩ series resistor to limit the
current as shown in Figure 4.1. To make this, you will need:
• Breadboard and jumper wires
• 1kΩ resistor
• LED
Having connected the LED, we need to be able to turn it on and off using commands from
Python. To do this, install the RPi.GPIO Python library.
Start a Python console from the Terminal with superuser access and enter these commands:
$ sudo python
>>> import RPi.GPIO as GPIO
>>> GPIO.setmode(GPIO.BCM)
>>> GPIO.setup(18, GPIO.OUT)
>>> GPIO.output(18, True)
>>> GPIO.output(18, False)
This will turn your LED on and off.
If you wanted to extend the experiments that you made in the Python console into a program
that makes the LED blink on and off repeatedly, you could paste the following code into the
editors. Save the file as led_blink.py.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
while (True):
GPIO.output(18, True)
time.sleep(0.5)
GPIO.output(18, False)
time.sleep(0.5)
Remember that to run the program, you must have superuser privileges for the RPi.GPIO
library, so you need to use this command:
$ sudo python led_blink.py
To vary the brightness of an LED from a Python program. The RPi.GPIO library has a pulse-
width modulation (PWM) feature that allows you to control the power to an LED and its
brightness. Here is the code for varying brightness.

MRITS/II-II/CSE-IoT/Sensors and Devices 2


Controlling Hardware UNIT-IV

import RPi.GPIO as GPIO


led_pin = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(led_pin, GPIO.OUT)
pwm_led = GPIO.PWM(led_pin, 500)
pwm_led.start(100)
while True:
duty_s = raw_input("Enter Brightness (0 to 100):")
duty = int(duty_s)
pwm_led.ChangeDutyCycle(duty)
PWM is a clever technique where you vary the length of pulses while keeping the overall
number of pulses per second (the frequency in Hz) constant. Figure 4.2 illustrates the basic
principle of PWM.

Figure 4.2: Pulse Width Modulation


At high frequencies, the measured PWM frequency varies somewhat from the frequency
supplied as an argument. This may be something that changes in later versions of the PWM
feature of RPi.GPIO.
You can change the PWM frequency by modifying this line:
pwm_led = GPIO.PWM(led_pin, 500)
The value is in Hz, so in this case, the frequency is set to 500 Hz.

MRITS/II-II/CSE-IoT/Sensors and Devices 3


Controlling Hardware UNIT-IV

4.1.2 Connecting Buzzer:


To make a buzzing sound with the Raspberry Pi. Use a piezo-electric buzzer
connected to a GPIO pin. Most small piezo buzzers work just fine using the arrangement
shown in Figure 4.3.

Figure 4.3: Connecting Buzzer to Raspberry Pi


Mostly use an Adafruit supplied component which connect the buzzer pins directly to the
Raspberry Pi using female-to-female headers. These buzzers use very little current. However,
if you have a large buzzer or just want to play it safe, then put a 470Ω resistor between the
GPIO pin and the buzzer lead.
Paste the following code into the editors. Save the file as buzzer.py.
import RPi.GPIO as GPIO
import time
buzzer_pin = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(buzzer_pin, GPIO.OUT)
def buzz(pitch, duration):
period = 1.0 / pitch
delay = period / 2
cycles = int(duration * pitch)
for i in range(cycles):
GPIO.output(buzzer_pin, True)
time.sleep(delay)
GPIO.output(buzzer_pin, False)
time.sleep(delay)
while True:

MRITS/II-II/CSE-IoT/Sensors and Devices 4


Controlling Hardware UNIT-IV

pitch_s = raw_input("Enter Pitch (200 to 2000): ")


pitch = float(pitch_s)
duration_s = raw_input("Enter Duration (seconds): ")
duration = float(duration_s)
buzz(pitch, duration)
When you run the program, it will first prompt you for the pitch in Hz and then the duration
of the buzz in seconds:
$ sudo python buzzer.py
Enter Pitch (2000 to 10000): 2000
Enter Duration (seconds): 20
Piezo buzzers don’t have a wide range of frequencies, nor is the sound quality
remotely good. However, you can vary the pitch a little. The frequency generated by the code
is very approximate. The program works by simply toggling the GPIO pin 18 on and off with
a short delay in between. The delay is calculated from the pitch.

4.1.3 Switching High Power Devices with Transistors:


High-power LEDs use far too much current to light directly from a GPIO pin. They
also require 12V rather than the 3.3V. To control such a high-power load, you need to use a
transistor. In this case, you will use a high-power type of transistor called a MOSFET (metal
oxide semiconductor field effect transistor), which costs less than a dollar but can handle
loads up to 30 amps, many times more than is required for the high-power LEDs. The
MOSFET used is a FQP30N06. Figure 4.4 shows how you can connect a MOSFET on a
breadboard. Make sure that you correctly identify the positive and negative supply leads for
the LED module.
To make this, you will need:
➢ Breadboard and jumper wires
➢ 1kΩ resistor
➢ FQP30N06 N-Channel MOSFET
➢ 12V power adapter
➢ 12V DC LED module
The Python code to turn the LED panel on and off is exactly the same as if we were
controlling a single low-power LED without the MOSFET.

MRITS/II-II/CSE-IoT/Sensors and Devices 5


Controlling Hardware UNIT-IV

Figure 4.4: Controlling Large Currents with MOSFET


Whenever you need to power anything significant using the GPIO connector, use
batteries or an external power adapter. The GPIO connector can only supply relatively low
currents. In this case, you’ll use a 12V DC power adapter to provide the power to the LED
panel. Pick a power adapter that has sufficient power handling. So, if the LED module is 5W,
then you need at least a 12V 5W power supply (6W would be better). If the power supply
specifies a maximum current rather than power, then you can calculate its power by
multiplying the voltage by the maximum current. So, a 500 mA 12V power supply can
provide 6 W of power. The resistor is necessary to ensure that the peak currents that occur as
the MOSFET switches from off to on and vice versa do not overload the GPIO pin. The
MOSFET switches the negative side of the LED panel, so the positive supply is connected
directly to the positive side of the LED panel, and the negative side of the LED panel is
connected to the drain of the MOSFET. The source connection of the MOSFET is connected
to GND, and the MOSFET’s gate pin controls the flow of current from the drain to the
source. If gate voltage is above about 2V, the MOSFET will turn on and current flows
through both it and the LED module. This circuit is suitable for controlling the power to other
low-voltage DC devices.

MRITS/II-II/CSE-IoT/Sensors and Devices 6


Controlling Hardware UNIT-IV

4.1.4 Controlling AC power Devices with Relays:


To turn devices on and off that may not be suitable for switching with a MOSFET. Use a
relay and small transistor. Figure 4.5 shows how you can connect up a transistor and relay on
breadboard. Make sure that both the transistor and diode are placed the right way around. The
diode has a stripe at one end, and the transistor used here has one side flat and one curved.

Figure 4.5: Using a Relay with Raspberry Pi


To make this, you will need:
• Breadboard and jumper wires
• 1kΩ resistor
• Transistor 2N3904
• 1N4001 diode
• 5V relay
• Multimeter

MRITS/II-II/CSE-IoT/Sensors and Devices 7


Controlling Hardware UNIT-IV

You can use the same LED blink program that you used in 4.1.1. If all is well, you’ll
hear a click from the relay each time the contacts are closed. However, relays are slow
mechanical devices, so don’t try to use them with PWM. It may damage the relay.
Relays:
Relays have been around since the early days of electronics and have the great
advantage of being easy to use, plus they’ll work in any situation where a switch would
normally work—for example, when you’re switching AC (alternating current) or in situations
where the exact wiring of the device being switched is unknown. If the relay contacts are
asked to exceed their specifications, then the relay’s life will be shortened. There will be
arcing, and the contacts may eventually fuse together. There is also the possibility of the relay
becoming dangerously hot. When in doubt, over specify the relay contacts.

Figure 4.6 Structure of Relay


Figure 4.6 shows how a relay is constructed. A relay is essentially a switch whose
contacts are closed when an electromagnet pulls them together. Since the electromagnet and
switch are not connected electrically in any way, this protects the circuit driving the relay coil
from any high voltages on the switch side. The downside of relays is that they are slow to
operate and will eventually wear out after many hundreds of thousands of operations. This
means they are only suitable for slow on/off control, not for fast switching like PWM. The
coil of a relay requires about 50 mA to close the connections. Because a Raspberry Pi GPIO
pin is only capable of supplying about 3 mA, you need to use a small transistor as a switch.
The base (middle lead) is connected to the GPIO pin via a 1kΩ resistor to limit the current.
The emitter is connected to GND, and the collector to one side of the relay. The other side of
the relay is connected to 5V on the GPIO connector. The diode is used to suppress any high
voltage pulses that occur when the transistor rapidly switches the power to the relay’s coil.

MRITS/II-II/CSE-IoT/Sensors and Devices 8


Controlling Hardware UNIT-IV

4.1.5 Controlling Servo Motors:


Want to use a Raspberry Pi to control the position of a servo motor. Use PWM to
control the width of pulses to a servo motor to change its angle. Although this will work, the
PWM generated is not completely stable, so there will be a little bit of jitter with the servo.
You should also power the servo from a separate 5V power supply because peaks in the load
current are likely to crash or overload the Raspberry Pi.

Figure 4.7: Controlling a Servo Motor


To make this, you will need:
➢ 5V servo motor
➢ Breadboard and jumper wires
➢ 1kΩ resistor
Open an editor and paste in the following code. Save it as servo.py.
Note that this program uses a graphical user interface, so you cannot run it from SSH. You
must run it from the windowing environment on the Pi itself or via remote control using
VNC. You also need to run it as superuser, so run it with the command
sudo python servo.py

MRITS/II-II/CSE-IoT/Sensors and Devices 9


Controlling Hardware UNIT-IV

from Tkinter import *


import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
pwm = GPIO.PWM(18, 100)
pwm.start(5)
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
scale = Scale(frame, from_=0, to=180,
orient=HORIZONTAL, command=self.update)
scale.grid(row=0)
def update(self, angle):
duty = float(angle) / 10.0 + 2.5
pwm.ChangeDutyCycle(duty)
root = Tk()
root.wm_title('Servo Control')
app = App(root)
root.geometry("200x50+0+0")
root.mainloop()

Figure 4.8: Servomotors

MRITS/II-II/CSE-IoT/Sensors and Devices 10


Controlling Hardware UNIT-IV

Servo motors are used in remote control vehicles and robotics. Most servo motors are
not continuous; that is, they cannot rotate all the way around but rather just over an angle of
about 180 degrees.
The position of the servo motor is set by the length of a pulse. The servo expects to
receive a pulse at least every 20 milliseconds. If that pulse is high for 1 millisecond, the servo
angle will be zero; if it is 1.5 milliseconds, it will be at its centre position; and if it is 2
milliseconds, it will be at 180 degrees as shown in figure 4.8. The example program sets the
PWM frequency to 100 Hz, which will send a pulse to the servo every 10 milliseconds. The
angle is converted into a duty cycle between 0 and 100. This actually produces pulses shorter
than the 1 millisecond expected minimum value and longer than 2 milliseconds maximum.

4.1.6 Speed Control of DC Motor:


want to control the speed of a DC motor, using your Raspberry Pi. For low-power motors
(less than 200 mA), you can base the design on the one used for a relay. You will need:
➢ 3V to 12V DC motor
➢ Breadboard and jumper wires
➢ 1kΩ resistor
➢ Transistor 2N3904
➢ Diode 1N4001
➢ Power supply with voltage to match the motor
If you are only using a low-power DC motor (less than 200 mA), you can use a smaller
(and cheaper) transistor as shown in figure 4.10.
You can probably get away with powering a small motor from the 5V supply line on the
GPIO connector. If you find that the Raspberry Pi crashes, use an external power supply,
as shown in Figure 4.11.
To control the speed of the motor, you can use the program gui_slider.py. Note that this
program uses a graphical user interface, so you can’t run it from SSH. You must run it from
the windowing environment on the Pi itself or via remote control using VNC in Figure 4.9.

Figure 4.9: User Interface for controlling PWM

MRITS/II-II/CSE-IoT/Sensors and Devices 11


Controlling Hardware UNIT-IV

Figure 4.10: Low Power DC Motor

Figure 4.11: High Power DC Motor


from Tkinter import *
import RPi.GPIO as GPIO
import time

MRITS/II-II/CSE-IoT/Sensors and Devices 12


Controlling Hardware UNIT-IV

GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
pwm = GPIO.PWM(18, 500)
pwm.start(100)
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
scale = Scale(frame, from_=0, to=100,
orient=HORIZONTAL, command=self.update)
scale.grid(row=0)
def update(self, duty):
pwm.ChangeDutyCycle(float(duty))
root = Tk()
root.wm_title('PWM Power Control')
app = App(root)
root.geometry("200x50+0+0")
root.mainloop()
Note that you will need to run it with sudo because the RPi.GPIO requires you to have
superuser privileges to access the GPIO hardware.
$ sudo python gui_slider.py

4.1.7 Controlling Unipolar Stepper Motor:


Want to drive a five-lead unipolar stepper motor using a Raspberry Pi. Use a
ULN2803 Darlington driver chip.
Stepper motors fit somewhere between DC motors and servo motors in the world of
motor technologies. Like a regular DC motor, they can rotate continuously, but you can also
very accurately position them by moving them a step at a time in either direction.
To make this, you will need:
➢ 5V, five-pin unipolar stepper motor
➢ ULN2803 Darlington driver IC
➢ Breadboard and jumper wires

MRITS/II-II/CSE-IoT/Sensors and Devices 13


Controlling Hardware UNIT-IV

Figure 4.12 shows the wiring diagram for using a ULN2803. Note that the chip can be
used to drive two such motors. To drive a second stepper motor, you will need to connect
four more control pins from the GPIO connector to pins 5 to 8 of the ULN2803 and connect
the second motor’s four pins to pins 11 to 14 of the ULN2803.

Figure 4.12 Using a ULN2803 to control a unipolar stepper motor


Open an editor (nano or IDLE) and paste in the following code.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
coil_A_1_pin = 18
coil_A_2_pin = 23
coil_B_1_pin = 24
coil_B_2_pin = 17
GPIO.setup(coil_A_1_pin, GPIO.OUT)
GPIO.setup(coil_A_2_pin, GPIO.OUT)
GPIO.setup(coil_B_1_pin, GPIO.OUT)
GPIO.setup(coil_B_2_pin, GPIO.OUT)
forward_seq = ['1010', '0110', '0101', '1001']
reverse_seq = list(forward_seq) # to copy the list
reverse_seq.reverse()
def forward(delay, steps):
for i in range(steps):

MRITS/II-II/CSE-IoT/Sensors and Devices 14


Controlling Hardware UNIT-IV

for step in forward_seq:


set_step(step)
time.sleep(delay)
def backwards(delay, steps):
for i in range(steps):
for step in reverse_seq:
set_step(step)
time.sleep(delay)
def set_step(step):
GPIO.output(coil_A_1_pin, step[0] == '1')
GPIO.output(coil_A_2_pin, step[1] == '1')
GPIO.output(coil_B_1_pin, step[2] == '1')
GPIO.output(coil_B_2_pin, step[3] == '1')
while True:
set_step('0000')
delay = raw_input("Delay between steps (milliseconds)?")
steps = raw_input("How many steps forward? ")
forward(int(delay) / 1000.0, int(steps))
set_step('0000')
steps = raw_input("How many steps backwards? ")
backwards(int(delay) / 1000.0, int(steps))
When you run the program, you will be prompted for a delay between steps. This should
be two or more. You will then be prompted for the number of steps in each direction:
$ sudo python stepper.py
Delay between steps (milliseconds)?2
How many steps forward? 100
How many steps backwards? 100
Delay between steps (milliseconds)?10
How many steps forward? 50
How many steps backwards? 50
Delay between steps (milliseconds)?
Stepper motors use a cogged rotor and electromagnets to nudge the wheel around a
step at a time as shown in Figure 4.13. Note that the colors of the leads will vary. Energizing

MRITS/II-II/CSE-IoT/Sensors and Devices 15


Controlling Hardware UNIT-IV

the coils in a certain order drives the motor around. The number of steps that the stepper
motor has in a 360-degree rotation is actually the number of teeth on the rotor.

Figure 4.13: Stepper Motor


4.1.8 Controlling Bi-Polar Stepper Motor:

Figure 4.14: Using a L293D to control a bipolar stepper motor

MRITS/II-II/CSE-IoT/Sensors and Devices 16


Controlling Hardware UNIT-IV

Want to drive a four-lead bipolar stepper motor using a Raspberry Pi. Use a L293D H-Bridge
driver chip. An H-Bridge is required to drive a bipolar stepper motor because, as the word
bipolar suggests, the direction of current across the windings needs to be reversed, rather like
driving a DC motor in both directions.
To make this, you will need:
➢ 12V, four-pin bipolar stepper motor
➢ L293D H-Bridge IC
➢ Breadboard and jumper wires
The motor used here, a 12V, is somewhat larger than the previous unipolar stepper motor
example. The power for the motor itself is therefore supplied from an external power supply
rather than from the Raspberry Pi. Code is same as above 4.1.7. The design uses both H-
Bridges of the L293D, so you need one of these chips for each motor you want to control.

Figure 4.15: H-Bridge

MRITS/II-II/CSE-IoT/Sensors and Devices 17

You might also like