[136] | 1 | /* Runaway Robot
|
---|
| 2 |
|
---|
| 3 | Play tag with your robot! With an ultrasonic
|
---|
| 4 | distance sensor, it's capable of detecting and avoiding
|
---|
| 5 | obstacles, never bumping into walls again!
|
---|
| 6 |
|
---|
| 7 | You'll need to attach an untrasonic range finder to M1.
|
---|
| 8 |
|
---|
| 9 | Circuit:
|
---|
| 10 | * Arduino Robot
|
---|
| 11 | * US range finder like Maxbotix EZ10, with analog output
|
---|
| 12 |
|
---|
| 13 | created 1 May 2013
|
---|
| 14 | by X. Yang
|
---|
| 15 | modified 12 May 2013
|
---|
| 16 | by D. Cuartielles
|
---|
| 17 |
|
---|
| 18 | This example is in the public domain
|
---|
| 19 | */
|
---|
| 20 |
|
---|
| 21 | // include the robot library
|
---|
| 22 | #include <ArduinoRobot.h>
|
---|
| 23 | #include <Wire.h>
|
---|
| 24 | #include <SPI.h>
|
---|
| 25 |
|
---|
| 26 | int sensorPin = M1; // pin is used by the sensor
|
---|
| 27 |
|
---|
| 28 | void setup() {
|
---|
| 29 | // initialize the Robot, SD card, and display
|
---|
| 30 | Serial.begin(9600);
|
---|
| 31 | Robot.begin();
|
---|
| 32 | Robot.beginTFT();
|
---|
| 33 | Robot.beginSD();
|
---|
| 34 | Robot.displayLogos();
|
---|
| 35 |
|
---|
| 36 | // draw a face on the LCD screen
|
---|
| 37 | setFace(true);
|
---|
| 38 | }
|
---|
| 39 |
|
---|
| 40 | void loop() {
|
---|
| 41 | // If the robot is blocked, turn until free
|
---|
| 42 | while (getDistance() < 40) { // If an obstacle is less than 20cm away
|
---|
| 43 | setFace(false); //shows an unhappy face
|
---|
| 44 | Robot.motorsStop(); // stop the motors
|
---|
| 45 | delay(1000); // wait for a moment
|
---|
| 46 | Robot.turn(90); // turn to the right and try again
|
---|
| 47 | setFace(true); // happy face
|
---|
| 48 | }
|
---|
| 49 | // if there are no objects in the way, keep moving
|
---|
| 50 | Robot.motorsWrite(255, 255);
|
---|
| 51 | delay(100);
|
---|
| 52 | }
|
---|
| 53 |
|
---|
| 54 | // return the distance in cm
|
---|
| 55 | float getDistance() {
|
---|
| 56 | // read the value from the sensor
|
---|
| 57 | int sensorValue = Robot.analogRead(sensorPin);
|
---|
| 58 | //Convert the sensor input to cm.
|
---|
| 59 | float distance_cm = sensorValue * 1.27;
|
---|
| 60 | return distance_cm;
|
---|
| 61 | }
|
---|
| 62 |
|
---|
| 63 | // make a happy or sad face
|
---|
| 64 | void setFace(boolean onOff) {
|
---|
| 65 | if (onOff) {
|
---|
| 66 | // if true show a happy face
|
---|
| 67 | Robot.background(0, 0, 255);
|
---|
| 68 | Robot.setCursor(44, 60);
|
---|
| 69 | Robot.stroke(0, 255, 0);
|
---|
| 70 | Robot.setTextSize(4);
|
---|
| 71 | Robot.print(":)");
|
---|
| 72 | } else {
|
---|
| 73 | // if false show an upset face
|
---|
| 74 | Robot.background(255, 0, 0);
|
---|
| 75 | Robot.setCursor(44, 60);
|
---|
| 76 | Robot.stroke(0, 255, 0);
|
---|
| 77 | Robot.setTextSize(4);
|
---|
| 78 | Robot.print("X(");
|
---|
| 79 | }
|
---|
| 80 | }
|
---|