Alternative version of the zigzag example using motor control functions

This is an alternative version of the zigzag example program from the RoboSlam workshop. It encapsulates the code that sets the motor control pins in handy reusable functions:

  • forward()
  • reverse()
  • turnleft()
  • turnright()
  • stoprobot()
//
// RoboSlam example: Better Zigzag with functions
//

// the setup routine runs once when you press reset:
void setup()
{
  // Digital output for LED
  pinMode(2, OUTPUT);

  // Digital outputs for left motor
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);

  // Digital outputs for right motor
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop()
{
  forward();    // forward for 2000ms
  delay(2000);
  
  turnleft();   // turn left for 1000ms
  delay(1000);  
  
  forward();    // forward for 2000ms
  delay(2000);
  
  turnright();  // turn right for 1000ms
  delay(1000);  
}

void forward()
{
  digitalWrite(3, HIGH); // Left motor forward
  digitalWrite(4, LOW);
  digitalWrite(7, HIGH); // Right motor forward
  digitalWrite(8, LOW);
}

void reverse()
{
  digitalWrite(3, LOW);  // Left motor forward
  digitalWrite(4, HIGH);
  digitalWrite(7, LOW);  // Right motor forward
  digitalWrite(8, HIGH);
}

void turnleft()
{
  digitalWrite(3, LOW);  // Left motor reverse
  digitalWrite(4, HIGH);
  digitalWrite(7, HIGH); // Right motor forward
  digitalWrite(8, LOW);
}

void turnright()
{
  digitalWrite(3, HIGH); // Left motor forward
  digitalWrite(4, LOW);
  digitalWrite(7, LOW);  // Right motor reverse
  digitalWrite(8, HIGH);
}

void stoprobot()
{
  digitalWrite(3, LOW); // Left motor stop
  digitalWrite(4, LOW);
  digitalWrite(7, LOW); // Right motor stop
  digitalWrite(8, LOW);
}
Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s