what's Ultrasonic module
Ultrasonic Distance Sensor module supports a contactless detection within a distance of
2cm-400cm. It contains an ultrasonic emitter, receiver and control circuits.
Notes:
1. The module is not suggested to connect wires when power is on. If you have to do so,
please first connect the GND and then other pins; otherwise, the module may not work.
2. During the ranging, the area of the targeted object should be no less than 0.5cm and the
surface facing the module should be as flat as possible; otherwise the result may be
inaccurate.
Trig | Digital output |
Echo | Digital output |
Vcc | VCC |
Gnd | GND |
1 * microbit
1 * microbit expansion board
1 * USB cable
1 * Ultrasonic sensor module
- Several Jumper wires
connection diagram:
Code:
Makecode:
MU python:
#----------------------------------------------------------- # File name : Ultrasonic.py # Description : Ultrasonic ranging. # Author : jason # E-mail : jason@adeept.com # Website : www.adeept.com # Date : 2019/01/21 #----------------------------------------------------------- from microbit import * class HCSR04: def __init__(self, tpin=pin15, epin=pin14, spin=pin13): self.trigger_pin = tpin self.echo_pin = epin self.sclk_pin = spin def distance_mm(self): spi.init(baudrate=115200, sclk=self.sclk_pin, mosi=self.trigger_pin, miso=self.echo_pin) pre = 0 post = 0 k = -1 length = 500 resp = bytearray(length) resp[0] = 0xFF spi.write_readinto(resp, resp) # find first non zero value try: i, value = next((ind, v) for ind, v in enumerate(resp) if v) except StopIteration: i = -1 if i > 0: pre = bin(value).count("1") # find first non full high value afterwards try: k, value = next((ind, v) for ind, v in enumerate(resp[i:length - 2]) if resp[i + ind + 1] == 0) post = bin(value).count("1") if k else 0 k = k + i except StopIteration: i = -1 dist= -1 if i < 0 else round((pre + (k - i) * 8. + post) * 8 * 0.172) return dist sonar=HCSR04() while True: print('%.1f' % (sonar.distance_mm()/10)) sleep(1000)
Click “flash” and download the code onto the micro:bit.
We can see the data fed back by the ultrasonic module on the serial port.
Effect Picture:
Components
- 1 * Adeept Arduino UNO R3 Board
- 1 * Ultrasonic Distance Sensor Module
- 1 * USB Cable
- 4 * Male to Female Wires
Step 1: Build the circuit
Adeept UNO R3 Board | Ultrasonic Distance Sensor Module |
D7 | Trig |
D5 | Echo |
5V | Vcc |
Step 2:Code
/*********************************************************** File name: _36_UltrasonicDistanceSensorModule.ino Description: When you move the obstacle in front of the ultrasonic module,you can see the data on the serial montiol. Website: www.adeept.com E-mail: support@adeept.com Author: Tom Date: 2019/01/21 ***********************************************************/ const int pingPin = 5; // pin connected to Echo Pin in the ultrasonic distance sensor const int trigPin = 7; // pin connected to trig Pin in the ultrasonic distance sensor void setup() { pinMode(pingPin, INPUT); //Set the connection pin output mode Echo pin pinMode(trigPin, OUTPUT);//Set the connection pin output mode trog pin Serial.begin(9600); //opens serial port, sets data rate to 9600 bps } void loop() { int cm = ping(pingPin); Serial.print("distance: "); // Print a message of "Temp: "to the serial montiol. Serial.print(cm); // Print a centigrade temperature to the serial montiol. Serial.println(" cm"); // Print the unit of the centigrade temperature to the serial montiol. delay(500); } int ping(int pingPin) { // establish variables for duration of the ping, // and the distance result in inches and centimeters: long duration, cm; // The PING))) is triggered by a HIGH pulse of 2 or more microseconds. // Give a short LOW pulse beforehand to ensure a clean HIGH pulse: pinMode(trigPin, OUTPUT); digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(5); digitalWrite(trigPin, LOW); pinMode(pingPin, INPUT); duration = pulseIn(pingPin, HIGH); // convert the time into a distance cm = microsecondsToCentimeters(duration); return cm ; } long microsecondsToCentimeters(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 of the // object we take half of the distance travelled. return microseconds / 29 / 2; }
Step 3: Compile and download the sketch to the UNO R3 board.
Open Serial Monitor of the Arduino IDE. You will see the distance to the obstacle at front of
the Ultrasonic Distance Sensor module displayed on the window.
Components
- 1 * Raspberry Pi
- 1 * GPIO Extension Board
- 1 * 40-Pin GPIO Cable
- 1 * Breadboard
- 1 * Ultrasonic Sensor Module
- 4 * Jumper Wires
Step 1: Build the circuit
Code:
C code
/* * Filename : distance.c * Description : Measure distance with ultrasonic sensor module. * Website : www.adeept.com * E-mail : support@adeept.com * Author : Jason * Date : 2019/01/21 */ #include <wiringPi.h> #include <stdio.h> #include <sys/time.h> #define Trig 4 #define Echo 5 void ultraInit(void) { pinMode(Echo, INPUT); pinMode(Trig, OUTPUT); } float disMeasure(void) { struct timeval tv1; struct timeval tv2; long start, stop; float dis; digitalWrite(Trig, LOW); delayMicroseconds(2); digitalWrite(Trig, HIGH); //produce a pluse delayMicroseconds(10); digitalWrite(Trig, LOW); while(!(digitalRead(Echo) == 1)); gettimeofday(&tv1, NULL); //current time while(!(digitalRead(Echo) == 0)); gettimeofday(&tv2, NULL); //current time start = tv1.tv_sec * 1000000 + tv1.tv_usec; stop = tv2.tv_sec * 1000000 + tv2.tv_usec; dis = (float)(stop - start) / 1000000 * 34000 / 2; //count the distance return dis; } int main(void) { float dis; if(wiringPiSetup() == -1){ //when initialize wiring failed,print message to screen printf("setup wiringPi failed !\n"); return -1; } ultraInit(); while(1){ dis = disMeasure(); printf("Distance = %0.2f cm\n",dis); delay(1000); } return 0; }
Python code
#! /usr/bin/python import RPi.GPIO as GPIO import time def checkdist(): GPIO.output(16, GPIO.HIGH) time.sleep(0.000015) GPIO.output(16, GPIO.LOW) while not GPIO.input(18): pass t1 = time.time() while GPIO.input(18): pass t2 = time.time() return (t2-t1)*340/2 GPIO.setmode(GPIO.BOARD) GPIO.setup(16,GPIO.OUT,initial=GPIO.LOW) GPIO.setup(18,GPIO.IN) time.sleep(2) try: while True: print 'Distance: %0.2f m' %checkdist() time.sleep(0.5) except KeyboardInterrupt: GPIO.cleanup()
For C language users:
Step 2: Edit and save the code with vim or nano.
(code path: /home/Adeept_Sensor_Kit_for_RPi_C_Code/21_ultrasonicSensor/distance.c)
Step 3: Compile
$ sudo gcc distance.c -o distance -lwiringPi
Step 4: Run
$ sudo ./distance
For Python users:Step 2: Edit and save the code with vim or nano.
(code path: /home/Adeept_Sensor_Kit_for_RPi_Python_Code/21_distance.py)
Step 3: Run
$ sudo python 21_distance.py
Now, you will see the distance to the obstacle at front of the Ultrasonic Distance Sensor
module displayed on the terminal.
Link for code download:http://www.adeept.com/learn/ Download the kit information as needed.
Video link:http://www.adeept.com/video/