Posts | Comments

Planet Arduino

Archive for the ‘Parallax Ping Sonar’ Category

Lil Herbert - Beginner Robot

Lil Herbert - Beginner Robot

Contest entry by Annie (note: was submitted within the deadline, I wasn’t able to add to the blog until today)

In September of 2009 I found myself in a learning mood.  Throughout my life I have been fascinated by everything: science, math, history…you name it, I love to know about it.  In September I decided I was going to brush up on my electronics knowledge and see where it would take me.  I had studied electronics at a tech school during the 90s and I’d grown up in Silicon Valley so I wasn’t completely new to the endeavor.  But upon graduation from the tech program I immediately began working on computer network support and Key System/PBX telephone system programming rather than the nitty gritty world of capacitors, resistors and ICs and found my understanding of it all both fading and lacking.

As I practiced building little 555 timer and 386 audio amplifier circuits, I soaked in as much information as I could from forums and online electronics articles.  It was then that I began hearing   about something called Arduino.  Arduino?  What, pray tell, is an Arduino?

A pizza, perhaps?  As in “I’ll have a large pepperoni and Arduino with extra cheese!”  No, that wasn’t it.  Arduino…hmmmm.

A new Italian sports car?  “The new 2010 Arduino Coupe, 0 to 60 in 200 microseconds” (Of course with a little disclaimer at the bottom explaining that the Arduino driver is a pro, so kiddies, don’t try this at home!).  Well, that wasn’t it either.

A quick search of Wikipedia and then Amazon was my road to Damascus. I had found a microcontroller that was cheap, extremely easy to learn, a massive open-source community to hold my hand as I dipped my pinky toe into the microcontroller waters, and a seemingly unending variety of applications and add-ons.  By October 9th I had my first Arduino.  A Duemilanove.  It was (and still is) a thing of beauty in my eyes.

After a week of the usual “Hello World” blinking LED type projects, I decided I needed a long term project to build upon and to hone my skills.  Thus, Herbert was born.

Herbert started out with a discussion I had with my mom.  I was thinking of  some goals to set to help me learn all of the different aspects of micro-controller use.  I wanted to learn to write code.  I wanted to continue my work designing and building circuits.  I wanted to practice my soldering skills.  A robot project was the answer!

The goals for Herbert were these:

  • Start from scratch.  To really understand the workings of Herbert I needed to build him from the ground up, no ready-made kits.
  • Have the Arduino control his movement; he must start out with simple forward, backward and turning motions autonomously.
  • Add sensors to let Herbert see the world.  His first sensor is a Parallax Ping ultrasonic sensor, but eventually he will have many different types.
  • Through code of my own creation, have Herbert avoid collisions by turning, stopping or reversing.  I felt it was important for my educational development to create my own code rather than borrow someone else’s.  I have seen some fancy avoidance programming out there that I admire greatly.  But I knew if I didn’t start from scratch I would miss out on the joys of failure.

Have Herbert be a long range project.  I decided that he could be open ended.  As I solve one set of obstacles, I can move on and add new features.  Someday Herbert will talk, tell me the weather, read me my email and play songs off my computer for me.  It’s all just one step at a time.

The Basics

Robot Chassis

Robot Chassis

I started building in late October.  I received an early Christmas present in the form of 4 motors, 4 wheels and a chassis.  I decided to focus on a pulse width modulation circuit design to control the  independent speed of each motor.  After much studying on the web,   I built a circuit with 4 Darlington transistors to control the current   through the motors with the Arduino pins controlling the current  through each motor.  In addition, I added 4 reversed biased diodes to      protect the Arduino pins from kick-back voltage.

Schematic

Schematic

This circuit worked great for my first foray across the living room floor.  I could change the motor speed by changing the PWM in the Arduino sketch and soon I had Herbert zipping around scaring the dogs.  I decided it was time to give him some ‘eyes’.  While shopping for parts at Radio Shack one day I stumbled upon the Parallax Ping))) Sensor.  It is an ultrasonic sensor that was perfect for what I was doing.  With only a 5v, Gnd and Signal pin, I knew I could get it up and running with the Arduino!

I modified my code and put the signal for the Ping sensor on pin 9 of the Arduino.  I attached the 5v and Gnd of the sensor to the respective spots on the Duemilanove.  At this point I broke from my stated goal of always writing my own code.  The truth is, I had not the slightest idea how to write my own functions at this point, let alone libraries.  Luckily, the Arduino IDE saved the day!  In Files-Examples-Sensors there is a sketch for the Parallax Ping))) sensor.

After testing the sensor on a breadboard, I wired it up on Herbert.  I then took the important parts of the Ping))) sketch and added them to my current working sketch.  Herbert saw the light and was on the move!  I had him driving forward, detecting objects in front of him and turning to avoid them.  Granted, my code needed polishing but it was a start!

At this point my goal was to have Herbert move forward.  If he detected an obstacle he would stop and sweep his ping sensor to the left and take a measurement.  Then he would swing the sensor to the right and take another measurement.  He would then compare the two to decide which was a clearer path.  I wrote the sketch and it worked….once.  Somehow I had run into my first major bug and I was at a loss to figure it out.  Herbert was acting strange, not responding correctly and dancing around like a madman.

With little time before the contest deadline and wanting Herbert to make an appearance, I decided the strange problem must’ve been something to do with the cheap wheel motors I had (they had been giving me problems now and again already) and so I quickly ordered  4 Solarbotics GM13a 150:1 mini metal gear motors and tires to match.  They are much smaller than the no-name motors I had been using, but they are quiet and nice!  Herbert became Lil’ Herbert.

I rebuilt Herbert with the new motors and wheels and ran into the same strange behavior.  Obviously the motors weren’t the problem.  I’m sure I now know what it is, and I will experiment after the contest deadline to see if I am right.  I’ve been using an Adafruit Minty Boost to power the Arduino.  It’s a little circuit that converts the 3 volts from 2 AA batteries to 5 volts and sits in an Altoids tin on Herbert’s chassis.  I now believe that having the Arduino power the ping sensor, a sweeping servo and itself is just too much for the Minty Boost, causing strange things to happen.  But, as I was running out of time, I chose to forego the sweeping of the servo until after the deadline.

So, this is where we stand.  Or where Herbert rolls as it were.  I was still using my transistor circuit to power the motors and pinging to avoid collisions.  The main problem with this setup is that the motors’ current could only go one way.  I was able to drive Herbert forward and turn him, but he couldn’t reverse or turn on a dime.  At this time I decided that I knew enough about my transistor circuit/motor setup that I could investigate motor controller boards.  I knew I could build H-Bridge circuits to allow the motors to drive either direction, but I felt the compact nature of some of the control boards I had been looking at would help me keep Herbert compact.

So into the picture came 2 Pololu Qik 2s9v1 Dual Serial Motor Controllers.  They are little, efficient and allowed me to have Herbert go forward or backwards.  I once again sacrificed my vow to write my own code and used a library specifically for these boards.  My only trouble was the code was written for one board only, and I had two.  I fumbled my way through making 2 instances of the library and all was well.

As I write this it is 3:30 PM on December 31, 2009.  I have reached the contest deadline and can do no more.  Herbert can currently sense obstacles in front of him and turn to avoid them.  He can move forward and backward.  Sadly, there was no time to resolve his neck sweep issues in time.  But as Herbert travels around the house in the coming months he will be doing more and doing it more efficiently.  I will keep adding new videos to my You Tube page and Herbert will continue to annoy my dogs.

I have included two versions of Herbert’s sketches in the zipped folder.  One is from the early days of the transistor circuit, and the other is from this very day with the motor controllers.

Herbert’s videos can be seen on my You Tube channel.  The first one, Herbert is Born, was from November.  The most recent is Lil Herbert.

Videos: http://www.youtube.com/profile?user=AnnieNakki#g/u

Share/Bookmark

This is a repost of a previous project. I am still working to get the older post back online from when we upgraded Wordpress.

The robot was basically built using a Parallax Boe Bot chassis. Rather than using the Basic Stamp we added an Arduino with a proto shield to control the robot functions.

You can use any type of chassis for this project. The robot moves about using a ping sonar and IR sensors to avoid running into any objects. As you can see in the video, it was a bit thrown off by our kitten. We added additional items such as a wireless camera that sends audio/video back to our TV.The original design for this was created by an Instructable’s member and can be found here.

Items you will need for this project:

Arduino Autonomous Robot

Arduino Autonomous Robot

The standard servo will be used to mount the Ping Rangefinder. This will give you a back and forth sweep motion as the robot travels around. The two continuous rotation servos are used for the wheels. You do not need to use the Parallax brand of servos, other brands will work. You may have to adjust the PWM values in the source code to go with the servos you are using.

It is also possible to use DC motors and edit the code, which would be considerably cheaper. You could use a SN754410 Quad Half H-Bridge to drive two DC motors. Tutorial for how to do this is available here.

The Arduino hook up is pretty simple. You will have the following:

  • Pin (Analog) 0: Left Sensor
  • Pin (Analog) 1: Center Sensor
  • Pin (Analog) 2: Right Sensor
  • Pin 5: Pan Servo
  • Pin 6: Left Drive Servo
  • Pin 7: Ultrasonic Rangefinder ( ‘Ping)))’ )
  • Pin 9: Right Drive Servo
  • Pin 11: Piezo Speaker
Shield Close-up

Shield Close-up

Radioshack sells an RC car battery as well as connector repair kit. You can solder the repair kit connector onto the shield, and then be able to hook up your battery to power the servos with. You can use a separate battery holder to power the Arduino.

Make all your connections onto the shield. This way everything can remain in place if you need to use your Arduino for something else and save you from needing to tear apart everything.

for power to the shield, you won’t need any extra filter capacitors since the 5V switching  regulator has them built in. We used a small project box to hold the battery in place, and was able to attach the wireless camera on top of it.

The Arduino and camera are power source 1, while the servos and sensors are power source 2 (the RC battery). A small piece of PVC pipe mounted onto a cable clip will help you to keep your wires all organized to a central point and be less likely to get caught or tangled up into something as the robot is moving around.

Arduino Sketch

// Begin Robot Code
int micVal;
int cdsVal;
int irLval;  // Left IR
int irCval;  // Center IR
int irRval;  // Right IR

int i;   // Generic Counter
int x;  // Generic Counter
int PLval;  // Pulse Width for Left Servo
int PRval;  // Pulse Width for Right Servo
int cntr;  // Generic Counter Used for Determining amt. of Object Detections
int counter; // Generic Counter
int clrpth;  // amt. of Milliseconds Of Unobstructed Path
int objdet;  // Time an Object was Detected
int task;  // Routine to Follow for Clearest Path
int pwm;  // Pulse Width for Pan Servo
boolean add;  // Whether to Increment or Decrement PW Value for Pan Servo
int distance;  // Distance to Object Detected via Ultrasonic Ranger
int oldDistance;  // Previous Distance Value Read from Ultrasonic Ranger

float scale = 1.9866666666666666666666666666667;  // *Not Currently Used*

int LeftPin = 6;  // Left Servo
int RightPin = 9;  // Right Servo
int PiezoPin = 11;  // Piezo
int PingServoPin = 5;  // Pan Servo
int irLPin = 0;            // Analog 0; Left IR
int irCPin = 1;            // Analog 1; Center IR
int irRPin = 2;            // Analog 2; Right IR

int ultraSoundSignal = 7; // Ultrasound signal pin
int val = 0;              // Used for Ultrasonic Ranger
int ultrasoundValue = 0;  // Raw Distance Val
int oldUltrasoundValue;  // *Not used*
int pulseCount;        // Generic Counter
int timecount = 0; // Echo counter
int ledPin = 13; // LED connected to digital pin 13

#define BAUD 9600
#define CmConstant 1/29.034

void setup() {
  Serial.begin(9600);
  pinMode(PiezoPin, OUTPUT);
  pinMode(ledPin, OUTPUT);
  pinMode(LeftPin, OUTPUT);
  pinMode(RightPin, OUTPUT);
  pinMode(PingServoPin, OUTPUT);
  pinMode(irLPin, INPUT);
  pinMode(irCPin, INPUT);
  pinMode(irRPin, INPUT);
  for(i = 0; i < 500; i++) {
    digitalWrite(PiezoPin, HIGH);
    delayMicroseconds(1000);
    digitalWrite(PiezoPin, LOW);
    delayMicroseconds(1000);
  }
  for(i = 0; i < 20; i++) {
  digitalWrite(PingServoPin, HIGH);
  delayMicroseconds(655 * 2);
  digitalWrite(PingServoPin, LOW);
  delay(20);
  }
  ultrasoundValue = 600;
  i = 0;
}

void loop()
{
  //Scan();
  Look();
  Go();
}
void Look() {
  irLval = analogRead(irLPin);
  irCval = analogRead(irCPin);
  irRval = analogRead(irRPin);
  //if(counter > 10) {
    //counter = 0;
    //readPing();
  //}
  if(irLval > 200) {
    PLval = 850;
    PRval = 820;
    x = 5;
    cntr = cntr + 1;
    clrpth = 0;
    objdet = millis();
  }
  else if(irCval > 200) {
    PLval = 850;
    PRval = 820;
    x = 10;
    cntr = cntr + 1;
    clrpth = 0;
    objdet = millis();
  }
  else if(irRval > 200) {
    PLval = 650;
    PRval = 620;
    x = 5;
    cntr = cntr + 1;
    clrpth = 0;
    objdet = millis();
  }
  else {
    x = 1;
    PLval = 850;
    PRval = 620;
    counter = counter + 1;
    clrpth = (millis() - objdet);
    if(add == true) {
      pwm = pwm + 50;
    }
    else if(add == false) {
      pwm = pwm - 50;
    }
    if(pwm < 400) {
      pwm = 400;
      add = true;
    }
    if(pwm > 950) {
      pwm = 950;
      add = false;
    }
    digitalWrite(PingServoPin, HIGH);
    delayMicroseconds(pwm * 2);
    digitalWrite(PingServoPin, LOW);
    delay(20);
    readPing();
    if(ultrasoundValue < 500) {
      cntr = cntr + 1;
      switch(pwm) {
        case 400:
          x = 7;
          PLval = 650;
          PRval = 650;
          Go();
          break;
        case 500:
          x = 10;
          PLval = 650;
          PRval = 650;
          Go();
          break;
        case 600:
          x = 14;
          PLval = 850;
          PRval = 850;
          Go();
          break;
        case 700:
          x = 10;
          PLval = 850;
          PRval = 850;
          Go();
          break;
        case 950:
          x = 7;
          PLval = 850;
          PRval = 850;
          Go();
          break;
      }
    }
  }
  //Serial.print("clrpth: ");
  //Serial.println(clrpth);
  //Serial.print("objdet: ");
  //Serial.println(objdet);
  //Serial.print("cntr: ");
  //Serial.println(cntr);
  if(cntr > 25 && clrpth < 2000) {
    clrpth = 0;
    cntr = 0;
    Scan();
  }
}
void Go() {
  for(i = 0; i < x; i++) {
    digitalWrite(LeftPin, HIGH);
    delayMicroseconds(PLval * 2);
    digitalWrite(LeftPin, LOW);
    digitalWrite(RightPin, HIGH);
    delayMicroseconds(PRval * 2);
    digitalWrite(RightPin, LOW);
    delay(20);
  }
}
void readPing() {  // Get Distance from Ultrasonic Ranger
 timecount = 0;
 val = 0;
 pinMode(ultraSoundSignal, OUTPUT); // Switch signalpin to output

/* Send low-high-low pulse to activate the trigger pulse of the sensor
 * -------------------------------------------------------------------
 */

digitalWrite(ultraSoundSignal, LOW); // Send low pulse
delayMicroseconds(2); // Wait for 2 microseconds
digitalWrite(ultraSoundSignal, HIGH); // Send high pulse
delayMicroseconds(5); // Wait for 5 microseconds
digitalWrite(ultraSoundSignal, LOW); // Holdoff

/* Listening for echo pulse
 * -------------------------------------------------------------------
 */

pinMode(ultraSoundSignal, INPUT); // Switch signalpin to input
val = digitalRead(ultraSoundSignal); // Append signal value to val
while(val == LOW) { // Loop until pin reads a high value
  val = digitalRead(ultraSoundSignal);
}

while(val == HIGH) { // Loop until pin reads a high value
  val = digitalRead(ultraSoundSignal);
  timecount = timecount +1;            // Count echo pulse time
}

/* Writing out values to the serial port
 * -------------------------------------------------------------------
 */

ultrasoundValue = timecount; // Append echo pulse time to ultrasoundValue

//serialWrite('A'); // Example identifier for the sensor
//printInteger(ultrasoundValue);
//serialWrite(10);
//serialWrite(13);

/* Lite up LED if any value is passed by the echo pulse
 * -------------------------------------------------------------------
 */

if(timecount > 0){
  digitalWrite(ledPin, HIGH);
}
} 
void Scan() {   // Scan for the Clearest Path
  oldDistance = 30;
  task = 0;
  for(i = 1; i < 5; i++) {
    switch(i) {
      case 1:
        //Serial.println("Pos. 1");
        pwm = 1125;    ///  incr. by 100 from 1085
        break;
      case 2:
        //Serial.println("Pos. 2");
        pwm = 850; //// increased by 100 from 850
        break;
      case 3:
        //Serial.println("Pos. 3");
        pwm = 400;
        break;
      case 4:
        //Serial.println("Pos. 4");
        pwm = 235;
        break;
    }
    for(pulseCount = 0; pulseCount < 20; pulseCount++) {  // Adjust Pan Servo and Read USR
      digitalWrite(PingServoPin, HIGH);
      delayMicroseconds(pwm * 2);
      digitalWrite(PingServoPin, LOW);
      readPing();
      delay(20);
    }
    distance = ((float)ultrasoundValue * CmConstant);   // Calculate Distance in Cm
    if(distance > oldDistance) {  // If the Newest distance is longer, replace previous reading with it
      oldDistance = distance;
      task = i;   // Set task equal to Pan Servo Position
    }
  }
  //Serial.print("Task: ");
  //Serial.println(task);
  //Serial.print("distance: ");
  //Serial.println(distance);
  //Serial.print("oldDistance: ");
  //Serial.println(oldDistance);
  distance = 50;  // Prevents Scan from Looping
  switch(task) {   // Determine which task should be carried out
    case 0:  // Center was clearest
      x = 28;
      PLval = (850);
      PRval = (850);
      Go();
      break;
    case 1:  // 90 degrees Left was Clearest
      x = 14;
      PLval = (650);
      PRval = (650);
      Go();
      break;
    case 2:  // 45 degrees left
      x = 7;
      PLval = (650);
      PRval = (650);
      Go();
      break;
    case 3:  // 45 degrees right
      x = 7;
      PLval = (850);
      PRval = (850);
      Go();
      break;
    case 4:  // 90 degrees right
      x = 14;
      PLval = (850);
      PRval = (850);
      Go();
      break;
  }
}

// End Robot Code
Share/Bookmark
Silly String Spider

Silly String Spider

Contest Entry by Todd Harrison

I had great fun this Halloween with a silly string shooting spider!  My plan was to use an Arduino micro-controller developer board to control my son’s “Teenage Mutant Ninja Turtle” RC car that already shoots silly string.  I didn’t get the spider to actually squirt the silly string but when you’re looking at a big black spider and something shoots silly string at you from the same direction it scares you just the same.

I was inspired to do this 4 hour marathon build by a blog posting by Eric on www.Instructables.com. Eric created a silly string shooting pumpkin which was so incredible I just had to build a spider for Halloween that did the same.

My major problem was that once I heard about Eric’s pumpkin I only had a day to get the supplies and about 4 hours of free time to wire-up something, code it and get it out in the front yard before the kids started coming for tricks or treats.

Here is a component breakdown of the final prop.

  • The red dot and arrow point to the RC car hiding under a bush.
  • 2) RC car remote control.
  • 3) Relay used by pin 2 on the Arduino to fire the remote control’s silly string button.
  • 4) Arduino board: Duemilanove with ATmega328 Purchased from adafruit.com
  • 5) Small blue servo to yank on the spiders leg: TowerPro SG-50.
  • 6) Two red LEDs for spider eyes. Not on the spider I know, I ran out of dev time
  • 7) Parallax Ping))) sonar sensor, held up with helping hands.
  • 8 ) Big black spider
Silly String Spider Parts

Silly String Spider Parts

I originally wanted the string to shoot from the spider’s behind but I really didn’t have time for that so I hid the RC car in the bushes behind the spider and loaded it with a fresh can of silly string.  All I really had to do was get the Arduino to sense somebody getting to close to the spider’s face and then “POW!” fire the silly string using the car’s remote control.

Just for extra effect I wanted the spider to move using a servo and have red LED eyes that blinked.  I also wanted the blinking and servo movement to ramp up faster and faster as a person got closer. To get this effect I used a Parallax Ping))) sonar sensor to track the approaching prey as well as to calculate an agitation delay.  The agitation delay was used to make the spider look more and more upset as the person got closer. If somebody was at a great distance the LED eyes flashed slow and the spider made slow jerking motions, but as the distance delay multiplier shortened the eyes flash furiously fast and the spider would jerk like mad!  If the trick-or-treater dared get closer the Arduino would fire a relay connected to the remote control and they would get a face full of silly string.

Silly String Spider Board Control

Silly String Spider Board Control

A lot of people did have the nerve to walk up on the spider but in the dark it took them a second to even realize they had just been doused in the face with silly string, but then they would laugh and do it again just for fun.  It only really scared a few that didn’t expect anything or were just standing behind the intended victim who was fortunately to short to get hit.

I didn’t get time to mount the eyes in the spider’s head but the red flashing LEDs on the control board seemed to have the same effect as they would have had if they were on the spider.  They were only needed to get the kids attention in the dark.

Arduino Sketch:

  1. #include
  2. Servo myservo;  // create servo object to control a servo
  3.  
  4. int pingPin = 7; // pin for ping sensor
  5. int stringPin = 2; // pin that will fire the silly string remote
  6. int LED_Eyes_Pin = 11; // pin for the two eyes
  7. int multiplier; // multiplier for delay
  8. int delay_time; // time to delay before next step
  9.  
  10. void setup() {
  11.   pinMode(LED_Eyes_Pin, OUTPUT);
  12.   pinMode(stringPin, OUTPUT);
  13.   myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  14.   Serial.begin(9600);
  15.   digitalWrite(stringPin, LOW);    //make sure this is off so we don’t shoot string
  16. }
  17.  
  18. void loop() {
  19.   ping();
  20.   eyes_and_servo(0,0);
  21.   delay(delay_time);
  22.  
  23.   ping();
  24.   eyes_and_servo(100,255);
  25.   delay(delay_time);
  26. }
  27.  
  28. void eyes_and_servo(int servo_pos, int eye_pulse)
  29. {
  30.   analogWrite(LED_Eyes_Pin, eye_pulse);
  31.   myservo.write(servo_pos);
  32. }
  33.  
  34. void ping()
  35. {  long duration, inches;
  36.  
  37.   // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  38.   // We give a short LOW pulse beforehand to ensure a clean HIGH pulse.
  39.   pinMode(pingPin, OUTPUT);
  40.   digitalWrite(pingPin, LOW);
  41.   delayMicroseconds(2);
  42.   digitalWrite(pingPin, HIGH);
  43.   delayMicroseconds(5);
  44.   digitalWrite(pingPin, LOW);
  45.  
  46.   // The same pin is used to read the signal from the PING))): a HIGH
  47.   // pulse whose duration is the time (in microseconds) from the sending
  48.   // of the ping to the reception of its echo off of an object.
  49.   pinMode(pingPin, INPUT);
  50.   duration = pulseIn(pingPin, HIGH);
  51.   // convert the time into a distance
  52.   inches = microsecondsToInches(duration);
  53.   multiplier = inches/10;
  54.  
  55.   delay_time = inches * multiplier;
  56.  
  57.   if (delay_time > 1000) {delay_time = 500;};
  58.  
  59.   if (delay_time < 300) {
  60.      digitalWrite(stringPin, HIGH);
  61.      delay(500);
  62.      digitalWrite(stringPin, LOW);
  63.      delay(2000);
  64.    };
  65.  
  66.   Serial.print(delay_time);
  67.   Serial.print(” delay time; inches are= “);
  68.   Serial.print(inches);
  69.   Serial.println();
  70. }
  71.  
  72. long microsecondsToInches(long microseconds)
  73. {
  74.   return microseconds / 74 / 2;
  75. }

Project Videos

Share/Bookmark


  • Newsletter

    Sign up for the PlanetArduino Newsletter, which delivers the most popular articles via e-mail to your inbox every week. Just fill in the information below and submit.

  • Like Us on Facebook