LEARN.PARALLAX.COM
Published on LEARN.PARALLAX.COM (https://learn.parallax.com)
Home > LED Lights

LED Lights

 

What it’s About

The LED lights in your kit are similar to those commonly used in products to display the device’s status.  They can be found on keyboards, monitors, alarm system control panels, and printers like the ones below.

The micro:bit has 25 red LEDs in its pixel array.  Those red LEDs contain the same elements; they just come in smaller packages.  Larger LED lights are used in traffic lights and automobile break and turn signal lights.

These activities introduce ways to control indicator light behaviors, including rate, timing, and sequencing.  You will also use your measuring skills to test the LED light’s micro:bit controlled supply voltage with a voltmeter, and learn to use a new device called an oscilloscope to see the relationship between the LED’s supply voltage over time.

Before you Start

These lessons use a specific kit and build on earlier tutorials.

You will need:

  • A What’s a Microcontroller with Python and micro:bit kit (#32750).
  • A computer with a Chrome browser and available USB 2.0 compatible port.

Complete these tutorials first:

  • Get Started with micro:bit and Python
  • Writing micro:bit programs
  • Computer – micro:bit Talk
  • Breadboard Setup and Testing for micro:bit.
  • Electrical Measurements

After You Finish

You will be able to:

  • Write scripts to control individual LED light blink rates
  • Write scripts to control the timing and sequence of multiple LED lights
  • Understand and be able to calculate an on/off signal’s frequency, period, and duty cycle
  • Measure on/off voltages with a voltmeter
  • Probe and display a signal with an oscilloscope

In later activities, you will apply these approaches to “indicate” something that has been sensed.  You will also use them to create slow motion versions of signals that control other devices like position controlling servo motors.

 

Connect and Blink a Light

In this activity, you will connect the LED circuit to a micro:bit I/O pin and use a script to turn the light on and off.  You will also use the script to adjust the on/off rate and number of times it blinks.  Last, but not least, you will calculate the timing of the lights.  The three most common ways to quantify timing are called period, frequency, and duty cycle.  

Parts

Let’s begin by re-using the familiar LED circuit, first built in the Breadboard Setup and Testing for micro:bit tutorial. In addition to the basic micro:bit adapter, power rail, and test post setup, it uses the following parts:

(1) LED – green
(1) resistor 220 Ω (red-red-brown-gold)
(1) jumper wire, black

  • Restore your setup to the way it was in the First Breadboard Circuit chapter’s Build the LED Circuit activity.
  • Remove the alligator clips for now, but leave behind the 3-pin headers.
  • If you just completed the Electrical Measurements chapter, you can leave the voltmeter and ohmmeter circuits, but make sure to remove the ammeter circuit’s 20 Ω resistor.
  • Compare your setup to the picture below, and verify that the circuit, power, and voltmeter connections all match.

Circuit

Instead of connecting the LED to the 3V supply rail on the breadboard, this activity requires a connection with a micro:bit I/O pin.

  • Disconnect the USB cable from the micro:bit.
  • Disconnect the LED circuit’s 220 Ω resistor lead from the bus strip’s 3V (+) column and connect it to P14.  In the picture, it’s connected to the left terminal strip’s (e, 16) socket.
  • Reconnect USB.  Don’t worry if the light doesn’t turn on, you haven’t loaded a script to make it do that yet.

 

Script and Tests

Script: led_blink

Let’s make the LED blink using a micro:bit script.

  • If it’s not already connected, connect your micro:bit module to your computer with its USB cable.
  • If you do not already have the micro:bit Python Editor open, browse to python.microbit.org in a Google Chrome or Microsoft Edge browser.
  • Set the project name field to led_blink.
  • Enter led_blink into the micro:bit Python Editor, then click Save.
    (See Save & Edit Scripts.)  
  • Click Send to micro:bit.
    (See Flash Scripts with Python Editor.)
# led_blink

from microbit import *

while True:
    pin14.write_digital(1)
    sleep(500)
    pin14.write_digital(0)
    sleep(500)

Tests

  • Verify that the green LED blinks on/off at about once every second.

There are lots of different ways to change the timing in the blinking pattern.  Try these examples to understand the cause and effect.  To test a change to the script, click Send to micro:bit.  Then, check the LED light for a changes.  

  • Try changing the sleep(500) calls to sleep(2500), then flash the modified script.  What’s the effect?
  • Try changing the sleep calls from sleep(2500) to sleep(250).  Again, flash the modified script and observe the effect.
  • Repeat using sleep(100) for both sleep calls.  Can you now predict what’s going to happen?
  • How much can you reduce the sleep arguments until it’s hard to tell that it’s blinking?
  • Try sleep(200) after the pin14.write_digital(1) call and sleep(800) after the pin14.write_digital(0) call. What happened?
  • Try reversing the sleep values so that sleep(800) follows pin14.write_digital(1) and sleep(200) follows pin14.write_digital(0). Did it have the effect you anticipated?
  • .Finally, change both sleep calls back to what you started with: sleep(500) and compare it to the previous two options.

 

How it Works

How the led_blink Script Controls the LED Circuit

This animation shows how the led_blink script causes the micro:bit to alternate between connecting P14 to the 3.3 V (+) and GND (-) power connections.  

(View full-size: blink-light-script-circuit-how.mp4)

The first statement in the led_blink script’s while True loop is pin14. write_digital(1).  This causes the micro:bit to connect P14 to its 3.3 V supply.  Since the LED circuit on the breadboard is connected to P14, it turns the light on, just like when you connected it to a socket by the red (+) line in the bus strip. Then, sleep(2500) tells the micro:bit to wait for 2.5 s before continuing.  The effect is that the light stays on during that time.  

When the script reaches pin14.write_digital(0), it causes the micro:bit to connect P14 to its GND (0 V) supply.  This is the same as if you were to connect the LED’s resistor to a socket by the blue (-) line on the bus strip.  Since the other end of the LED circuit is also connected to GND, it means there’s no electrical pressure across the LED circuit, so no current flows through it and the LED does not emit light.  After that, sleep(2500) leaves the light off for 2.5 s before the while True loop repeats.

Try This: Blink Timing

The for …in range(…) loop isn’t just for counting.  You can also use it to repeat statements a certain number of times without making use of the value of the counting variable.  Here is an example where for n in range(0, 10): makes the light blink 10 times.    

  • Change the project name to led_blink_your_turn.  
  • Update your script to match the one below, then click Save.
  • Click Send to micro:bit.
  • Verify that the light blinks 10 times.

 

On-Off Signals


Did You Know: Period, Frequency, and Duty Cycle

In the Tests section, you modified the script to adjust the light’s period, frequency, and duty cycle.  Not all lights blink indefinitely, so after this, you will also experiment with script modifications to make the light blink a certain number of times.

On/off signal period and duty cycle matter because they are used to control many devices other than lights.  Examples include:

  • Ovens where more heating element on-time in relation to off-time translates to more heat
  • Devices use on/off times to exchange information.  For example, a very rapid version of the LED on/off signal where the amount of on time in each on/off repetition controls the position the servo turns to.   

Period is the time it takes for a signal to repeat.  Period is measured in seconds and abbreviated with an upper-case T.  In the case of your LED on/off signal, it’s the sum of the high (on) and low (off) times.  

Example: The LED was on for 0.25 seconds and off for 0.25 seconds.  What is the period?

   T = tHIGH + tLOW
      = 0.25 s + 0.25 s
      = 0.5 s

Frequency is the rate at which the light blinks on/off, in repetitions per second.  Frequency’s abbreviation is f, and its SI unit for measurements is hertz (Hz).  The hertz is named after Heinrich Rudolf Hertz, who did important work to prove the existence of electromagnetic waves.  Examples of electromagnetic waves include visible light and radio waves.

Convert period to frequency (and frequency to period) by making the known value the denominator of 1.  For example, if you know the time it takes a signal to repeat itself (period T), then the frequency is f = 1 / T.  Likewise, if you know the repetitions per second (frequency F), then the period is T = 1 / f.  

   f = 1 / T          T = 1 / f

Example: The period is 0.5 s, what is the frequency?  

   f = 1 / T
      = 1 / 0.5 s
      = 2 Hz

Example: The frequency is 2 Hz, what is the period?  

   T = 1 / f
      = 1 / 2 Hz
      = 0.5 s

SI units 1 Hz = 1/s.  In speaking terms, you can think of 1/s as “one repetition per second or one ’cycle’ per second”.

Duty cycle is a measure of how much time a repeating signal stays on (high) during its period.  It is commonly abbreviated D, DC, or %DC, and most commonly measured as a percent value.  In other words, what percent of the period did the light stay on?  

In the Tests section, you experimented with three different combinations of high and low time at 1 Hz:

Example: Calculate the duty cycle for a signal that is high for 200 ms and low for 800 ms.

   %DC = [ tHIGH / (tHIGH + tLOW) ] x 100 %
            = [ 200 ms / (200 ms + 800 ms) ] x 100 %
            =  0.2 x 100 %
            = 20 %

Example: Calculate the duty cycle for a signal that is high for 200 ms and low for 800 ms.

   %DC = [ tHIGH / (tHIGH + tLOW) ] x 100 %
            = [ 500 ms / (500 ms + 500 ms) ] x 100 %
            =  0.5 x 100 %
            = 50 %

Example: Calculate the duty cycle for a signal that is high for 800 ms and low for 200 ms.

   Answer: 80%


Your Turn: Variable Blink Rates

With a variable, you can also make a light blink at varying rates.  You will try that with the led_blink_variable_rate script.  

  • Change the project name to led_blink_variable_rate.  
  • Update your script to match the one below, then click Save.
  • Click Send to micro:bit.
  • Verify that the light blink rate speeds up and slows back down repeatedly.

In this example, the time variable controls the on/off times.  The time variable is also multiplied by scale variable to increase and decrease the on/off times with each loop repetition.  Initially, scale is 0.7, which causes time to decrease with each loop repetition.  When time drops to 2 or less, scale gets changed to 1.3.  Then, time starts increasing again until scale grows to 300 or more.

Review and Practice

Self-check

  • In this activity, you:
    • built an LED circuit and used a script to turn the LED off and on, adjusting the timing to create different patterns.
    • calculated the period, frequency, and duty cycle.
  • Did you successfully build your LED circuit?
  • Can you adjust the rate at which the LED blinks and create different patterns?
  • Do you understand period, frequency, and duty cycle and can you calculate each?

Questions

  1. What are LEDs used for in products, and what are examples where they are used?
  2. How is period defined?
  3. How is frequency defined?
  4. How is duty cycle defined?
  5. What ways are you able to modify the blink of a light?

Exercises

  1. How would you modify a light on/off loop to change it from blinking every ½ second to blinking every ¼ second?
  2. How do you vary the script so that the time the light is on is longer than the time off?
  3. What sleep values would make the light appear to constantly be on but still be blinking?
  4. What part of the write_digital() statement signals that the light will turn off?
  5. How can the for…in range() loop be used with a light?
  6. If the period length is 1 s and the LED is on for .25 s during the period, how long is the LED off?
  7. If the period is .75 s, what is the frequency?
  8. What is the duty cycle for an LED that stays on for 500 ms and off for 500 ms?
  9. If the duty cycle is 30% and the LED stays on for 300 ms, how long is the period?

Projects

  1. Try adjusting the Try This – Blink Timing script to mimic a typical counting crosswalk signal. What considerations are there?
  2. Some warning lights blink faster as they ‘run out of time,’ for example the classic movie bomb countdown timer. Write a script to mimic this.

 

Solutions

Questions

  1. Answer: They are used to display status in things like alarm control panels, keyboards, monitors, and printers.
  2. Answer: Period is the time it takes for a signal to repeat.
  3. Answer: Frequency is the rate at which the light blinks on/off.
  4. Answer: Duty cycle is a measure of how much time a repeating signal stays on (high) durings its period.
  5. Answer: The period, frequency, duty cycle, and the number of times it blinks are ways to manipulate a light blinking.

Exercises

  1. Answer: Change sleep(500) to sleep(250)
  2. Answer: Make the first sleep value (for pin14.write_digital(1)) higher than the second sleep value.
  3. Answer: sleep values of around 5 will achieve this.
  4. Answer: (0)
  5. Answer: You can use this loop to measure out the number of times a light blinks.
  6. Answer:   
    T = tHIGH + tLOW
    1 = .25 s + tLOW
    tLOW = .75 s
  7. Answer:    
    F = 1 / T
    F = 1 / .75 s
    F = 1 ⅓ Hz
  8. Answer:
    %DC = [ tHIGH / (tHIGH + tLOW) ] x 100%
    = [ 500 ms / (500 ms + 500 ms) ] x 100%
     =  0.5 x 100%
     = 50%
  9. Answer:     
    %DC = [ tHIGH / (tHIGH + tLOW) ] x 100%
    30 = [ 300 ms / (300 ms + tLOW) ] x 100%
    0.3 =  (300 ms / 300 ms + tLOW)
    0.3 x (300 ms + tLOW) = 300 ms
    90 ms + .3(tLOW) = 300 ms
    0.3(tLOW) = 210 ms
    tLOW = 700 ms
    Period = tHIGH + tLOW = 300 ms + 700 ms = 1000 ms

Projects

  1. Solution
from microbit import*
        
for n in range(0, 20):
      pin14.write_digital(1)
      sleep(750)
      pin14.write_digital(0)
      sleep(500)

 

  1. Solution
from microbit import*

time = 1000
scale = .5

for t in range (2500,0,-100):
    
    pin14.write_digital(1)
    sleep(time)
    pin14.write_digital(0)
    sleep(time)

    if t <= 1500:
        scale = .75
    elif t > 1500:
        scale = 1
        
         time = time * scale

 

Set Brightness with a Script

Changing Brightness Digitally

A binary value can hold one of two states: 1 or 0.  Up to this point, we’ve been using those 1/0 binary values to turn lights on and off with pin14.write_digital(1) and pin14.write_digital(0).

In electronics, digital to analog conversion is used to make things seem like they are analog (varying continuously).  For example, with the LED in this activity, you will use the digital values of 0 through 1023 and back to 0 to make the LED light take small steps from dim to bright and then to dim again.  The steps will be so small that human eyes cannot perceive them, so it is called “digital to analog conversion”.    

The pin14.write_analog() method accepts arguments from 0 to 1023 to set the LED’s brightness from off to full brightness.  Here are some examples of write_analog calls that adjust how brightly the P14 LED shines.

pin14.write_analog(1023)             # Max brightness
pin14.write_analog(512)              # half brightness
pin14.write_analog(256)              # quarter brightness
pin14.write_analog(1)                # 1/1024th of full brightness

In this activity, you will experiment with write_analog and scripts that control the brightness of the P14 LED.  You will also use for loops to make this brightness seem to vary continuously (analog).

Circuit

For this activity, you will re-use the same setup and LED circuit from Connect and Blink a Light.

  • Check your setup and circuit to make sure it matches the one shown below. If it does not, return to Connect and Blink a Light and bring it up to date.

 

Script and Tests

Script: led_brightnesses

This script sets a light to ⅛, ¼, ½, and full brightnesses.

  • Change the project name to led_brightnesses.  
  • Update your script to match the one below, then click Save.
  • Click Send to micro:bit.
# led_brightnesses

from microbit import *

while True:
    pin14.write_analog(128)
    sleep(1000)
    pin14.write_analog(256)
    sleep(1000)
    pin14.write_analog(512)
    sleep(1000)
    pin14.write_analog(1023)
    sleep(1000)

Test the LED Brightnesses

  • Look straight down at the top of the LED’s dome, and verify the four different brightnesses.

 

How it Works

How the led_brightnesses Script Works

Remember from the Connect and Blink a Light activity’s On-Off Signals section that a blinking light has a period, frequency, and duty cycle.  The period is the total on/off time for a single blink, abbreviated T and measured in s.  The frequency is the blinks per second, abbreviated f and measured in Hz.  The duty cycle is the percent of the period that the light is on.

The write_analog() method makes the light blink at 50 times per second (f = 50 Hz).  That’s faster than the eye can see, but the eye does detect the high time of each blink as brightness.  If the light is on for ½ the time, it appears to be half as bright.  On for ¼ of the time -¼ as bright, and so on…

Remember that the period is 1/f.  In the case of write_analog, the micro:bit sets the light’s blink period to T = 1/50 Hz = 20 ms.  You have 1024 options for how long the light stays on during the 20 ms period — from 0/1024ths to 1023/1024ths of the time.  For 50% duty cycle (and 50% brightness), use pin14.write_analog(512).  That’ll give you 512/1024ths of on time, which is 50%.

Example: Set the brightness to 25%.
Solution: For 25% brightness, we need 25% duty cycle.  0.25 x 1024 = 256, so use 256 in write_analog, like this: pin14.write_analog(256).

Try This: Brightness Fade-in

Here is an example that uses a for loop inside a while loop to repeatedly fade-in brightness from 0 to max (1023).

  • Change the project name to led_brightnesses_loop_up.  
  • Update your script to match the one below, then click Save.
  • Click Send to micro:bit.
  • Watch the LED gradually go from completely off to fully on.

     

    More About A/D


    Did You Know: About D/A Converters

    In the physical world, analog quantities like light intensity and audio volume are continuously variable.  Think of “continuously variable” as having an infinite number of increments in any range.  Like the blue analog line in the diagram.  It’ll have values like 514.00… and 515.00…, but between those two levels, there’s an infinite number of other levels.  Two examples include 514.33… and 514.66…  

    In electronics, analog quantities are represented by digital steps, like the orange 509 through 515 integer steps in the diagram.  Many electronic devices store digital step values and use them to synthesize analog values.  In addition to the light intensity example we are working with, music and video streaming use digitized audio and video data.  But, the steps in the digitized values are so close together that we cannot hear/see the difference.    

    In the case of the micro:bit, it can set the LED to 1024 different brightnesses (including off).  If it increases by one increment at a time, it looks like it varies continuously, but it’s actually stepping from one brightness to the next.  Even so, it is commonly called an “analog” setting, and the process of converting a number in the 0 to 1023 range to an LED brightness is a form of “digital to analog conversion”.

    Digital to analog conversion devices normally have a number of steps that is some power of two.  For example, 1024 is 210.  The power of 2 is actually a memory size, measured in “bits” which are memory elements that can store binary digits: 1 or 0.  In the case of the micro:bit D/A converter, it’s called a 10-bit digital to analog converter.  With 10 bits or memory (10 binary 1/0 digits), you can count from 0 through 1023:

    Decimal    Binary (10-bit)
    1          0000000001
    2          0000000010
    3          0000000011
    4          0000000100
    5          0000000101
    6          0000000110
    7          0000000111
    …
    509        0111111101
    510        0111111110
    511        0111111111
    512        1000000000
    513        1000000001
    514        1000000010
    515        1000000011
    …
    1021       1111111101
    1022       1111111110
    1023       1111111111

    Small Code Tests before Using Larger Values

    Sometimes, it’s helpful to test a small loop to figure out what a larger one will really do.  For example, you could use this script to quickly see what the result of a for…in range() loop with one argument will be.  Since it prints 0, 1, 2, and 3, it can help verify that it counts from 0 up to, but not including, the value in the parentheses.

    for n in range(4):
        print(n)

    Another approach would be to look it up in the Python language documentation.  For example, the answer is on this page too: 4. More Control Flow Tools.  It’s part of the Python 3 Documentation, which is what the MicroPython for the micro:bit is based on.

    One way to make the brightness fade in and then fade back out would be to have a loop that counts up, like the one you just tried, followed by a loop that counts back down. Counting down with range needs a start, stop, and negative step value.  For example, this for loop counts 5, 4, 3, 2, 1:

    for n in range(5, 0, -1):
        print(n)

    Extending that to the for brightness loop, you could use for brightness in range(1023, 0, -1).  This would start at maximum brightness and count down to a brightness of 1.  That loop following the fade-in loop would fade the brightness back out.  


    Your Turn -Brightness Fade-in Fade-out

    Let’s try the fade-in, fade-out effect explained in the try Did You Know section above.

    • Change the project name to led_brightnesses_loop_up_loop_down.  
    • Update your script to match the one below, then click Save.
    • Click Send to micro:bit.
    • Verify that the LED brightness repeatedly increases and decreases.

    Review and Practice

    Self-check

    • In this activity, you:
      • played with scripts and the write_analog() method to control the brightness of an LED assigned to a specific pin and
      • used loops with these scripts.
    • Were you able to calculate the appropriate values for write_analog() to get the desired brightness?
    • Were you able to use for/n in range() to adjust how the LED performed?  

    Questions

    1. What frequency does the write_analog() method set for the light blink?
    2. A change in the high time for each light blink will appear to the eye as a change in what?
    3. What is the range for how long the light stays on using the write_analog() method?
    4. What values are needed in  a for…in range() loop to make it count values down?

    Exercises

    1. To reduce the brightness of the light by ⅛, you need to change the argument of pin14.write_analog(1023) to what value?
    2. Calculate the necessary value for the write_analog()argument for 50% brightness.
    3. Calculate the necessary value for the write_analog() argument for 3/4th  brightness.
    4. Insert the necessary values in the following loop to make it count down by a step of 2 from 100 through 2. for n in range ( ).
    5. Write a for…in range() statement that will gradually increase the brightness of the LED to half its maximum value.

    Project

    • Some sleep alarms increase in brightness to gently wake you and then try again if it doesn’t work. Alter the speed of the change and pauses in brightness to create this effect.

     

    Solutions

    Questions

    1. Answer: 50 Hz
    2. Answer: Brightness
    3. Answer: 0 – 1024
    4. Answer: A start, stop, and (negative) step value.

    Exercises

    1. Answer: change pin14.write_analog(1023) to pin14.write_analog(128)
    2. Answer: 1024 x 0.5 = 512
    3. Answer. 1024 x 0.75 = 768
    4. Answer: for n in range(100, 1, -2)
    5. Answer: for brightness in range(512)   Note: the variable name is up to the student.

    Project

    Solution:

    from microbit import*
    
    while True:
        for brightness in range(0,1023,10):
            sleep(500)
            pin14.write_analog(brightness)
                    sleep(1000)

     

    Add a Light

    Add a Second LED Light

    In this activity, you will:

    • Add a second LED light circuit to your board.
    • Write scripts with variations of digital_write() to blink the two lights:
      • In tandem
      • Alternating
      • Sequentially

    Parts

    (1) Setup from Connect and Blink a Light including the green LED circuit parts.
    (1) LED – yellow
    (1) Resistor – 220 Ω (red-red-brown-gold)
    (1) Jumper wire (black)

    Circuit

    To build the LED circuits in the picture shown below:

    • Move the green LED circuit down from row 16 to row 17. 
    • Connect the green LED to micro:bit P13 with the 220 ohm resistor.
    • Build the yellow LED circuit on row 13, and connect it to micro:bit P13.

     

    Script and Tests

    This script will test your LED circuits by blinking them on/off together.

    Script: led_blink_x2

    • If it’s not already connected, connect your micro:bit module to your computer with the USB cable.
    • If you do not already have the micro:bit Python Editor open, browse to python.microbit.org in a Google Chrome or Microsoft Edge browser.
    • Set the project name field to led_blink_x2.  
    • Update your script to match the one below, then click Save.
    • Click Send to micro:bit.
    # led_blink_x2
    
    from microbit import *
    
    while True:
        pin13.write_digital(1)
        pin14.write_digital(1)
        sleep(500)
        pin13.write_digital(0)
        pin14.write_digital(0)
        sleep(500)

    Tests: On/Off Together

    • Verify that BOTH LEDs blink on/off once every second.
    • Try changing the sleep(500) to sleep(250) in both calls and verify that both LED’s blink in unison, twice as fast.

     

    How it Works

    How the led_blink_2x Script Works

    These statements repeat indefinitely inside the while True loop:

    • The pin13.write_digital(1) method call sets a high signal through P13, turning on the green light.  
    • The pin14.write_digital(1) call does the same thing but through P14, turning on the yellow light.
    • The sleep(500) call makes the script pause for 0.5 s.  The lights stay on during this time.
    • The pin13.write_digital(0) and pin14_write_digital(0) calls set P13 and P14 low, turning the LED lights off.
    • The sleep(500) call makes the script pause for another 0.5 s, during which time, the lights stay off.

    Try This: On/Off Alternating

    Changing from simultaneous to alternating blinks is pretty simple.  All you have to do is change the state argument in two of the pin14.write_digital calls.

    • Change the line 1 comment and the project name field to led_blink_2x_alternating.  
    • Change the first pin14.write_digital call’s state argument from 1 to 0.
    • Change the second pin14.write_digital call’s state argument from 0 to1.
    • Click Save and then click Send to micro:bit.
    • Verify that only one light is on at a time, and that they alternate.

     

    Sequential Blinks


    Did You Know: Simultaneous vs. Sequential

    Up to this point, it looks like both lights change at the same instant.  In reality, the P13 light turned on a tiny fraction of a second before the P14 light.  That’s because the micro:bit executes statements in a script sequentially—one after another.  Since pin13.write_digital() comes before pin14.write_digital() in the script examples, the P13 light changes first. The P14 light changes an instant AFTER the P13 light.  

    In the current script, the time between light changes for P13 and P14 is not visible to the human eye. You can make it visible by adding a sleep statement between the two write_digital() calls (along with other changes).


    Your Turn: On/Off Sequentially

    Sequential blinking takes a few more changes since the script has to turn one light on/off, and then turn the other light on/off afterwards.  In this approach, the script turns the P13 light on and off first, then follows with the P14 light.

    • Change the line 1 comment and the project name field to led_blink_2x_sequential. 
    • Enter the script shown below, then click Save.
    • Click Send to micro:bit.
    • Verify that the P13 light turns on and off, then the P14 light turns on and off.  

     

    Review and Practice

    Self-Check

    In this activity, you learned how to use the digital_write() method to blink two lights in various arrangements to each other.

    • Were you able to blink the two lights together? Alternately?
    • Were you also able to get the two lights to blink in a sequence?
    • Thinking back over the last several activities. Do you understand the difference between how to work with write_analog and write_digital?

    Questions

    1. When using the write_digital() method, how do you change the length of time the light stays on?
    2. In what order do the statements execute?
       

    Exercises

    1. Change the blink rate in the following statement to 1/10 th of a second: sleep(500).
    2. What two “write” methods can be used to turn LEDs on and off?.
    3. Which “write” method turns the LED on for part of a period, adjusting the brightness level?
    4. Which loop keeps the statements repeating indefinitely?
    5. How can you easily change the script from two lights blinking simultaneously to blinking alternately?
    6. In which situation(s) are pin().write_digital() statements for blinking LEDs paired ahead of a sleep() statement: alternating, sequential, or simultaneous?
       

    Project

    Create a script that holds the green LED on while the yellow LED turns on and off. Place the code for the green LED outside the while True() loop.

    Solutions

    Questions

    1. Answer:  Use the sleep() function.
    2. Answer: Sequentially within loops.

    Exercises

    1. Answer:  change sleep(500) to sleep(100)
    2. Answer:  write_analog() and write_digital()
    3. Answer:  write_analog()
    4. Answer: while True
    5. Answer:  Change the values in the pair of write_digital() statements for the lights from 0,0 and 1,1 to 1,0 and 0,1
    6. Answer:  alternating and simultaneous
       

    Project

    Solution:

    from microbit import*
    
    pin13.write_digital(1)
    
    while True:
        
        pin14.write_digital(1)
        sleep(500)
        pin14.write_digital(0)
        sleep(500)

     

    Intro to Lists

    In the next activity, you will be adding a third LED light, and then turning them on/off in custom sequences.  It’s true that you could extend the coding approach you used for two LEDs, but there’s a better way: lists.  (We’ll practice lists using a serial terminal first, so there is no circuit needed for this activity).

    About Lists

    A list is a sequence of items contained between brackets, like this:

    clist = [’green’, ’yellow’, ’red’]

    A script can access an item in a list by using the item’s index value, starting with 0 from left to right. So, the index of ’green’ is 0, ’yellow’ is 1, and ’red’ is 2.  The instruction print(clist[2]) would display the word “red” in a serial terminal.  A script can also change items a list using index values. For example, to change clist[1] from ’yellow’ to ’blue’ you would use clist[1] = ’blue’.

    In this activity, you will use lists to display different sequences of printed colors in the terminal.  In the next activity, you will instead use the lists to make the colored lights display in various sequences.

    There are different ways to display items in a list. This activity will start by displaying items in a list “the hard way” because it’s good to get familiar with how to access items in a list by their index values.  The Try This section introduces “the easy way” to access each item in a list with a loop that does the indexing for you.  Last, but not least, the Did You Know and Your Turn sections show how to use your script to change, append, and display the contents of lists.  

    Script: first_list

    This first script repeatedly displays this in the python.microbit.org Serial terminal.  

    color = green
    color = yellow
    color = red  

    • Set the project name field to first_list.
    • Enter script below into the micro:bit Python Editor, and then click Save.
    • Click Send to micro:bit.
    # first_list
    
    from microbit import *
    
    clist = ['green', 'yellow', 'red']
    index = 0
    
    while True:
        color = clist[index]
        print('color =', color)
        sleep(1000)
        index = index + 1
        if index >= len(clist):
            index = 0
            print()

    Tests

    • Click the Show seriaal button to open the serial monitor.
      (See Use the Serial Monitor.)
    • Verify that the color = green, color = yellow, color = red sequence displays repeatedly in the terminal.

     

    How it Works

    How the first_list Script Works

    • Watch the animation as it steps through the first_list script and displays variable values and data. (Or view full size with play/pause control: list-how-it-works.mp4.)
    • Pay careful attention to the index values, and how they control which string gets stored by the color variable and displayed.

    In the script, clist = [’green’, ’yellow’, ’red’] creates a list with three items: clist[0] is ’green’, clist[1] is ’yellow’, and clist[2] is ’red’.  The value of the index variable starts at zero.  Inside the while True loop, color = clist[index] stores ’green’ in color when index is 0, ’yellow’ in color when index is 1, or ’red’ in color when index is 2.  Each time through the loop, index = index + 1 increases the value of index by 1.  Before repeating the loop, if index >= len(clist) statement compares the value of index to the number of elements in the list.  When index reaches 3, the statement evaluates to true, and index is set back to 0.

    Try This: Lists the Easier Way

    Yes, there is an easier way!  A for color in clist: loop will automatically copy each successive item in clist into the color variable.  If your script just needs to cycle through items in a list, this is the way to go!

    • Set the project name field and line-1 comment to first_list_try_this.
    • Modify the script as shown below, then click Save.
    • Click Send to micro:bit.

     

    • If the serial monitor isn’t already open, click Show serial.
    • Verify that the output matches the first example.

     

    Other Data Types in Lists


    Did You Know: Other Data Types in Lists

    Even though you have been working with lists of strings, lists can contain other data types, like int, and a microbit.pin object.  Different types can even appear in the same list.  

    my_list = ['yellow', 1000, pin14]

    Lists can be changed after they are created.  In Python-speak, the term is mutable.  Here are some ways to change lists in a script:

    clist[1] = 'blue'         # replaces 'yellow' to 'blue'
    
    clist.append('yellow')    # adds 'yellow' as the last item in the list
    
    clist.index('red')        # finds the first instance of 'red' in the
                              # list and returns the index

    Your application can even use both list items and their index values in a list; here is an example that uses a for loop.  Note how it uses len(clist) instead of 3.  The len(clist) call returns the length of the list.  It is currently 3, but if you added items to the list, the result of a call to len(clist)would automatically increase.  

       for index in range(len(clist)):
            color = clist[index]
            print('index:', index, ', color:', color)
            sleep(1000)
        print()

    Here is another example that uses enumerate instead of in range.  Enumerate returns 2 values (a tuple) that contains the index number in the list and the item.  In this example, the index number gets copied to the variable named index, and the color string (’green’, ’yellow’, or ’red’) gets copied to the variable named color.

           for index, color in enumerate(clist):
            print('index:', index, ', color:', color)
            sleep(1000)
        print()    

    Your Turn

    Here is the script from the Try This section on the previous page  with statements from the Did You Know section above added.  It replaces ’yellow’ with ’blue’, adds ’yellow’ after ’red’, and gets the index of ’red’.

    • Change the project name and line 1 comment to first_list_your_turn.
    • Modify the script as shown below, and then click Save.
    • Click Send to micro:bit.

     

    • If the serial monitor isn’t already open, click Show serial.  
    • Verify that the output matches the example below.

    • Set the project name and line 1 comment to first_list_your_turn_with_index.
    • Use the tips in the Try This section at the bottom of the previous page to modify your script so that it displays both the index and the color.
    • Verify your solution by making sure the serial monitor displays this.
    • Sfter debugging to get it to work, click Save.

     

    Review and Practice

    Self-check

    In this activity, you used lists to display different sequences of color names in the serial terminal.

    • Were you able to use both methods – the easy way and the hard way?
    • Were you able to create the script to display the color names?
    • Were you able to modify and access the color list in your script?
    • Lastly, do you understand how to create and access any list?

    Questions

    1. How does a script access the items in a list?
    2. How are index items numbered?
    3. What types of data can a list contain?
    4. What does it mean for a list to be mutable?

    Exercises

    1. In list nlist = [’Ava’, ’Marco’, ’Jubal’, ’Maria’], which item has an index of 3?
    2. If index = len(nlist) for the list: nlist = [’Ava’, ’Marco’, ’Jubal’, ’Maria’], what is the value of index?
    3. How would you change the last item in the list, vlist = [1, 2, 3, 4, 6], to a 5?
    4. How do you add an item to the end of a list?
    5. What is the function of using the line clist.index(‘snake’) in a script?

    Project

    There’s an easy way and a hard way to cycle through items in a list. Using the variable city and the list name c, write the code for a 4-item list of cities with a while True loop that will print them the ‘easy’ way.
     

    Solutions

    Questions

    1. Answer: A script accesses the items in a list using the index number.
    2. Answer: They are numbered sequentially left to right starting with 0.
    3. Answer: A list can contain information like strings, int, and micropython.pin objects.
    4. Answer: Mutable means that a list can be changed after it is created.

    Exercises

    1. Answer: Maria
    2. Answer: 4
    3. Answer: vlist[4] = ’5’
    4. Answer: Use clist.append()
    5. Answer: It will return the index of the first instance of the word “snake” in the clist.

    Project

    Solution:

    clist = [‘city1’, ‘city2’, ‘city3’, ‘city4’]
    
    while True:
        for city in clist:
            print(‘city = ’, city)
            sleep(1000)
        print()

     

    Blink Sequencing

    In Add a Light you built a second LED and wrote scripts to control both of them.  In Intro to Lists, you got to see how to create and access lists.  In this activity, you will add a third LED, and then use lists to set up custom LED on/off sequences.  You will even use a list of LED pins and a list of on times in the same for loop to fully customize the light sequence.

    Parts

    (1) Setup from Add a Light
    (1) LED – Red
    (1) Resistor – 220 Ω (red-red-brown-gold)
    (1) Jumper wire (black)

    Circuit

    • Disconnect USB.
    • Connect a red LED to P15.  Build it above the yellow and green LEDs so that it looks like a stop light (red above yellow above green).
    • Reconnect USB.

     

    Script and Tests

    Script: led_blink_list

    This script will blink the LEDs in sequence according to a list named pin_list.

    • Set the project name field to led_blink_list.
    • Enter script below into the micro:bit Python Editor, and then click Save.
    • Click Send to micro:bit.
    # led_blink_list
    
    from microbit import *
    
    pin_list = [pin13, pin14, pin15]
    
    while True:
        for pin in pin_list:
            pin.write_digital(1)
            sleep(500)
            pin.write_digital(0)

    Tests

    • Verify that the lights repeat the same sequence over and over: green for 0.5 s, yellow for 0.5 s, and then red for 0.5 s.
    • Try changing sleep(500) to sleep(100) and flash the modified script. Did you anticipate the effect of this change correctly?

     

    How it Works

    How led_blink_list Works

    Instead of string objects like ’green’, ’yellow’, and ’red’, the list in this example contains microbit.pin objects: pin13, pin14, and pin15.

    pin_list = [pin13, pin14, pin15]
    
    while True:

     

    The first time through the for pin in pin_list loop, pin gets set to pin13.  So, in the first pass, pin.write_digital(1) is really pin13.write_digital(1), which turns the P13 light on.  Likewise, pin.write_digital(0) is really pin13.write_digital(0), which turns the P13 light off.  

        for pin in pin_list:
            pin.write_digital(1)
            sleep(500)
            pin.write_digital(0)

     

    The second time through the loop, pin is pin14, so pin.write_digital(1) is really pin14.write_digital(1), and pin.write_digital(0) is really pin14.write_digital(0).  The third time through the loop, pin is pin15.  So, pin.write_digital(1) and pin.write_digital(0) are really pin15.write_digital(1) and pin15.write_digital(0).  

    Try This: Up/Down Sequence

    Sometimes a little change can make a big difference in the way something behaves.  For example, adding just one pin to the list will make the sequence look like the lights bounce back and forth between red and green.

    • Set the project name field and line-1 comment to led_blink_try_this.
    • Modify the script as shown below, then click Save.
    • Click Send to micro:bit.
    • Verify that the sequence is now green, yellow, red, yellow, green, yellow, red, yellow, green, …

     

    Zip Lists Together


    Did You Know: zip() Function

    Sometimes, a Python script needs a loop to access each successive item in more than one list.  For example, maybe each color has a corresponding on-time in a different list.  When used in place of in range(), Python’s zip() function makes this easy.  Here’s an example:

    # lists_with_zip
    
    from microbit import *
    
    color_list  = ['green', 'yellow', 'red']
    time_list   = [ 1000,    200,      500]
    
    for color, time in zip(color_list, time_list):
        print('color:', color, '| time:', time)
    
    print('Done!')

    The first time through the loop, the color variable stores ’green’, while the time variable stores 1000.  The second time through, color is ’yellow’,  and time is 200.  The third time through, color is ’red’ and time is 500.  Each time through the loop,  print(’color:’, color, ’| time:’, time) displays both variables.
     


    Your Turn: Add a Times List

    Now that you’ve seen how to use a single loop with the zip() function to access related items in more than one list, let’s try it with custom LED on-times.

    • Click Open and reopen led_blink_list.hex.
    • Set the project name field and line-1 comment to led_blink_list_your_turn.
    • Modify the script as shown below, then click Save.
    • Click Send to micro:bit.
    • Check to make sure that the green light stays on for about a second, the yellow light stays on for about 1/5th of a second, and the red light stays on for about half a second.

     

    Review and Practice

    Self-check

    • In this activity you:
      • Added a third LED to your breadboard, and
      • Used lists to customize some LED on/off sequences.
    • Were you successfully able to create the third LED circuit?
    • Do you understand how to use microbit.pin objects in a list?
    • Can you accurately use the zip() function and modify the LED on/off sequences?

    Questions

    1. What are two types of objects can you include in a list?
    2. Which function did you use to access two lists at the same time?
    3. Which statement accesses the pin to turn the LED on and off.

    Exercises

    1. What type of information is in this list? location_list = [pin9, pin12, pin16]:
    2. What values turn the LEDs on and off?
    3. Describe what this line does: for time, temp in zip(time_list, temp_list):
    4. Create two short lists for names and scores then write a line of code that will match the name list with the score list.

    Project

    Create a script that turns the green on constantly for 10s, then flashes the yellow, and then finally ends with a solid red.
    Solution.

     

    Solutions

    Questions

    1. Answer: You can put string and microbit.pin objects in lists.
    2. Answer: The zip() function.
    3. Answer: write_digital()

     

    Exercises

    1. Answer: microbit.pin objects
    2. Answer: 0 and 1
    3. Answer:  This line creates a loop (for) that will aggregate (zip) the time and temp lists (time_list, temp_list) to more efficiently use them for some purpose like printing to the terminal. Each item from the list will be assigned to the variables time and temp respectively.
    4. Answer:
    name_list = [Emmanuel, Izzie, Inez, Jon]
    score_list = [456, 435, 482, 421]
    for name, score in zip(name_list, score_list):

     

    Project

    Solution:

    from microbit import*
    
    while True:
        
    pin13.write_digital(1)
            sleep(10000)
            pin13.write_digital(0)
    
            for n in range(0, 10):
            
                pin14.write_digital(1)
    sleep(200)
            pin14.write_digital(0)
            sleep(200)
    
            pin15.write_digital(1)

     

     

    Measure Blinking Light with a Voltmeter

    In this activity, you will send very slow on/off signals to the P13 LED light circuit and measure the voltage that the I/O pin supplies to turn the light on and off.  By slowing down the highs and lows, you will be able to measure the voltages the P13 pin supplies to the green LED.   

    Parts

    Setup from Blink Sequencing.
    (2) Alligator clip probes connected for voltmeter functionality, like in the Parts and Circuit from First Electrical Connections with a Breadboard
    (1) 1 kΩ resistor (for the Your Turn section).

    Circuit

    • Connect the red P2 probe to P13.  That would be b, c, or d in row 17.
    • Connect the black P0 probe to the right bus strip’s (-) columns.
    • IMPORTANT: Make sure that a 20 Ω resistor IS NOT plugged into the left terminal strip’s (b, 28) and (b, 30) sockets.

     

    Script and Tests

    Script: led_blink_with_voltmeter

    • Right-click led_blink_with_voltmeter.hex (below), and choose Save Link As…to download.

    led_blink_with_voltmeter.hex

    • Click the micro:bit Python Editor’s Open button, and then select and open led_blink_with_voltmeter.hex. 
    • Click Send to micro:bit.  
    • Click the three vertical dots  ⋮  by the Send to micro:bit button, and select Disconnect.
    • Start the CYBERscope:
      • In a different browser tab, go to cyberscope.parallax.com.  
      • Click the CYBERscope’s Connect button.
      • In the serial port dialog, select the port with mbed in its name, and then click Connect. 

    Tests

    IMPORTANT: Your LED on voltage measurements might be considerably higher than the 2.65 V measurements shown below.  Basically, if you get anything in the 2.5 to 3.3 V range, assume it’s good.

    • When the light turns on, check the CYBERscope voltmeter to see what voltage it applies to the circuit.  There may be a delay of a second or so between when the light turns on and when the measurement updates.

    • Repeat the voltage measurement for the LED off state.

     

    How it Works

    How It Works: led_blink_with_voltmeter

    Earlier, we learned that the micro:bit’s microcontroller connects a pin like P13 to its 3.3 V supply in response to pin13.write_digital(1) and to its 0 V (GND) supply in response to pin13.write_digital(0).  It looks like the 0 V (GND) signal checks out, but why does it only supply 2.65 V to turn the LED light on?

    The answer is that the transistors inside the micro:bit that make connection between an I/O pin and 3.3 V have some internal resistance.  With current for the LED circuit flowing through that internal resistance, the result is a voltage drop of 0.55 V inside the micro:bit, leaving 2.65 V for the LED circuit.  This I/O pin behavior is called voltage drop under load.  Again, your measurements could vary, and the variations will depend on temperature, version of micro:bit, and even microcontroller manufacturing variations from one batch to the next.

    This script started as led_blink from Connect and Blink a Light.  Aside from the fact that the green light was moved from P14 to P13, the led_blink_with_voltmeter script has two main differences.  First, it has from multimeter import *, which has functions for measuring voltage and displaying it with the CYBERscope.  Second, it measures voltage with voltmeter(device=”CYBERscope”) after each pin13.write call.  This function call measures the voltage between the P2 and P0 alligator clips and sends the measurement data to the CYBERscope to be displayed.

    # led_blink_with_voltmeter
    
    from microbit import *
    from multimeter import *                  # <-- added
    
    while True:
        pin13.write_digital(1)
        voltmeter(device="CYBERscope")        # <-- added
        sleep(2500)
        pin13.write_digital(0)
        voltmeter(device="CYBERscope")        # <-- added
        sleep(2500)
        

    Try This: Float the P13 Resistor Lead

    Here, you will test I/O pin voltage without any load.  You will do this by disconnecting the circuit “load” from the I/O pin “supply.”

    • Unplug the resistor lead that’s connected to the left terminal strip’s (e, 17) socket.
    • Leave the other end where it is, plugged into the right terminal strip’s (a, 17) socket.
    • Unbend the resistor leads to make it point straight up in the air.  In electronics-speak, this is sometimes called “floating” the lead.
    • Repeat your voltage measurements.
    • Do the measurements now oscillate between about 3.3 V and 0 V?
    • Reconnect the resistor to the left terminal strip’s (e, 17) socket when you are done.

     

    Change the Resistance


    Did You Know: Load or No Load?

    In the main activity, you measured the I/O pin high voltage under load.
    In the Try This section, you measured the I/O pin high voltage with no load.
    In both activities the I/O pin low voltage was not under load because it was trying to supply 0 V to a circuit that had 0 V (GND) at the other end.  No electrical pressure was applied, so no current was flowing through the circuit.  Thus, no current “load” on the I/O pin.


    Your Turn: Change the Resistor Value

    • Try replacing the 220 Ω resistor with a 1 kΩ (brown-black-red-gold) resistor.  
    • Repeat the high and low signal I/O pin voltage measurements.  

    What I/O pin voltage under load did you observe?  What is your explanation?  

    • Make sure to put the 220 Ω resistor back before moving to the next activity.

     

    Review and Practice

    Self-check

    In this activity, you used a voltmeter to measure the voltage supplied by the I/O pins to turn the LED on and off in the P13 LED light circuit.

    • Were you able to slow down the blink to take the measurements with the voltmeter?
    • Do you understand why there is a change in the voltage when using different size resistors?

     

    Questions

    1. How many volts is the supply voltage for your micro:bit circuit?
    2. Why is the measured voltage across the circuit closer to 2.65 V than 3.3 V?
    3. What is it called when you disconnect the circuit load from the supply?
    4. What happens to the voltage through the circuit when you put in a bigger resistor?
       

    Exercises

    1. What line allows the script to access voltage measuring functions and display with the CYBERscope?
    2. The voltmeter() function is used to measure what?
    3. What allows the voltmeter to measure both the high and low signals?

     

    Project

    Use the voltmeter to check the voltage across the yellow LED circuit. Confirm that it is similar to that of the green LED circuit.
     

     

    Solutions

    Self-check

    Questions

    • Answer: 3.3 V
    • Answer: It is closer to 2.65 V because the transistors inside the microcontroller create some internal resistance causing a voltage drop under load.
    • Answer: “floating” the lead
    • Answer:  There is an increase in voltage.

     

    Exercises

    • Answer: from multimeter import*
    • Answer: voltage
    • Answer: Pin 13 is set to both high and low through pin13.write_digital() with each followed by a measurement call.
       

    Project

    Solution: Make sure to change the pin in the script to 14. The reading should be approximately 2.95 V.

     

    Measure Light with an Oscilloscope

    An oscilloscope is an instrument that graphs voltages over time.  Engineers and technicians use them to check voltage signals, especially ones that repeat too rapidly to measure with a simple voltmeter. 

    In this activity, you will:

    • Use an oscilloscope to graph the LED voltages over time.
    • Examine how changing the duty cycle “looks” in an oscilloscope voltage vs. time graph.
    • Use the Time/Div control to “zoom in” on the time axis to see more voltage “signal detail.”

    Parts & Circuit

    Same as Measure a Blinking Light with a Voltmeter (shown again below.)

    Script and Tests

    Script: led_blink_with_plot

    • Right-click led_blink_with_plot.hex (below), and choose Save Link As…to download.

    led_blink_with_plot.hex

    • Click the micro:bit Python Editor’s Open button, then select and open led_blink_with_plot.hex. 
    • Click Send to micro:bit.  
    • Click the three vertical dots  ⋮  by the Send to micro:bit button, and select Disconnect.
    • Start the CYBERscope:
      • In a different browser tab, go to cyberscope.parallax.com.  
      • Click the CYBERscope’s Connect button.
      • In the serial port dialog, select the port with mbed in its name, and then click Connect. 

    Tests

    • Set the Time/Div dropdown to 500 ms.
    • Verify that your plot resembles the picture below. You should see equally spaced squared peaks slightly above 2.5 V and dropping to 0 V.

     

    How it Works

    How led_blink_with_plot Works

    An oscilloscope plot graphs voltage over time.  Since your script turns the light on for 500 ms, then off for 500 ms, the plot shows the voltage repeatedly stays at 2.65 V for about half a second and then at 0 V for half a second.

    As you can see the script timing is not precise.  It spends more than more than 500 ms high and low.  The reason for this is because it takes the micro:bit time to execute each statement, and it also takes time for it to send that data to the CYBERscope.  

    When you adjusted the Time/Div from 1000 ms to 500 ms, you changed the x-axis increments from 1000 ms to 500 ms.  The total amount of time it graphed dropped from 10,000 ms to 5000 ms.

    This script also started as led_blink from Connect and Blink a Light.  Again, the multimeter module is imported for sending data to the CYBERscope.  The plot data is sent to the CYBERscope with plot(volts(pin2),”y2″).  The plot function sends data to the CYBERscope formatted so that it can be plotted in the oscilloscope display.  The value it sends is volts(pin2), which measures the voltage with the P2 pin (through the red alligator clip lead).  The “y2” text string is forwarded to the CYBERscope, which results in the data being plotted on its red channel 2 (ch2) trace.

    # led_blink_with_plot                     # <-- changed
    
    from microbit import *
    from multimeter import *                  # <-- added
    
    while True:
    
        pin13.write_digital(1)
        sleep(1)                              # <-- added
        plot(volts(pin2), "y2")               # <-- added
        sleep(499)                            # <-- changed
        plot(volts(pin2), "y2")               # <-- added
    
        pin13.write_digital(0)
        sleep(1)                              # <-- added
        plot(volts(pin2), "y2")               # <-- added
        sleep(499)                            # <-- changed
        plot(volts(pin2), "y2")
    

    The measurements have to be plotted before and after each pin13.write_digital call.  Normal oscilloscopes send many data points; whereas, this script sends just the points before and after each signal level change.  The sleep(1) is added between each pin13.write_digital call to give the voltage enough time to rise to its final value.

    If you are curious why the sleep wasn’t needed for the voltmeter but is needed here, it’s because voltmeter() measurements are actually the average of ten measurements, taken every 10 ms.  In contrast volts() is a single measurement.

    Try This: 25% Duty Cycle

    In the main activity, you experimented with a 50% duty cycle signal.  The high and low times were equal, and the plot showed that.  Here, you will change it to a 25% duty cycle and observe the differences in the CYBERscope.

    • In the script, try changing the first sleep(500) to sleep(250) and the second sleep(500) to sleep(750).
    • Click the CYBERscope’s Disconnect button.
    • In the micro:bit Python Editor, Send to micro:bit.
    • Click the three vertical dots  ⋮  by the Send to micro:bit button, and select Disconnect.
    • Back in the CYBERscope, click the Connect button.
    • Verify that the plot now resembles the image below.  See how the plot shows the signal as high (around 2.65 V) for about 250 ms and low (0 V) for about 750 ms?

    • Try taking a closer look at the signal timing by changing the Time/Div dropdown to 250 ms.  
    • Verify that the result should resemble the image below. Can you see what changed?

     

    Setting a Trigger


    Did You Know: Oscilloscope Triggers

    Oscilloscopes have a trigger feature that allows you to position the entire plot on the screen relative to a certain trigger time and trigger voltage.  The trigger event can be rising or falling.  If the trigger event is rising, it means that the voltage rose above the trigger voltage.  Falling means the voltage fell below the trigger voltage.  The oscilloscope takes the entire plot and aligns that rise or fall event with the vertical trigger time.

    When binary on/off signals are plotted, they are described as having rising and falling edges.  The rising edges are the lines that connect 0 V to 2.65 V, and the falling edges are the ones that connect 2.65 V to 0 V.


    Your Turn: Set a Trigger

    • In the CYBERscope, set the Trigger dropdown to rise.
    • Wait for 5-10 seconds for the plot to align the signal’s rising edge with the vertical crosshair at 500 ms.

    • Try sliding the trigger time control (blue slider below the plot) right from 500 to 1250.
    • Wait another 5-10 seconds for the plot to snap to the new trigger time.
    • Try setting the Trigger dropdown to Fall.  Describe what happens.

     

    Review and Practice

    Self-Check

    • In this activity you:
      • Probed,  measured, and graphed voltage with an oscilloscope.
      • Examined the appearance of the duty cycle on the voltage vs time graph.
      • Used the Time/Div control to view the voltage signal in more detail.
    • Were you able to manipulate the duty cycle through the script?
    • Could you see the relationship between the LEDs supply voltage and time?

     

    Questions

    1. What are oscilloscopes used for?
    2. What does an oscilloscope do?
    3. What does it mean to have a falling trigger event?
    4. Describe a rising edge.
    5. Where on the graph will you find the high signal represented?
       

    Exercises

    1. How do you change the duty cycle from 50% to 75%?
    2. What is the purpose of sleep(1) in the oscilloscope script?
    3. In order to more closely inspect each on/off signal on the graph, you can make adjustments to which setting on the CYBERscope?
    4. What function sends data to the CYBERscope so that it can be displayed on the graph?
       

    Project

    Change the resistor in the green LED circuit to a 1 kΩ resistor (brown-black-red-gold). What changes do you observe in the graph? (Make sure to switch the resistor back.)

     

    Solutions

    Questions

    1. Answer: They are used to check voltage signals.
    2. Answer: An oscilloscope graphs voltage over time.
    3. Answer: It means that the voltage has dropped below the designated trigger voltage.
    4. Answer: The rising edge is the line connecting 0 V to the max volts for the binary on/off signal plot.
    5. Answer: The high signal can be seen at the highest point of the plotted line.

    Exercises

    1. Answer:  Change the first sleep(499) to sleep(749) and the second sleep(499) to sleep(249).
    2. Answer: It is necessary to allow enough time for the voltage to reach its highest level.
    3. Answer. Change the Time/Div value to a lower setting so only one rise and fall is shown.
    4. Answer. The plot function.
       

    Project

    Solution. Remember the Your Turn activity in Measure Blinking Light with a Voltmeter. Your measurements showed decreased voltage. The oscilloscope graph will show the same thing. More resistance resulted in less current. It turns out that the voltage will remain about the same.  The increase in resistance results in less current, which in turn results in less light.  The LED has (mostly) unchanging forward voltage, so the change in current is simply caused by more resistance.  The voltage drops remain about the same, but since there is more resistance, there is less current to get the same voltage across the resistor.

     

    DISCUSSION FORUMS | PARALLAX INC. STORE

    About | Terms of Use | Feedback: learn@parallax.com | Copyright©Parallax Inc. 2024


    Source URL:https://learn.parallax.com/courses/led-lights/
    Links