How to Blink an LED on Raspberry Pi 3 Model B+

In this post, I’ll show you how to blink an LED on Raspberry Pi 3 Model B+. This project shows you how to use the Raspberry Pi’s GPIO (General Purpose Input Output) pins as an output to manipulate an external device (in this case the LED).

Requirements

Here are the requirements:

  • Make an LED blink on Raspberry Pi 3 Model B+.

You Will Need

The following components are used in this project. You will need:

Directions

Set up the Raspberry Pi

Set up the Raspberry Pi as explained in this video:

Explore the Raspberry Pi (Optional)

From the Raspberry Pi desktop, click the Pi logo, and go to Preferences -> Raspberry Pi Configuration. Make sure your settings look like the image below and reboot (we’ll make use of these settings in future posts):

blink-led-11

Before we dive into the LED project, let’s have a look at the Raspberry Pi terminal.

The terminal is a way to communicate with your computer. Back in the 1980s and early 1990s when I first started using computers, the command-line interface of the terminal was the main way to send commands to your computer.

Back in those days computers did not have the processing power they have now. If you were born in the 1990s or later, you probably have only interacted with your computer via a graphical user interface. I like to use the command-line interface for robotics projects because it is more efficient, and you can tell the computer exactly what to do.

To open the terminal, click the Raspberry Pi logo in the upper left of the Raspberry Pi desktop and go to Accessories -> Terminal.

That black window you are looking at is the terminal. Typing ls will display all the files and folder in that directory. Blue items are directories. Green text shows our username (i.e “pi”).

blink-led-12

To change to a directory, you use the cd Directory Name command. For example cd Documents, gets you to the Documents directory.

Determine What Resistor to Use

Find out what the forward voltage is of your 5mm LED. Forward voltage is the minimum voltage required in order for the LED to light up. The forward voltage for my red LED is 1.8-2.2V.

Raspberry Pi is powered by 5V micro USB (2.5A). Each GPIO (General Purpose Input Output) pin supplies 3.3V (our source voltage) and can provide 16mA of current. Since 3.3V > 2.2V, we know that Raspberry Pi has enough voltage to power the LED.

Forward voltage is also the amount of voltage lost when a current runs through the LED. Consider it the “voltage drop” across the LED. To understand the basics of this concept, check out this 3D animation.

Find out what the maximum forward current of the 5mm LED is. Maximum forward current is the maximum current the LED can handle before it is at risk of getting damaged. The maximum forward current of my LED is 20mA (0.02A), which I obtained from the LED’s datasheet.

Now, we calculate the value of the resistor we need using Ohm’s Law (V = I * R):

  • Source voltage in volts = 3.3V
  • Forward voltage of LED = 1.8V
  • Maximum current of LED = 20mA = 0.02A
Resistor in ohms = ((Source voltage in volts) - (Forward voltage of LED in volts)) / (Maximum current in amps) = (Voltage leftover after the LED drops some of it) / (Maximum current)
Resistor in ohms = (3.3 - 1.8) / 0.02 = 75 ohms

So, we need at least a 75 ohm resistor. I’ll chose 330 ohms. The higher the resistor value you use, the dimmer the LED.

What is the current (represented as the capital letter ‘I’) in this case?

(3.3V - 1.8V) = I * 330
I = 4.5mA (which is well under the 20mA max current)

Now, we need to calculate how much power the resistor the LED can dissipate before it fails. We use this equation (P = VI):

Power in watts = Voltage in volts * Current in amps
Power in watts = (3.3 - 1.8) * 0.02A = 0.03 watts

Our resistor is rated at 0.25 watts, so we have more than enough cushion. We are good to go!

Wire the LED to the Breadboard

Here is the diagram to use to wire (using male to female jumper wire) the 330 ohm resistor and 5mm LED to the Raspberry Pi. That kink in one of the LEDs represents the long leg of the LED:

blink_led
blink-led-2

Blink the LED

Now we need to write a program in Python to blink the LED.

I have a folder in my Home Directory named robot. I get to this directory by opening up a terminal window in Raspberry Pi and typing:

cd robot

Now, we open up the Nano text editor to enable us to write the Python program. We name it led_blink.py. Here is the terminal command:

nano led_blink.py

We type in this python code:

import gpiozero  # The GPIO library for Raspberry Pi
import time  # Enables Python to manage timing

led = gpiozero.LED(17) # Reference GPIO17

while True:
  led.on() # Turn the LED on
  time.sleep(1)
  led.off() # Turn the LED off
  time.sleep(1)  # Pause for 1 second

We then press CTRL-X, then Y, then press Enter to save the program and return to the terminal.

To run the program, we type:

python3 led_blink.py

Your LED should be blinking. If it doesn’t blink, try connecting the red positive lead to another GPIO pin on the Raspberry Pi.

blink-led-3
blink-led-4

To stop the program, you press CTRL-C.

You can also try different color LEDs, as shown below.

blink-led-5
blink-led-6
blink-led-7
blink-led-8
blink-led-9
blink-led-10

How to Add Sound to a Wheeled Robot | Arduino

In this post, I’ll show you how to add sound to a wheeled robot.

Shout out to the late Gordon McComb for this project idea. He is the author of an excellent book that I recommend buying if you’re getting started with robotics: How to Make a Robot.

Requirements

Here are the requirements:

  • Build a wheeled robot that makes sound before it backs up.

You Will Need

The following components are used in this project. You will need:

Directions

Get the Piezo Transducer.

Stick the positive lead of the transducer into cell j26. Stick the other lead of the transducer into cell j29.

Connect digital pin 5 of the Arduino board to cell f26 of the breadboard.

Connect f29 to e29 with a male to male jumper wire, or just make sure that j29 is electrically connected to Ground.

sound-robot

Upload the following sketch to the Arduino breadboard to test the Piezo transducer.

#define SPKR 5

/**
 * Test the piezo transducer 
 * connected to pin 5
 * 
 * @author Addison Sears-Collins
 * @version 1.0 2019-05-15
 */
 
void setup() {
}

// Play sounds over and
// over again
void loop() {
   tone(SPKR, 247, 300); //247 Hz, 300ms
   delay(200);
   tone(SPKR, 131, 300);
   delay(200);
   tone(SPKR, 1175, 300);
   delay(200);
   tone(SPKR, 262, 300);
   delay(200);
   tone(SPKR, 1175, 300);
   delay(200);
   tone(SPKR, 131, 300);
   delay(200);
   tone(SPKR, 262, 300);
   delay(200);
   tone(SPKR, 1175, 300);
   delay(200);
   tone(SPKR, 247, 300); //247 Hz, 300ms
   delay(200);
}

Upload the following sketch to the Arduino breadboard in order to cause the robot to make sound just before it backs up.

#include <Servo.h> 

/**
 *  This robot will move around a room and when it 
 *  bumps into an object, it will turn around and 
 *  go in another direction. It will make a noise
 *  just before it backs up.
 * 
 * @author Addison Sears-Collins
 * @version 1.0 2019-05-12
 */

#define SPKR 5

// Create two servo objects, one for each wheel
Servo right_servo;
Servo left_servo;

// Volatile keyword is used because these variables
// can change at any time without any action having been
// taken by the compiled code. 

volatile int left_switch = LOW;   // Left switch flag
volatile int right_switch = LOW;  // Right switch flag
boolean already_started = false;  

/*   
 *  This setup code is run only once, when Arudino is 
 *  supplied with power.
 */
void setup() {
  // Set the pin modes for the switches
  pinMode(2, INPUT); // Right switch is input
  pinMode(3, INPUT); // Left switch is input
  pinMode(4, OUTPUT); // Pin 4 is ground
  
  // Turn on the internal pull up resistors for the switches
  // Keeps input from floating when the switches are not
  // pressed
  digitalWrite(2, HIGH);     // Right switch default to high
  digitalWrite(3, HIGH);     // Left switch default to high
  digitalWrite(4, LOW);      // Pin 4 default is ground

  right_servo.attach(9);      // Right servo is pin 9
  left_servo.attach(10);      // Left servo is pin 10
 
  // Declare the interrupts
  // attachInterrupt(digitalPinToInterrupt(pin), ISR, mode)
  // Interrupt when go from high to low
  attachInterrupt(digitalPinToInterrupt(2), hit_right, FALLING); 
  attachInterrupt(digitalPinToInterrupt(3), hit_left, FALLING);  
  
  already_started = true;  // Bot can now move
}

void loop() {
  if (left_switch == HIGH) {       // If the left switch is hit
    go_backwards();                // Go backwards for one second
    delay(1000); 
    go_right();                    // Turn to the right for one second
    delay(1000);
    go_forward();                  // Move forward
    left_switch = LOW;             // Reset the flag
  }
  
  if (right_switch == HIGH) {      // If the right switch is hit
    go_backwards();                // Go backwards for one second
    delay(1000); 
    go_left();                     // Turn left for one second
    delay(1000);
    go_forward();                  // Move forward
    right_switch = LOW;            // Reset the flag
  }
}
  
// Interrupt routine for left switch bumping into an object
void hit_left() {
  if (already_started)              // Valid if the program has begun
    left_switch = HIGH;             
}

// Interrupt routine for right switch bumping into an object
void hit_right() {
  if (already_started)              // Valid if the program has begun
    right_switch = HIGH;
}

/*   
 *  Forwards, backwards, right, left, stop.
 */
void go_forward() {
  right_servo.write(0);
  left_servo.write(180);
}
void go_backwards() {

  // Make a noise before you go backwards
  tone(SPKR, 247, 300); //247 Hz, 300ms
  delay(200);
  tone(SPKR, 131, 300);
  delay(200);
  tone(SPKR, 1175, 300);
  delay(200);
  right_servo.write(180);
  left_servo.write(0);
}
void go_right() {
  right_servo.write(180);
  left_servo.write(180);
}
void go_left() {
  right_servo.write(0);
  left_servo.write(0);
}
/*
void stop_all() {
  right_servo.write(90); // Tweak the 90
  left_servo.write(90);  // Tweak the 90
}
*/

How to Add Lights to a Wheeled Robot | Arduino

In this post, I’ll show you how to add lights to a wheeled robot so that the light is red when the robot is moving backwards and is green when the robot is moving forwards.

Shout out to the late Gordon McComb for this project idea. He is the author of an excellent book that I recommend buying if you’re getting started with robotics: How to Make a Robot.

Requirements

Here are the requirements:

  • Add lights to a wheeled robot so that the light is red when the robot is moving backwards and is green when the robot is moving forwards.

You Will Need

The following components are used in this project. You will need:

Directions

Get the bi-color LED.

Cut the shorter lead of the LED so that it is 1/4 inches in length.

Get the 300 Ohm resistor. Cut one of the ends so that it is 3/8 inches.

Solder the short lead of the LED to the short lead of the 300 Ohm resistor.

Cut the bottom of the resistor so that its lead is 3/8 inches in length.

Cut the lead of the LED that is not connected to the resistor so that it is the same length as the lead that has the resistor soldered to it.

Insert the LED into the Arduino board. The lead with the resistor goes into pin 11. The lead that does not have the resistor gets inserted into pin 12.

Upload the following code to the Arduino board. you should see the LED flashing red and green.

/**
 * Make a bi-color LED flash red and green.
 * 
 * @author Addison Sears-Collins
 * @version 1.0 2019-05-15
 */

#define LED_RED 11
#define LED_GREEN 12

/*   
 *  This setup code is run only once, when 
 *  Arudino is supplied with power.
 */
void setup() {
  
  // Define output pins
  pinMode(LED_RED, OUTPUT);  
  pinMode(LED_GREEN, OUTPUT);
 
  // Set output values
  digitalWrite(LED_RED, LOW); 
  digitalWrite(LED_GREEN, LOW);
}

/*   
 *  This code is run again and again to
 *  make the LED blink.
 */
void loop() {
  red_blink();
  green_blink();
}

// Method to blink the red LED
void red_blink() {
  digitalWrite(LED_RED, HIGH);
  delay(250);                          
  digitalWrite(LED_RED, LOW);     
  delay(250);                         
} 

// Method to blink the green LED
void green_blink() {
  digitalWrite(LED_GREEN, HIGH);
  delay(250);                         
  digitalWrite(LED_GREEN, LOW);     
  delay(250);                         
}

Now, upload the following code to the Arduino board. In this code, the LED will flash green when the robot is moving forward, and the LED will flash red when the robot is moving backwards.

#include <Servo.h> 

/**
 * Make a robot whose light is red when the robot 
 * is moving backwards and is green when the robot 
 * is moving forwards.
 * 
 * @author Addison Sears-Collins
 * @version 1.0 2019-05-15
 */


Servo right_servo;
Servo left_servo;

volatile int left_switch = LOW;   // Flag for left switch
volatile int right_switch = LOW;  // Flag for right switch
boolean started = false;     // True after first start

#define LED_RED 11
#define LED_GREEN 12

void setup() {
  // Set pin modes for switches
  pinMode(2, INPUT);
  pinMode(3, INPUT);
  pinMode(4, OUTPUT);
  
  // Set internal pull up resistors for switches
  // These go LOW when pressed as connection
  // is made with Ground.
  digitalWrite(2, HIGH);     // Right switch
  digitalWrite(3, HIGH);     // Left switch
  
  digitalWrite(4, LOW);      // Pin 4 is ground

  right_servo.attach(9);      // Right servo to pin 9
  left_servo.attach(10);      // Left servo to pin 10
 
  // Set up the interrupts
  attachInterrupt(0, bump_right, FALLING);
  attachInterrupt(1, bump_left, FALLING);
  
  started = true;            // OK to start moving
  
  pinMode(LED_GREEN, OUTPUT);
  pinMode(LED_RED, OUTPUT);
  digitalWrite(LED_GREEN, LOW);
  digitalWrite(LED_GREEN, LOW);
}

void loop() {
  if (left_switch == HIGH) {   // If the left switch hit
    go_backwards();            // Go backwards for 0.5 sec
    delay(500); 
    turn_right();              // Spin for 1 second
    delay(1000);
    go_forward();              // Go forward
    left_switch = LOW;         // Reset flag shows bumped
  }
  
  if (right_switch == HIGH) {  // If right switch hit
    go_backwards();
    delay(500); 
    turn_left();
    delay(1000);
    go_forward();
    right_switch = LOW;
  }
}
  
// Interrupt handlers
void bump_left() {
  if (started)              // If robot has begun
    left_switch = HIGH;
}
void bump_right() {
  if (started)             
    right_switch = HIGH;
}

// Motion Routines: forward, backwards, turn, stop
// Continuous servo motor
void go_forward() {
  right_servo.write(0);
  left_servo.write(180);
  led_green();
}
void go_backwards() {
  right_servo.write(180);
  left_servo.write(0);
  led_red();
}
void turn_right() {
  right_servo.write(180);
  left_servo.write(180);
  led_off();
}
void turn_left() {
  right_servo.write(0);
  left_servo.write(0);
  led_off();
}
void stop_all() {
  right_servo.write(90);
  left_servo.write(90);
}

void led_green() {
  digitalWrite(LED_GREEN, HIGH);
  digitalWrite(LED_RED, LOW);      
} 
void led_red() {
  digitalWrite(LED_GREEN, LOW);
  digitalWrite(LED_RED, HIGH);
}
void led_off() {
  digitalWrite(LED_GREEN, LOW);
  digitalWrite(LED_RED, LOW);
}

If for some reason you get a situation where you get the opposite result of what should occur (flashes red when moving forward and green when in reverse), the LED is reversed. Turn it around.

lighted-robot-1
lighted-robot-2

Also, if you are getting a situation where your servos are not moving, it likely means that voltage is insufficient. Changing the location of the servo power wire, the wire that connects the red servo line to the red line of the 4xAA battery pack usually does the trick. If not, get new batteries for the servo.