This example uses three LEDs to make a model traffic light signal. You can use all red LEDs if you like, but its more realistic if you use red, yellow and green.
The LEDs cycle around in the sequence red, yellow, green, yellow and then back to red again.
To add the extra LEDs and resistors, wire them up as shown in the breadboard layout below.
Take care to ensure that the LEDs are the right way around, with the longer positive leads (anodes) to the left.
JavaScript Blocks Code
The JavaScript Blocks Code editor is embedded directly on this page below. From the editor, you can click on Download button (bottom right) and then copy the downloaded file onto your micro:bit. Alternatively, you can Click here to open the editor in a separate browser tab.
from microbit import * red_pin = pin0 # giving the LED pins names by using variables amber_pin = pin1 # makes it easier to see how the program works green_pin = pin2 while True: # red - turn amber LED off and red LED on amber_pin.write_digital(0) red_pin.write_digital(1) sleep(4000) # delay 4 seconds # amber - turn red LED off and amber LED on red_pin.write_digital(0) amber_pin.write_digital(1) sleep(1000) # green - turn amber LED off and green LED on amber_pin.write_digital(0) green_pin.write_digital(1) sleep(4000) # amber - turn green LED off and amber LED on green_pin.write_digital(0) amber_pin.write_digital(1) sleep(1000)
// define constants for each LED pin const int redPin = 0; const int amberPin = 1; const int greenPin = 2; void setup() { // set all three pins to act as digital outputs pinMode(redPin, OUTPUT); pinMode(amberPin, OUTPUT); pinMode(greenPin, OUTPUT); } void loop() { // red - turn amber LED off and red LED on digitalWrite(amberPin, LOW); digitalWrite(redPin, HIGH); delay(4000); // delay 4 seconds // amber - turn red LED off and amber LED on digitalWrite(redPin, LOW); digitalWrite(amberPin, HIGH); delay(1000); // green - turn amber LED off and green LED on digitalWrite(amberPin, LOW); digitalWrite(greenPin, HIGH); delay(4000); // amber - turn green LED off and amber LED on digitalWrite(greenPin, LOW); digitalWrite(amberPin, HIGH); delay(1000); }
Text editor powered by tinymce.