Linux Format

Controllin­g servos

Sean D. Conway provides the theory before using Python with a Pi to control a servomotor, and to change LED brightness.

- Sean D. Conway A retired IT Security Specialist who invests time in Raspberry Pi projects in order to satisfy his passion for continuous learning.

Sean D. Conway provides the theory before using Python with a Pi to control a servomotor or change LED brightness.

After completing this tutorial, you’ll have all the knowledge to understand how to code Pulse Width Modulation (PWM) support for a Raspberry Pi using Python. This knowledge will enable you to control servomotor­s as well as control the level of brightness of an LED, both of which are crucial for many a project.

PWM is a digital signal modulated by varying the width of the pulsing signal. First let’s explore some terms and concepts to set the groundwork for the tutorial, and we’ll include some diagrams to provide visual examples.

In theory…

A cycle is an interval of time during which a complete excursion of a value sequence is completed. In the waveform A1 shown below, the value of the digital signal in a time interval starts at 0V, rises to 5V for a period, then returns to 0V to complete the cycle. This complete excursion is one cycle of the digital signal. In waveform A2, in the same time period two excursions of the digital signal have occurred. This would be two cycles. Similarly, waveform A3 shows four cycles of the digital signal occurring.

The time it takes for the digital signal value to complete one cycle is called the period of the digital signal. The number of cycles completed in one second is called the frequency. Until 1965, frequency was indicated in cycles per second. Today, the more common technical term for the unit of measuremen­t for frequency is Hertz, with the symbol Hz.

You may have encountere­d Hertz in describing mains electrical power, or more likely the speed of a computer’s CPU (when measured in GHZ). In North

America, AC (mains) power has a frequency of 60Hz, while in the UK and Europe it’s 50Hz (Jonni was explaining there are minor variances across Europe due to a dispute in Serbia that make your microwave clock

lose time. FACT!–ED). The frequency value of a digital signal is a required parameter when coding a PWM setup in Python for a Raspberry Pi.

The term ‘duty cycle’ refers to a comparison of the time interval at which the digital signal is high (5V, in this example) versus low (0V). If the digital pulse is high for 50 per cent of the time interval, as in waveform B1, the digital signal has a duty cycle of 50 per cent. In waveform B2, the digital signal is high 25 per cent of the time: a 25 per cent duty cycle. Waveform B3 establishe­s a digital signal that is high for three quarters of the time interval, so has a duty cycle of 75 per cent. By varying the duty cycle of the digital signal, the pulse width changes. Changing the width of the pulse is referred to as a Pulse Width Modulated digital signal. This can be a method of of controllin­g an analogue device. Note the word analogue there – digital devices react differentl­y to PWM signals.

PWM is one of the primary means of driving devices such as variable-speed motors, dimmable lights (that is, an analogue light), actuators and speakers. PWM signals apply power in pulses of voltage. The voltage is applied and then removed many times in an interval, as shown in waveform C1. An analogue device driven by PWM reacts to the average value of the pulses, shown by the red lines in the waveforms in column C. The motor doesn’t stop instantly when the pulse drops to zero; inertia causes the motor to slow a bit before power is reapplied by the pulse returning high. The average voltage changes as the pulse widths are varied.

As with the frequency value, the width of a pulse stated as a duty cycle is a required parameter when coding a PWM setup.

Servomotor­s to maximum!

Using this knowledge, let’s examine the operation of a digital motor called a servomotor. The movement of a servomotor (determined by its actuator) can be rotary, moving in a circle, or linear, moving in and out. The servomotor uses a feedback sensor coupled to a controller to establish position. Having precise control of the angular or linear position, velocity and accelerati­on is what makes servomotor­s unique.

A servomotor can move an arm extension to a specific distance, or rotate a shaft to a specific angle. The movement is a function of the width of the pulse signal applied. By continuous­ly applying a signal of a specific pulse width, the positional feedback to the controller of the servomotor determines the motion – in-out, left-right – and the final position.

Fortunatel­y, we don’t have to get too far into the operation of servomotor controller­s in order to develop knowledge about how they work. The motor graphic in the centre of the diagram above depicts a SG92R digital servomotor. Its physical orientatio­n is related to angular motion, and this is important when you are trying to determine left and right directions. Facing the servomotor in the opposite direction will change what is ‘left’ and ‘right’ when it comes to determinin­g angles.

In order for the servomotor actuator arm to take up the position on the left, at zero degrees (see waveform X), the width of the pulse will need to be 2.5ms, or 12.5 per cent duty cycle at a frequency of 50 times per second – that is, 50Hz. To move the servomotor

actuator arm all the way to the right at 180 degrees (see waveform Z), the same 50Hz digital signal must have a pulse width of 0.5ms, or a duty cycle of 2.5 per cent. When a pulse signal is applied the actuator moves; when no pulse signal is applied, it’s stationary.

The electronic controller inside the servomotor evaluates the width of the incoming pulse and positions the actuator arm to reflect the correspond­ing pulse width. The controller has the ability to position the arm precisely along the arc, according to the incoming signal. If the actuator was linear rather than angular, the linear movement would also be precise.

LEDS to maximum!

Now let’s return to what we’ve learned so far and apply it to lighting a light emitting diode (LED). Remember that we said that when PWM is applied to an analogue device such as a light, it causes the intensity to change, because the average voltage level varies depending on the duty cycle (that is, the pulse width). Column C in the diagram on page 56 shows some examples.

When applied to a digital device like a LED, PWM provides the same result – lower intensity – but for different underlying reasons. An LED is a device that is either on or off: there’s no in-between. The brightness of the LED is part of its design and not a result of the voltage level applied. Apply a voltage to an LED and it’s on; take the voltage away and the LED is off. So how do we actually make a LED dimmer?

If you take a source such as an LED and apply a digital signal that has a frequency of less than approximat­ely 30Hz, the LED will appear to flicker. You can see this in waveform 1 in the diagram below. The absence of LED light during the off cycle causes the flicker in the human eye.

So what happens if the frequency is greater than 30Hz, as seen in waveform 2 below? Think of the eye as having persistenc­e: it retains what it sees for certain amount of time, as can easily be demonstrat­ed if you look at a very bright light and then immediatel­y close your eyes. In this case, then, the LED comes on and the eye registers light. If the next pulse occurs fast enough, the eye and brain persistenc­e ‘fills in the gap’ to make it seem as if the LED light is still on.

Now let’s keep the frequency higher than 30Hz, but reduce the duty cycle (pulse width). In reality, the light is turning on and off. However, thanks to the eye’s persistenc­e and the high frequency of the signal, we view the LED as being continuous­ly on, but dimmer. You’ll get a chance shortly to see the theory in action by using Python code to demonstrat­e how changing pulse widths changes the LED’S brightness.

The frequency rate of ‘greater than 30Hz’ to eliminate flicker is not a fixed value. Human eyes and brains are unique; some people may not see a flicker at a frequency less than 30Hz, and others (me!–ed) might.

There’s another wrinkle, too, in that the outside of the retina has more sensors to detect dark and light than the center of the retina. You’ve probably experience­d seeing flicker in a fluorescen­t light in an office only when it’s in the periphery of your vision. When you look straight at the light, it seems to be completely stable.

On the periphery, you see the flicker because your eye detects it better. In evolutiona­ry terms, of course, this is because it makes sense to be able to detect potential threats – such as a moving dark shape – at the edge of your viewpoint, even when you aren’t looking in their direction.

Putting theory into practice

Anyway, let’s put the theory into practice by examining the Python code that will control a servomotor and an LED connected to a Raspberry Pi, as shown in the schematic drawing on page 59.

The Python code you’ll find in the archive has been annotated with the reference marker text

#[Callout ] . You can open the scripts from the LXF archives in your favourite text editor and then locate the reference markers that correspond to the explanatio­n listed below.

Let’s examine the code from the script called one_ servo_continuous_move.py. When executed, this Python script changes the position of the servomotor actuator arm in three increments from left to right continuous­ly. At Callout 1 we start with:

import time import RPI.GPIO as GPIO

These are external Python code modules that need to be referenced so they can be used within the script. The RPI.GPIO module is used to control the Raspberry Pi’s GPIO pins. This module contains specific parameters to support PWM. Next, Callout 2 :

freq = 50

Here’s where the frequency value of a digital signal is defined. This parameter can be found in the servomotor manufactur­er’s specificat­ion. The SG92R requires a digital pulsing signal of 50Hz.

pwm = GPIO.PWM(GPIOPIN, freq) pwm.start(7.5)

This code segment at Callout 3 contains the parameters defining which GPIO pin(s) will be supporting pulse width modulation (PWM) with the frequency value already defined.

pwm.changeduty­cycle(2.5) time.sleep(1) pwm.changeduty­cycle(7.5) time.sleep(1) pwm.changeduty­cycle(12.5) time.sleep(1)

Here at Callout 4 is where the percentage value of duty cycle for the initial PWM is defined. This value positions the actuator arm in the center of its left-right rotation. In the remaining code, the PWM percentage is changed with pwm.changeduty­cycle(2.5) to move the actuator arm to left, the 7.5 value to move to centre and 12.5 to full right.

Let’s examine the code from the script called PWM_ LED.PY. This script changes the brightness intensity of an LED. The initial value is off, then ramps up from lowest to highest intensity using three increments.

freq = 74

Callout 1 : Here’s where we define the frequency of the PWM signal. Remember that the frequency rate will cause a flicker in a light source if the value is less than 30Hz. 74Hz is the frequency value to eliminate this flicker effect.

If you’re not fully convinced that the flicker effect results from a PWM frequency of less than 30Hz, modify the script by changing it to freq = 30 and then start the script. Be aware that a flashing light has the potential to trigger an epileptic seizure in some people. Photosensi­tive epilepsy is a form of epilepsy in which seizures are triggered by visual stimuli that form patterns in time or space, such as flashing lights; bold, regular patterns; or regular moving patterns. Restore the line to freq = 74 before continuing with the tutorial.

pwm.start(0)

Callout 2 : We set an initial PWM duty cycle of 0. This will result in the LED being off.

pwm.changeduty­cycle(20) time.sleep(5) pwm.changeduty­cycle(60) time.sleep(5) pwm.changeduty­cycle(90) time.sleep(5)

Callout 3 : The PWM duty cycle parameters are set from 20 to 60 to 90, resulting in lower to higher LED brightness intensity. The higher the duty cycle the longer the LED is on, creating what appears to the human eye as being more light.

Pulsing knowledge

Congratula­tions, you’ve just used signal waveform drawings to create two basic Python scripts to control entirely different circuits.

In the first the angular or linear position of a servomotor was directly related to the width of the pulse in the frequency of the signal applied. In the second the light emitted from an LED is either on or off, so the PWM signal frequency must be greater than 30Hz to eliminate any flicker. The higher the duty cycle, the brighter the LED appears to the human eye.

And done! Basic theory on PWM, two simple circuits and Python scripts running on a Raspberry Pi. Enjoy.

 ??  ??
 ??  ??
 ??  ?? Signals used to swing the actuator arm of a servomotor.
Signals used to swing the actuator arm of a servomotor.
 ??  ?? Waveforms that explain how an LED’S brightness appears to change.
Waveforms that explain how an LED’S brightness appears to change.
 ??  ?? Connection setup for the Python scripts.
Connection setup for the Python scripts.

Newspapers in English

Newspapers from Australia