3.2. Flashing an LED
3.2.1. Our goal
In this tutorial, we are making a Grove Led flash continuously, while it’s being connected to a GoPiGo3 robot.
3.2.2. The code we analyse
The code we’re analyzing in this tutorial is the following one.
# import the EasyGoPiGo3 drivers
import time
import easygopigo3 as easy
# Create an instance of the GoPiGo3 class.
# GPG will be the GoPiGo3 object.
gpg = easy.EasyGoPiGo3()
# create the LED instance, passing the port and GPG
my_led = gpg.init_led("AD1")
# loop 100 times
for i in range(100):
my_led.light_max() # turn LED at max power
time.sleep(0.5)
my_led.light_on(30) # 30% power
time.sleep(0.5)
my_led.light_off() # turn LED off
time.sleep(0.5)
The source code for this example program can be found here on github.
3.2.3. The modules
Start by importing 2 important modules:
import time
import easygopigo3 as easy
The easygopigo3
module is used for interacting with the GoPiGo3 robot, whilst
the time
module is generally used for delaying actions, commands, setting timers etc.
3.2.4. The objects
After this, we need to instantiate an easygopigo3.EasyGoPiGo3
object.
We are using the EasyGoPiGo3
object for creating an instance of Led
class,
which is necessary for controlling the Grove Led device.
gpg = easy.EasyGoPiGo3()
Now that we have an EasyGoPiGo3
object, we can instantiate
a Led
object.
The argument of the initializer method is the port to which we connect the Grove Led and
it’s set to "AD1"
.
my_led = gpg.init_led("AD1")
Note
See the following graphical representation as a reference to where the ports are.
3.2.5. Main part
In this section of the tutorial we are focusing on 3 methods of the easysensors.Led
class.
The
light_max()
method - which turns the LED at the maximum brightness.The
light_on()
method - used for turning the LED at a certain percent of the maximum brightness.The
light_off()
method - used for turning off the LED.
All in all, the following code snippet turns on the LED to the maximum brightness, then it sets the LED’s brightness at 30% and in the last it turns off the LED. The delay between all these 3 commands is set at half a second.
for i in range(100):
my_led.light_max() # turn LED at max power
time.sleep(0.5)
my_led.light_on(30) # 30% power
time.sleep(0.5)
my_led.light_off() # turn LED off
time.sleep(0.5)