How to Set Up Visual Studio Community 2019 for Windows 10

In this post, I’ll show you how to set up Visual Studio Community 2019 for Windows 10. This IDE will help us build C++ and Python programs. Our goal is to create a simple “Hello World” program in C++ and in Python.

Requirements

Here are the requirements:

  • Set up Visual Studio Community 2019 for Windows 10.
  • Create a simple “Hello World” program in C++ and in Python

Directions

Installation of Visual Studio Community 2019

Open a web browser.

Type “download visual studio community” into your favorite search engine.

visual-studio-community-setup-1

Click on the first result.

visual-studio-community-setup-2

Click to download Visual Studio Community.

Click the up arrow (^) and then click “Show in folder.”

visual-studio-community-setup-3

Right click on the file and click “Run as administrator.”

Click Yes.

Acknowledge the terms and conditions by clicking “Continue”.

visual-studio-community-setup-4

Wait for the Visual Studio Installer to do its thing.

visual-studio-community-setup-5

Select “Desktop Development with C++”. This is all you need to build C++ programs.

Select “Python development”. This is all you need to build Python programs.

visual-studio-community-setup-6

I also plan to develop for Raspberry Pi and do some data science, so I installed some extra workloads. This is optional if all you want to do is develop programs in C++ and Python:

  • Linux development with C++
  • Data science and analytical applications
visual-studio-community-setup-7

Choose the individual components that you want to install. It is OK to keep the default. Here is what else I selected:

  • Git for Windows
  • GitHub extension for Visual Studio
  • Class Designer (under Code Tools)
visual-studio-community-setup-8

You don’t need any of the .Net stuff.

Click “Install”. Go get a bite to eat or take a break. This will take a while.

visual-studio-community-setup-9

Once the install is complete, reboot your computer.

visual-studio-community-setup-10

Search for the program “Visual Studio 2019” on your computer, and then create a Desktop shortcut for it so that it is easier to find the next time around.

On the sign-in screen, sign in using your Microsoft account (or create one).

visual-studio-community-setup-11

Select “General”.

Creating the “Hello World!” Program in C++

Click “Create a new project”.

visual-studio-community-setup-12

Click “Empty Project” to start a new project.

visual-studio-community-setup-13

Configure your new project.

Right click on the project under the Solution Explorer. Go to Add -> New Item.

visual-studio-community-setup-14

Select C++ File (.cpp), and give the source code a name. Then click “Add”.

visual-studio-community-setup-15

Type in the code for your “Hello World!” program:

// This is a basic C++ program to display "Hello World!" 

// Header file for input output functions 
#include<iostream>  

using namespace std;

// main function: where the execution of program begins 
int main()
{
	// prints Hello World! to the console
	cout << "Hello World!";

	return 0;
}

Click the green button (Local Windows Debugger) to compile and run.

visual-studio-community-setup-16

You can also go to Build -> Build Solution. Then go to Debug -> Start Without Debugging.

That’s it! You should see the Hello World! message pop up.

visual-studio-community-setup-17

Running a Program in a Command Window

Solution Explorer (Right click the project name) -> Open Folder in File Explorer

Open the Debug folder.

visual-studio-community-setup-18

Select the hello_world.exe application.

visual-studio-community-setup-19

Hold down the Shift Key and right click to open a menu

Choose “Copy as path”.

Press Windows + R to open a command prompt window.

Type cmd.exe in the box.

visual-studio-community-setup-20

Click OK.

Right click to paste in the path.

visual-studio-community-setup-21

Press Enter to run.

visual-studio-community-setup-22

Creating the “Hello World!” Program in Python

Click “Create a new project”.

visual-studio-community-setup-23

Under “Language” select Python.

Select “Python Application”.

visual-studio-community-setup-24

Configure your new project. This time I checked “Place solution and project in the same directory”.

Click “Create”.

visual-studio-community-setup-25

Type in the code for your “Hello World!” program:

print("Hello World!")

Click the green button (“Attach”) to run.

That’s it! You should see the message pop up.

visual-studio-community-setup-26

To run via command line, go to the project folder and find the python file (hello_world.py in this case).

visual-studio-community-setup-27

Hold down the Shift Key and right click to open a menu.

Choose “Copy as path”.

Press Windows + R to open a command prompt window.

Right click to paste in the path.

visual-studio-community-setup-28

Press Enter to run. You might have to select the Python application you want to use to execute the file. You’ll only have to do this once.

The message should print to the terminal window. Congratulations! You are now ready to build C++ and Python programs!

visual-studio-community-setup-29

How to Read Input from a Push Button Switch on Raspberry Pi 3 Model B+

In this post, I’ll show you how to read input from a push button switch on Raspberry Pi 3 Model B+. This project shows you how to use the Raspberry Pi’s GPIO pins as an input (instead of an output) to receive information from the outside world.

Requirements

Here are the requirements:

  • Detect if a switch button is pressed.
  • When button is pressed, print “Button is pressed!”.
  • When button is not pressed, print “Button is not pressed!”.

You Will Need

push-button-2

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:

Wire the Push Button Switch to the Breadboard

push-button-3
push-button-4

Write the Program and Execute

Now we need to write a program in Python.

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 push_button.py. Here is the terminal command:

nano push_button.py

We type in this python code:

import gpiozero  # We are using GPIO pins

button = gpiozero.Button(17) # GPIO17 connects to button 

while True:
  if button.is_pressed:
    print("Button is pressed!")
  else:
    print("Button is not pressed!")

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 push_button.py

When you press the push button switch, you should see a message that says “Button is pressed!”. Otherwise, you will see a message that says “Button is not pressed!”.

push-button-5
push-button-1

To stop the program, you press CTRL-C.

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.

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-1
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.

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.

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.

How to Make an Autonomous Line-Following Robot | Arduino

In this post, I’ll show you how to make an autonomous line-following robot using Arduino and a reflectance sensor.

Requirements

Here are the requirements:

  • Make an autonomous line-following robot using Arduino and a reflectance sensor.

You Will Need

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

Directions

First grab the 0.25 inch thick foam board. Cut it into two 3/8 inch by 3/4 inch pieces.

line-following-robot-1
line-following-robot-2

Glue both pads so that one is on top of the other.

Glue the stack of two pads to the underside of the board so that the middle of the stack is exactly in the center of the lower board.

The stack should be right in between both snap action switches. The front of the stack should be slightly behind the front edge of the board.

line-following-robot-3
line-following-robot-4

Grab the header pins that came with the reflectance sensors. Cut the pin headers so that you have two sets of three pins. One set of three will be for one of the sensors and the other set of three will be for the other sensor.

line-following-robot-5

Insert the short end of the header pins into the reflectance sensors.

line-following-robot-6
line-following-robot-7

Solder the short end of the header pins so that the header pins remain in place. Be careful not to solder big blobs that connect one short pin to another. It is a difficult soldering job because the pins are so close together. Just take your time. No need to hurry.

line-following-robot-8
line-following-robot-9
line-following-robot-10
line-following-robot-11
line-following-robot-12

Now grab the following 6 male-to-female jumper wires and hook up the female part as follows:

  • Black, red, yellow (Right sensor)
  • Green, orange, white (Left sensor)
line-following-robot-13
line-following-robot-14

Get a piece of double-sided tape and attach the sensor to the underside of the board on top of small foam board stack.

The front of the sensor should be aligned with the front of the robot.

line-following-robot-15
line-following-robot-16
line-following-robot-17

Connect the 6 male-to-female jumper wires to the breadboard as follows:

  • White wire connects to c23
  • Orange wire connects to h12
  • Green wire connects to GND via h5.
  • Yellow wire connects to c25
  • Red wire connect to g12
  • Black wire connects to GND via h29
  • Connect a wire from a23 to analog pin 4 on the Arduino
  • Connect a wire from a25 to analog pin 5 on the Arduino
line-following-robot-18
line-following-robot-19

If you have issues with the servos not moving, try connecting the ground on the reflectance sensor (the green and black wires) to their own ground on the Arduino.

Upload the following code to the Arduino board to test the reflectance sensors.

/**
 * This is a test of the reflectance
 * sensor of the line following robot.
 * 
 * @author Addison Sears-Collins
 * @version 1.0 2019-05-15
 */

#define line_left A4 // The IO pins connected to sensor
#define line_right A5

int irleft_reflect = 0; // Readings stored here
int irright_reflect = 0;

/*   
 *  This setup code is run only once, when 
 *  Arudino is supplied with power.
 */
void setup() { 
   Serial.begin (9600); // Set the baud rate
} 


/*
 * This is the main code that runs again and again while
 * the Arduino is connected to power.
 */
void loop() { 

  // Read the reflectance sensors
  // Values range from 0 to 1023, representing
  // analog voltage from 0 to 5 volts
  // 0 = solid white; 1023 = solid black
  irleft_reflect = analogRead(line_left);
  irright_reflect = analogRead(line_right);

  Serial.print ("Left:");      
  Serial.print ("\t");        
  Serial.print (irleft_reflect);
  Serial.print ("\t");
  Serial.print ("Right:");
  Serial.println (irright_reflect);
  
  delay(100);
}

Open the Serial Monitor to verify that the values are changing when you wave an object in front of the sensors.

Feel free to close down the Serial Monitor at this stage. We will now make the line course that the robot will follow.

Grab the white poster (22 inches by 28 inches), and also get the 0.75 inch black electrical tape.

Create a course that looks something like the image below. Be sure to keep at least a three-inch margin between the side of the poster board and the line course. Make sure the turns and the course are smooth, otherwise you will have problems.

line-following-robot-20

The course is ready, so upload the following sketch to the Arduino.

#include <Servo.h> // We are using servos, so add library

/**
 * This robot follows a line made with black electric
 * tape on white poster board.
 * 
 * @author Addison Sears-Collins
 * @version 1.0 2019-05-15
 */

// Each servo is an object with its own data and behavior
Servo left_servo;
Servo right_servo;

// Sensors connected to analog pins 4 (left sensor) and 5 (right sensor)
const int left_line = A4;
const int right_line = A5;

// Store sensor readings here
int irleft_reflect = 0;
int irright_reflect = 0;

// Try values between 400 and 800. 
// Helps determine if robot is over the line
int threshold = 800;           

/*   
 *  This setup code is run only once, when 
 *  Arudino is supplied with power.
 */
void setup() { 
  // Assign each servo to its own digital pin on the Arduino
  right_servo.attach(9);  
  left_servo.attach(10); 
} 

void loop() { 

  // Read the reflectance sensors
  irleft_reflect = analogRead(left_line);  
  irright_reflect = analogRead(right_line);

  // robot is right over the line
  if (irleft_reflect >= threshold &amp;&amp; irright_reflect >= threshold) {
    line_forward();   
  }

  // robot is veering off to the right
  if (irleft_reflect >= threshold &amp;&amp; irright_reflect <= threshold) {
    line_left_slip();  
    delay(4);
  }

  // robot is veering off to the left
  if (irleft_reflect <= threshold &amp;&amp; irright_reflect >= threshold) {
    line_right_slip();  
    delay(4);
  }

  // If robot has lost the line, go find it
  if (irleft_reflect < threshold &amp;&amp; irright_reflect < threshold) {
    line_right_spin();
    delay(20);
  }
}

// On the continuous rotation servo, the write() 
// method sets the speed of the servo.
// 0 is full speed in one direction.
// 180 is full speed in the other direction.
// ~90 is no movement (You will have to tweak to
//   get no movement).
void line_forward() {
  right_servo.write(0);  
  left_servo.write(180);
}
void line_right_slip() {
  right_servo.write(90);  
  left_servo.write(180);
}
void line_left_slip() {
  right_servo.write(0);  
  left_servo.write(90);
}
void line_right_spin() {
right_servo.write(180);  
  left_servo.write(180);
}
void line_left_spin() {
  right_servo.write(0);  
  left_servo.write(0);
}

Disconnect the USB cable from the Arduino, and place the Arduino on the floor.

Turn on the servos:

  • a13 to e3 = left servo ON
  • e13 to e28 = right servo ON
line-following-robot-25

Plug in the Arduino’s power.

Press the Reset button on the Arduino as you position the robot over the black electrical tape on the course. The Reset button is like unplugging the Arduino and plugging it in again.

Watch the robot in action!

line-following-robot-21-1
line-following-robot-22-1
line-following-robot-24-1
line-following-robot-27

Video

How to Make a Remote Controlled Robot | Arduino

In this post, I’ll show you how to make a remote controlled robot using Arduino and a Sony Universal Remote Control.

Requirements

Here are the requirements:

  • Control a wheeled robot using a Sony Universal Remote Control.

You Will Need

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

Directions

First, get the infrared sensor. Bend the metal lead 0.25 inches below the base of the square sensor so that it makes a 90-degree angle.

remote-control-robot-1

Cut the lead 3/8 inches below the point of the bend. The dome of the sensor should face the opposite direction of the 90-degree bend.

remote-control-robot-2

Insert the infrared sensor into the Arduino board so that the pins are inside analog pins 0, 1, and 2. The dome of the infrared sensor should face upwards.

remote-control-robot-4
remote-control-robot-3

Insert batteries into the Sony Universal remote control.

Set up the remote control so that it can operate a Sony television. The instructions for how to setup the remote control should be included inside the package that it came with.

Add the IRremote library to the Arduino IDE. Go to Sketch -> Include Library -> Manage Libraries and look for “IRremote.” Add it, and then restart the IDE.

Upload the IRtest sketch to the Arduino (see code below). This sketch will be used to test the remote control, whose buttons do the following:

  • 1: Left Turn (Forward)
  • 2: Forward
  • 3: Right Turn (Forward)
  • 4: Spin Left
  • 5: Stop
  • 6: Spin Right
  • 7: Left Turn (Reverse)
  • 8: Backwards
  • 9: Right Turn (Reverse)

Open the Serial Monitor, and press any number from 1 to 9. You should see that number show up in the Serial Monitor.

#include <IRremote.h>      

/**
 * This code tests the Sony Universal Remote Control
 * 
 * Credit: Gordon McComb, How to Make a Robot.
 * Book available here: https://amzn.to/2Q303ed
 * 
 * Code was modified by Addison Sears-Collins
 */

#define  show_code  false   // Test mode
                            // false means match to # buttons
                            // true means display raw code

const int RECV_PIN = A0;     // Receiver input on Analog 0
IRrecv irrecv(RECV_PIN);     // Define IR recever object
decode_results results;

/*   
 *  This setup code is run only once, when 
 *  Arudino is supplied with power.
 */
void setup() {
  pinMode(A1, OUTPUT);       // IR power, ground pins
  pinMode(A2, OUTPUT);
  digitalWrite(A1, LOW);     // The ground for the IR
  digitalWrite(A2, HIGH);    // Power to the IR
  irrecv.enableIRIn();       // Initiate the receiver
  Serial.begin(9600);        // Set the baud rate
}

void loop() {

  if (irrecv.decode(&amp;results)) {  // If valid value was received
    if(show_code) {                // If show_code=true 
      Serial.print("0x");
      Serial.println(results.value, HEX);  // Display raw hex
    } else {                      // else show_code=false
      switch (results.value) {    // Match button to Sony codes
        case 0x10:
          Serial.println("1");
          break;
        case 0x810:
          Serial.println("2");
          break;
        case 0x410:
          Serial.println("3");
          break;
        case 0xC10:
          Serial.println("4");
          break;
        case 0x210:
          Serial.println("5");
          break;
        case 0xA10:
          Serial.println("6");
          break;
       case 0x610:
          Serial.println("7"); 
          break;
        case 0xE10:
          Serial.println("8");
          break;
        case 0x110:
          Serial.println("9");
          break;
      }        
    }
    irrecv.resume();    // Receive the next value
    delay(10);          // Pause for 10 milliseconds
  }

}

Now, upload the code below to the Arduino. Remove the USB cord. Place the robot on the floor. Turn on the servos. Insert the 9V battery jack into the Arduino, and drive the robot around the room!

#include <Servo.h> 

/**
 * This code runs the remote controlled robot
 * 
 * 
 * @author Addison Sears-Collins
 * @version 1.0 2019-05-14
 */
 
Servo left_servo;              // Define left servo
Servo right_servo;             // Define right servo

#include <IRremote.h>
int RECV_PIN = A0;
IRrecv irrecv(RECV_PIN);
decode_results results;
volatile int active_left = LOW;
volatile int active_right = LOW;
boolean started = false;

void setup() {
  // Set pin modes for switches
  pinMode(2, INPUT);
  pinMode(3, INPUT);
  pinMode(4, OUTPUT);
  digitalWrite(2, HIGH);
  digitalWrite(3, HIGH);
  digitalWrite(4, LOW);     // Serves as ground connection
  
  pinMode(A1, OUTPUT);       // IR power, ground pins
  pinMode(A2, OUTPUT);
  digitalWrite(A1, LOW);     // IR ground
  digitalWrite(A2, HIGH);    // IR power

  right_servo.attach(9);    // Set right servo to digital pin 9  
  left_servo.attach(10);    // Set left servo to digital pin 10
  irrecv.enableIRIn();     // Start the receiver
  
  Serial.begin(9600);
    
  // Set up interrupts
  attachInterrupt(0, bump_right, FALLING);
  attachInterrupt(1, bump_left, FALLING);
  
  started = true;
}

void loop() {
  
  if (active_left == HIGH) {           // If left bumper hit
    go_backwards();
    delay(500); 
    spin_right();
    delay(1000);
    go_forward();
    active_left = LOW;
    Serial.println("active_left");
  }
  
  if (active_right == HIGH) {          // If right bumper hit
    go_backwards();
    delay(500); 
    spin_left();
    delay(1000);
    go_forward();
    active_right = LOW;
    Serial.println("active_right");  
  }
  
  if (irrecv.decode(&amp;results)) {
    switch (results.value) {
      case 0x10:
        Serial.println("1");     // Turn left forward
        left_turn_fwd();
        break;
      case 0x810:
        Serial.println("2");     // Forward
        go_forward();
        break;
      case 0x410:
        Serial.println("3");     // Turn right forward
        right_turn_fwd();
        break;
      case 0xC10:
        Serial.println("4");    // Spin left
        spin_left();
        break;
      case 0x210:
        Serial.println("5");    // Stop
        stop_all();
        break;
      case 0xA10:
        Serial.println("6");    // Spin right
        spin_right();
        break;
     case 0x610:
        Serial.println("7");    // Turn left reverse
        left_turn_backwards();
        break;
      case 0xE10:
        Serial.println("8");    // Reverse
        go_backwards();
        break;
      case 0x110:
        Serial.println("9");    // Turn right reverse
        turn_right_backwards();
        break;
    }        
    irrecv.resume(); // Receive the next value
    delay(2);
  }
}

// Routines for forward, reverse, turns, and stop
void go_forward() {
  left_servo.write(180);
  right_servo.write(0);
}
void go_backwards() {
  left_servo.write(0);
  right_servo.write(180);
}
void spin_right() {
  left_servo.write(180);
  right_servo.write(180);
}
void spin_left() {
  left_servo.write(0);
  right_servo.write(0);
}
void right_turn_fwd() {
  left_servo.write(180);
  right_servo.write(90);
}
void left_turn_fwd() {
  left_servo.write(90);
  right_servo.write(0);
}
void left_turn_backwards() {
  left_servo.write(90);
  right_servo.write(180);
}
void turn_right_backwards() {
  left_servo.write(0);
  right_servo.write(90);
}
void stop_all() {
  left_servo.write(90);
  right_servo.write(90);
}

// Interrupt service routines
void bump_left() {
  if (started)
    active_left = HIGH;
}
void bump_right() {
  if (started) 
    active_right = HIGH;
}

Video

How to Make an Obstacle Avoiding Robot | Arduino

In this post, I’ll show you how to give your robot the ability to “see.” We’ll create an obstacle avoiding robot using Arduino and an ultrasonic sensor.

An ultrasonic sensor works by producing high frequency sound waves and then measuring the time it takes for the sound to reflect back to the sensor. Objects that are closer to the robot reflect sound back faster than objects that are farther away. This data is then used by the robot to avoid running into objects. Bats use ultrasound in order to locate food and avoid obstacles inside dark caves. Dolphins emit ultrasound as well in order to detect and recognize objects.

dolphin_ocean_waves_jump

Requirements

Here are the requirements:

  • Make a robot that avoids obstacles using an ultrasonic sensor.

You Will Need

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

Directions

First, get your ultrasonic distance sensor and place the far left pin (the one labeled VCC, the supply voltage) into the solderless breadboard in cell j12.

Now, wire the ultrasonic sensor to the Arduino as follows. Remember that each cell in a single row of 5 cells on a solderless breadboard is electrically connected (e.g. j12 is connected to f12, g12, h12, and i12 electrically):

  • VCC on the sensor connects to 5V on the Arduino
  • Echo on the sensor connects to Digital Pin 8 on the Arduino
  • Trig (stands for trigger) on the sensor connects to Digital Pin 7 on the Arduino
  • GND (stands for Ground) on the sensor connects to ground on the solderless breadboard
obstacle-avoiding-robot-1
obstacle-avoiding-robot-2

Now, upload the following sketch to the Arduino to test the ultrasonic sensor.

/**
 *  This program tests the ultrasonic
 *  distance sensor
 * 
 * @author Addison Sears-Collins
 * @version 1.0 2019-05-13
 */

/* Give a name to a constant value before
 * the program is compiled. The compiler will 
 * replace references to Trigger and Echo with 
 * 7 and 8, respectively, at compile time.
 * These defined constants don't take up 
 * memory space on the Arduino.
 */
#define Trigger 7
#define Echo 8

/*   
 *  This setup code is run only once, when 
 *  Arudino is supplied with power.
 */
void setup(){

  // Set the baud rate to 9600. 9600 means that 
  // the serial port is capable of transferring 
  // a maximum of 9600 bits per second.
  Serial.begin(9600);

  // Define each pin as an input or output.
  pinMode(Echo, INPUT);
  pinMode(Trigger, OUTPUT);
}

void loop(){

  // Make the Trigger LOW (0 volts) 
  // for 2 microseconds
  digitalWrite(Trigger, LOW);
  delayMicroseconds(2);

  // Emit high frequency 40kHz sound pulse
  // (i.e. pull the Trigger) 
  // by making Trigger HIGH (5 volts) 
  // for 10 microseconds
  digitalWrite(Trigger, HIGH);
  delayMicroseconds(10);
  digitalWrite(Trigger, LOW); 

  // Detect a pulse on the Echo pin 8. 
  // pulseIn() measures the time in 
  // microseconds until the sound pulse
  // returns back to the sensor.
  int distance = pulseIn(Echo, HIGH);

  // Speed of sound is:
  // 13511.811023622 inches per second
  // 13511.811023622/10^6 inches per microsecond
  // 0.013511811 inches per microsecond
  // Taking the reciprocal, we have:
  // 74.00932414 microseconds per inch 
  // Below, we convert microseconds to inches by 
  // dividing by 74 and then dividing by 2
  // to account for the roundtrip time.
  distance = distance / 74 / 2;

  // Print the distance in inches
  Serial.println(distance);

  // Pause for 100 milliseconds
  delay(100);
}

As soon as uploading is finished and with the USB cable still connected to the Arduino, click on the green magnifying glass in the upper right of the IDE to open the Serial Monitor.

Make sure you have the following settings:

  • Autoscroll: selected
  • Line ending: No Line ending
  • Baud: 9600 baud

Place any object in front of the sensor and move it back and forth. You should see the readings on the Serial Monitor change accordingly.

Now, close the Serial Monitor and upload the following sketch to the Arduino.

#include <Servo.h> 

/**
 * This robot avoids obstacles 
 * using an ultrasonic sensor.
 * 
 * @author Addison Sears-Collins
 * @version 1.0 2019-05-13
 */

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

/* Give a name to a constant value before
 * the program is compiled. The compiler will 
 * replace references to Trigger and Echo with 
 * 7 and 8, respectively, at compile time.
 * These defined constants don't take up 
 * memory space on the Arduino.
 */
#define Trigger 7
#define Echo 8

/*   
 *  This setup code is run only once, when 
 *  Arudino is supplied with power.
 */
void setup(){
  
  // Set the baud rate to 9600. 9600 means that 
  // the serial port is capable of transferring 
  // a maximum of 9600 bits per second.
  Serial.begin(9600);

  right_servo.attach(9);      // Right servo to pin 9
  left_servo.attach(10);      // Left servo to pin 10  

  // Define each pin as an input or output.
  pinMode(Echo, INPUT);
  pinMode(Trigger, OUTPUT);

  // Initializes the pseudo-random number generator
  // Needed for the robot to wander around the room
  randomSeed(analogRead(3));

  delay(200);     // Pause 200 milliseconds               
  go_forward();   // Go forward
}

/*
 * This is the main code that runs again and again while
 * the Arduino is connected to power.
 */
void loop(){
  int distance = doPing();

  // If obstacle <= 2 inches away
  if (distance >= 0 &amp;&amp; distance <= 2) {    
    Serial.println("Obstacle detected ahead");  
    go_backwards();   // Move in reverse for 0.5 seconds
    delay(500);

    /* Go left or right to avoid the obstacle*/
    if (random(2) == 0) {  // Generates 0 or 1, randomly        
      go_right();  // Turn right for one second
    }
    else {
      go_left();  // Turn left for one second
    }
    delay(1000);
    go_forward();  // Move forward
  }
  delay(50); // Wait 50 milliseconds before pinging again
}

/*
 * Returns the distance to the obstacle as an integer
 */
int doPing () {
  int distance = 0;
  int average = 0;

  // Grab four measurements of distance and calculate
  // the average.
  for (int i = 0; i < 4; i++) {

    // Make the Trigger LOW (0 volts) 
    // for 2 microseconds
    digitalWrite(Trigger, LOW);
    delayMicroseconds(2);

    
    // Emit high frequency 40kHz sound pulse
    // (i.e. pull the Trigger) 
    // by making Trigger HIGH (5 volts) 
    // for 10 microseconds
    digitalWrite(Trigger, HIGH);
    delayMicroseconds(10);
    digitalWrite(Trigger, LOW);
     
    // Detect a pulse on the Echo pin 8. 
    // pulseIn() measures the time in 
    // microseconds until the sound pulse
    // returns back to the sensor.    
    distance = pulseIn(Echo, HIGH);

    // Speed of sound is:
    // 13511.811023622 inches per second
    // 13511.811023622/10^6 inches per microsecond
    // 0.013511811 inches per microsecond
    // Taking the reciprocal, we have:
    // 74.00932414 microseconds per inch 
    // Below, we convert microseconds to inches by 
    // dividing by 74 and then dividing by 2
    // to account for the roundtrip time.
    distance = distance / 74 / 2;

    // Compute running sum
    average += distance;

    // Wait 10 milliseconds between pings
    delay(10);
  }

  // Return the average of the four distance 
  // measurements
  return (average / 4);
}

/*   
 *  Forwards, backwards, right, left, stop.
 */
void go_forward() {
  right_servo.write(0);
  left_servo.write(180);
}
void go_backwards() {
  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);
  left_servo.write(90);
}

Disconnect the USB cable from the Arduino, and place the Arduino on the floor.

Turn on the servos:

  • a13 to e3 = left servo ON
  • e13 to e28 = right servo ON

Then plug in the Arduino’s power.

Watch the Obstacle Avoiding Robot move!

obstacle-avoiding-robot-3

Video

How to Make an Object Detection Robot | Arduino

In this post, I’ll show you how to make an object detection robot using Arduino. This robot will move around a room and when it bumps into an object, it will turn around and go in another direction. Reminds me of the iRobot vacuum cleaner!

roomba_discovery

Requirements

Here are the requirements:

  • Make a robot that can turn around and go in a different direction after bumping into an object.

You Will Need

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

Directions

First, I position the snap action switches so that the corners are aligned with the side and front of the lower base of the robot. I will make a mark with a pencil to indicate where I should glue (we’ll glue them down later).

object_detection_robot-2
object_detection_robot-1

Grab three pieces of 6-inch male-to-female jumper wire.

object_detection_robot-3

Cut off the female end of the jumper wire.

object_detection_robot-4

Remove 0.25 inches of insulation from the end of the wire that you just cut.

Twist the loose ends of each wire.

object_detection_robot-5
object_detection_robot-6

Before you solder, it is helpful to first stick the wire strands through the pinhole of the terminal.

object_detection_robot-8
object_detection_robot-9

Solder one wire to the NO metal terminal of a switch (black wire).

Solder one wire to the NO metal terminal of the other switch (brown wire).

Solder one wire to the COM terminal of the switch that will go on the right side of the robot (white wire).

Get 3 inches of solder wire and connect the COM terminals of both switches (yellow wire).

object_detection_robot-7
object_detection_robot-11
object_detection_robot-12
object_detection_robot-10

If you don’t know how to solder, check out this video (skip to the soldering part):

Now we need to test the switches.

Plug the jumper connected to the Right switch COM into Digital Pin 4 on the Arduino.

Plug the jumper connected to the Right switch NO into Digital Pin 2 on the Arduino.

Plug the jumper connected to the Left switch NO into Digital Pin 3 on the Arduino.

object_detection_robot-13

Now, upload the following code to the Arduino. When you press down one of the switches, the built-in LED on the Arduino should light up.

/**
 * This program is to test the snap action switches
 * 
 * @author Addison Sears-Collins
 * @version 1.0 2019-05-12
 */

/*   
 *  This setup code is run only once, when Arudino is 
 *  supplied with power.
 */
void setup() {

  // Pin 13 is LED output
  pinMode(LED_BUILTIN, OUTPUT);
  
  pinMode(2, INPUT);  // Right Switch
  pinMode(3, INPUT);  // Left Switch
  pinMode(4, OUTPUT); // Ground for Switches
  
  digitalWrite(2, HIGH); // Enable pullup resistors
  digitalWrite(3, HIGH); // Enable pullup resistors
  digitalWrite(4, LOW);  // Set ground to 0 volts
}


/*   
 * Light LED pin13 if pin 2 or 3 goes LOW (i.e. pressed)
 */
void loop() {
  if ((digitalRead(2) == LOW) || (digitalRead(3) == LOW))
    digitalWrite(LED_BUILTIN, HIGH);
  else
    digitalWrite(LED_BUILTIN, LOW);
  delay (100); 
}

If everything is working OK, go ahead and glue the switches to the lower base of the board.

object_detection_robot-14
object_detection_robot-15

Now, upload the following sketch to the Arduino, and then place the Arduino on the floor.

#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.
 * 
 * @author Addison Sears-Collins
 * @version 1.0 2019-05-12
 */

// 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 1 sec
    delay(1000); 
    go_right();             // Turn to the right for 1 sec
    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;    // Set flag high to get serviced
}

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

/*   
 *  Forwards, backwards, right, left, stop.
 */
void go_forward() {
  right_servo.write(0);
  left_servo.write(180);
}
void go_backwards() {
  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
}
*/

Power it up by turning on the servos:

  • a13 to e3 = left servo ON
  • e13 to e28 = right servo ON

Then plug in the Arduino’s power.

In order to actually start the program, you need to depress one of the switches. Make sure the Arduino is on the floor before you start the program.

Watch the Object Detection Robot move!

Video

How to Make an Autonomous Wheeled Robot Move | Arduino

In this post, I’ll show you how to make a basic autonomous wheeled robot move forwards, backwards, to the right, and to the left using Arduino.

Requirements

Here are the requirements:

  • Make an autonomous wheeled robot move forwards, backwards, to the right, and to the left using Arduino.

You Will Need

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

Directions

First, we need to test the servos to see if they are working. Code up the sketch below into the Arduino Integrated Development Environment (IDE).

Give it a descriptive name like test_servos.ino.

1_code_the_sketchPNG
// Include library that enables us to work with servos
#include <Servo.h> 

/**
 * This program is a test of the servo motors 
 * 
 * @author Addison Sears-Collins
 * @version 1.0 2019-05-11
 */

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

/*   
 *  This setup code is run only once, when Arudino is 
 *  supplied with power.
 */
void setup() { 
  
  // Right servo is connected to digital pin 9
  right_servo.attach(9);   

  // Right servo is connected to digital pin 9
  left_servo.attach(10);
} 

/*   
 *  This code repeats as long as the Arduino has power.
 */
void loop() { 
  
  // On the continuous rotation servo, the write() 
  // method sets the speed of the servo.
  // 0 is full speed in one direction.
  // 180 is full speed in the other direction.
  // ~90 is no movement (You will have to tweak to
  //   get no movement).
  
  // Move forwards
  right_servo.write(0);  
  left_servo.write(180);

  // Wait 2 seconds
  delay(2000);

  // Move backwards (reverse)
  right_servo.write(180);  
  left_servo.write(0);

  // Wait 2 seconds
  delay(2000);
/*
  // Turn right
  right_servo.write(180); 
  left_servo.write(180);
  
  // Wait 2 seconds
  delay(2000);

  // Turn left
  right_servo.write(0);    
  left_servo.write(0);     
  
  // Wait 2 seconds
  delay(2000);
  */
}

Make sure the right and left servos are OFF:

  • a13 to j2 = left servo OFF
  • e13 to j28 = right servo OFF
2_servos_are_off

Compile the sketch in the IDE by clicking the checkmark in the upper left corner of the IDE.

3_compile_the_sketchPNG

Upload the sketch to the Arduino board by connecting the USB to your computer. Then click the right arrow (Upload) button on the IDE. The LED on your Arduino should be illuminated.

4_connect_usb
5_right_arrow_arduino_uploadPNG

Remove the USB cord from the Arduino.

Turn ON both servos:

  • a13 to e3 = left servo ON
  • e13 to e28 = right servo ON
6_servos_are_on

Hold the robot in your hand or place the robot on the floor.

Power up the Arduino by plugging in the 9V jack.

Observe the robot move.

7_moving_robot
8_moving_robot

When you are done watching it move, pull the 9V jack out of the Arduino and turn the servos OFF. Remember:

  • a13 to j2 = left servo OFF
  • e13 to j28 = right servo OFF

Here is another sketch (named basic_wheeled_bot.ino) that you can upload to the Arduino that adds some different movements to your robot and breaks up the movements we had in the test code into separate methods. Feel free to play around with this and create your own movement sequence:

// Include library that enables us to work with servos
#include <Servo.h> 

/**
 * This program makes a basic wheeled robot
 * do different movements.
 * 
 * @author Addison Sears-Collins
 * @version 1.0 2019-05-11
 */

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

/*   
 *  This setup code is run only once, when Arudino is 
 *  supplied with power.
 */
void setup() { 
  
  // Right servo is connected to digital pin 9
  right_servo.attach(9);   

  // Right servo is connected to digital pin 9
  left_servo.attach(10);
} 

/*   
 *  This code repeats as long as the Arduino has power.
 */
void loop() { 

  // On the continuous rotation servo, the write() 
  // method sets the speed of the servo.
  // 0 is full speed in one direction.
  // 180 is full speed in the other direction.
  // ~90 is no movement (You will have to tweak to
  //   get no movement).
  
  go_forward();

  // Pause 2 seconds
  delay(2000);

  go_backwards();

  // Pause 2 seconds
  delay(2000);
  
  go_right();

  // Pause 2 seconds
  delay(2000);
  
  go_left();

  // Pause 2 seconds
  delay(2000);
  
  stop_all();

  // Pause 2 seconds
  delay (2000);
}

/*   
 *  Forwards, backwards, right, left, stop.
 */
void go_forward() {
  right_servo.write(0);
  left_servo.write(180);
}
void go_backwards() {
  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
}

Video