Skip to content

Commit

Permalink
Merge pull request #2 from srobo/ultrasound
Browse files Browse the repository at this point in the history
Add ultrasound function
  • Loading branch information
WillB97 authored Aug 31, 2024
2 parents 41a8ed0 + 7528459 commit 5c09d31
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FW_VER=1
FW_VER=2
DEV=/dev/ttyACM0

CC=avr-gcc
Expand Down
32 changes: 32 additions & 0 deletions src/ruggeduino.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ void setup() {
}

int read_pin() {
// Convert the ASCII character to a pin number.
// a -> 0, b -> 1, c -> 2, etc.
while (!Serial.available());
int pin = Serial.read();
return (int)(pin - 'a');
Expand Down Expand Up @@ -47,6 +49,33 @@ void command_mode(int mode) {
pinMode(pin, mode);
}

void command_ultrasound() {
int pulse = read_pin();
int echo = read_pin();

// config pins to correct modes
pinMode(pulse, OUTPUT);
pinMode(echo, INPUT);

// provide pulse to trigger reading
digitalWrite(pulse, LOW);
delayMicroseconds(2);
digitalWrite(pulse, HIGH);
delayMicroseconds(5);
digitalWrite(pulse, LOW);

// measure the echo time on the echo pin
int duration = pulseIn(echo, HIGH, 60000);
Serial.print(microsecondsToMm(duration));
}

long microsecondsToMm(long microseconds) {
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance we need half
// 10 x (us / 29 / 2)
return (5 * microseconds / 29);
}

void loop() {
// Fetch all commands that are in the buffer
while (Serial.available()) {
Expand Down Expand Up @@ -74,6 +103,9 @@ void loop() {
case 'p':
command_mode(INPUT_PULLUP);
break;
case 'u':
command_ultrasound();
break;
case 'v':
Serial.print("SRduino:");
Serial.print(FW_VER);
Expand Down

0 comments on commit 5c09d31

Please sign in to comment.