[136] | 1 | /* Robot Compass
|
---|
| 2 |
|
---|
| 3 | The robot has an on-board compass module, with
|
---|
| 4 | which it can tell the direction the robot is
|
---|
| 5 | facing. This sketch will make sure the robot
|
---|
| 6 | goes towards a certain direction.
|
---|
| 7 |
|
---|
| 8 | Beware, magnets will interfere with the compass
|
---|
| 9 | readings.
|
---|
| 10 |
|
---|
| 11 | Circuit:
|
---|
| 12 | * Arduino Robot
|
---|
| 13 |
|
---|
| 14 | created 1 May 2013
|
---|
| 15 | by X. Yang
|
---|
| 16 | modified 12 May 2013
|
---|
| 17 | by D. Cuartielles
|
---|
| 18 |
|
---|
| 19 | This example is in the public domain
|
---|
| 20 | */
|
---|
| 21 |
|
---|
| 22 | // include the robot library
|
---|
| 23 | #include <ArduinoRobot.h>
|
---|
| 24 | #include <Wire.h>
|
---|
| 25 | #include <SPI.h>
|
---|
| 26 |
|
---|
| 27 | int speedLeft;
|
---|
| 28 | int speedRight;
|
---|
| 29 | int compassValue;
|
---|
| 30 | int direc = 180; //Direction the robot is heading
|
---|
| 31 |
|
---|
| 32 | void setup() {
|
---|
| 33 | // initialize the modules
|
---|
| 34 | Robot.begin();
|
---|
| 35 | Robot.beginTFT();
|
---|
| 36 | Robot.beginSD();
|
---|
| 37 | Robot.displayLogos();
|
---|
| 38 | }
|
---|
| 39 |
|
---|
| 40 | void loop() {
|
---|
| 41 | // read the compass orientation
|
---|
| 42 | compassValue = Robot.compassRead();
|
---|
| 43 |
|
---|
| 44 | // how many degrees are we off
|
---|
| 45 | int diff = compassValue - direc;
|
---|
| 46 |
|
---|
| 47 | // modify degress
|
---|
| 48 | if (diff > 180)
|
---|
| 49 | diff = -360 + diff;
|
---|
| 50 | else if (diff < -180)
|
---|
| 51 | diff = 360 + diff;
|
---|
| 52 |
|
---|
| 53 | // Make the robot turn to its proper orientation
|
---|
| 54 | diff = map(diff, -180, 180, -255, 255);
|
---|
| 55 |
|
---|
| 56 | if (diff > 0) {
|
---|
| 57 | // keep the right wheel spinning,
|
---|
| 58 | // change the speed of the left wheel
|
---|
| 59 | speedLeft = 255 - diff;
|
---|
| 60 | speedRight = 255;
|
---|
| 61 | } else {
|
---|
| 62 | // keep the right left spinning,
|
---|
| 63 | // change the speed of the left wheel
|
---|
| 64 | speedLeft = 255;
|
---|
| 65 | speedRight = 255 + diff;
|
---|
| 66 | }
|
---|
| 67 | // write out to the motors
|
---|
| 68 | Robot.motorsWrite(speedLeft, speedRight);
|
---|
| 69 |
|
---|
| 70 | // draw the orientation on the screen
|
---|
| 71 | Robot.drawCompass(compassValue);
|
---|
| 72 | }
|
---|