michael ma
Created November 27, 2023

Ultrasonic Ranging and Obstacle Avoidance for Swimming

Use ultrasonic sensor to avoid obstacle in swimming or walking for individuals with disabilities.

58

Things used in this project

Hardware components

Blues Swan
Blues Swan
×1
Ultrasonic Sensor - HC-SR04 (Generic)
Ultrasonic Sensor - HC-SR04 (Generic)
×1
Seeed Studio buzzer
×1

Story

Read more

Code

ultrasound detector

C/C++
trigger ultrasound to detect distance from obstacle.
#include <Arduino.h>

// put function declarations here:
// PA3->A0  PA1->A1 PC3->A2
#define TRIG PA5
#define ECHO PA6
#define ALARM PA7

long duration, distance;

void setup() {
  // put your setup code here, to run once:
  pinMode(TRIG,OUTPUT);
  pinMode(ECHO,INPUT);
  pinMode(ALARM,OUTPUT);
  pinMode(LED_BUILTIN, OUTPUT);
}
void flash(int dis){ 
  digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
  delay(distance*10);                     // wait for a second
  digitalWrite(LED_BUILTIN, LOW);  // turn the LED off by making the voltage LOW
  delay(distance*10);                     
}


// put function definitions here:
int Sonar() {
  //sent pulse to trig
  digitalWrite(TRIG, LOW);
  delayMicroseconds(5);
  digitalWrite(TRIG, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG, LOW);

  duration = pulseIn(ECHO,HIGH,250000);
  //计算距离,单位厘米
  distance = duration/2/29.1; 

  return distance;
}

//if distance is too near, broadcast alarm sound
void alarm(int dis){
  int max = 250;
  int min = 20;
  int dd = 250;
  if (dis> max)
    dis = max;
  else if(dis<min)
    dis = min;
  dd  = (dis-min)*1.0/(max-min)+min;
  
  digitalWrite(ALARM, HIGH); // turn the LED on (HIGH is the voltage level)
  delay(dd);                     // wait for a second
  digitalWrite(ALARM, LOW);  // turn the LED off by making the voltage LOW
  delay(dd);                    // wait for a second
}

//display sonar value in screen
void display(int dis){

}

void loop() {
  // put your main code here, to run repeatedly:
  long distant = 0;
  distant = Sonar();
  alarm(distant);
  delayMicroseconds(250);
  flash(distant);
}

Credits

michael ma

michael ma

4 projects • 2 followers

Comments