Alex JonssonJohan Risch
Published © MIT

Measure distance with ultrasonics on SA Studio

Arduino UNO is great for sensor projects. With som help from SA Engine, you get your own visual measuring tool, and learn about SA Studio!

BeginnerProtip1 hour153
Measure distance with ultrasonics on SA Studio

Things used in this project

Hardware components

Arduino UNO
Arduino UNO
×1
Ultrasonic Sensor - HC-SR04 (Generic)
Ultrasonic Sensor - HC-SR04 (Generic)
×1

Software apps and online services

Arduino IDE
Arduino IDE
SA Studio
Stream Analyze SA Studio

Story

Read more

Schematics

Basic controller for HSC04 Ultrasonic Sensor

Code

Arduino code for the HSC04 Ultrasonic Sensor

C/C++
Use with Ardunio SDK, trigger on pin D4, receiving pin on D5
#define echoPin 5
#define triggerPin 4

long duration; // variable for the duration of sound wave travel
uint16_t  distance; // distance to target in cm

void setup() {
  pinMode(triggerPin, OUTPUT); // Sets the trigPin as an OUTPUT
  pinMode(echoPin, INPUT);
  Serial.begin(115200); 
  Serial.println("let's go");
}

uint16_t distance_sensor()
{
  // Clears the trigPin condition
  digitalWrite(triggerPin, LOW);
  delayMicroseconds(2);
  // Sets the triggerPin HIGH (ACTIVE) for 10 microseconds
  digitalWrite(triggerPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(triggerPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  // Calculating the distance
  distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (to target and back)
  // Displays the distance on the Serial Monitor (cm)
  if (distance > 500)   // avoid out-of-range measurements
    {
        distance = 500;
    }
  return distance;
}

void loop() {
  static uint8_t pkt[2];
   pkt[0] = 0x55; //Startbyte
 *((uint16_t *)&pkt[1]) = distance_sensor();
  pkt[3] = 0xAA; //stopbyte
  Serial.write(pkt,4);  
  // Serial.write(distance_sensor());
  delay(500);
}

Credits

Alex Jonsson
5 projects • 0 followers
Contact
Johan Risch
3 projects • 0 followers
Contact

Comments

Please log in or sign up to comment.