|
3 | 3 | // We communicate with the Arduino at 115200 baud.
|
4 | 4 | #define SERIAL_BAUD 115200
|
5 | 5 |
|
6 |
| -#define FW_VER 1 |
| 6 | +#define FW_VER 2 |
7 | 7 |
|
8 | 8 | void setup() {
|
9 | 9 | Serial.begin(SERIAL_BAUD);
|
10 | 10 | }
|
11 | 11 |
|
12 | 12 | int read_pin() {
|
| 13 | + // Convert the ASCII character to a pin number. |
| 14 | + // a -> 0, b -> 1, c -> 2, etc. |
13 | 15 | while (!Serial.available());
|
14 | 16 | int pin = Serial.read();
|
15 | 17 | return (int)(pin - 'a');
|
@@ -43,6 +45,33 @@ void command_mode(int mode) {
|
43 | 45 | pinMode(pin, mode);
|
44 | 46 | }
|
45 | 47 |
|
| 48 | +void command_ultrasound() { |
| 49 | + int pulse = read_pin(); |
| 50 | + int echo = read_pin(); |
| 51 | + |
| 52 | + // config pins to correct modes |
| 53 | + pinMode(pulse, OUTPUT); |
| 54 | + pinMode(echo, INPUT); |
| 55 | + |
| 56 | + // provide pulse to trigger reading |
| 57 | + digitalWrite(pulse, LOW); |
| 58 | + delayMicroseconds(2); |
| 59 | + digitalWrite(pulse, HIGH); |
| 60 | + delayMicroseconds(5); |
| 61 | + digitalWrite(pulse, LOW); |
| 62 | + |
| 63 | + // measure the echo time on the echo pin |
| 64 | + int duration = pulseIn(echo, HIGH, 60000); |
| 65 | + Serial.print(microsecondsToMm(duration)); |
| 66 | +} |
| 67 | + |
| 68 | +long microsecondsToMm(long microseconds) { |
| 69 | + // The speed of sound is 340 m/s or 29 microseconds per centimeter. |
| 70 | + // The ping travels out and back, so to find the distance we need half |
| 71 | + // 10 x (us / 29 / 2) |
| 72 | + return (5 * microseconds / 29); |
| 73 | +} |
| 74 | + |
46 | 75 | void loop() {
|
47 | 76 | // Fetch all commands that are in the buffer
|
48 | 77 | while (Serial.available()) {
|
@@ -70,6 +99,9 @@ void loop() {
|
70 | 99 | case 'p':
|
71 | 100 | command_mode(INPUT_PULLUP);
|
72 | 101 | break;
|
| 102 | + case 'u': |
| 103 | + command_ultrasound(); |
| 104 | + break; |
73 | 105 | case 'v':
|
74 | 106 | Serial.print("SRcustom:");
|
75 | 107 | Serial.print(FW_VER);
|
|
0 commit comments