How’s it going. I’m going to try and limit this for simplicity. I am a student studying EE. I have an UltraSonic Sensor connected using USB Serial Port CH340. I have tried to look for a python script that could give the distance but it seems it’s not possible. Any help or guidance is greatly appreciated. I’m just lost and don’t know where to turn to
You have to install pyserial library and write a code like the following:
import serial
import time
# Set up the serial connection
ser = serial.Serial('COM3', 9600, timeout=1) # Replace 'COM3' with your port, or '/dev/ttyUSB0' for Linux
time.sleep(2) # Wait for the connection to initialize
def read_distance():
if ser.in_waiting > 0:
data = ser.readline().decode('utf-8').rstrip() # Read the data from the sensor
try:
distance = float(data) # Convert to float if valid
print(f"Distance: {distance} cm")
except ValueError:
print("Invalid data received") # Handle non-numeric data
try:
while True:
read_distance()
time.sleep(0.1) # Small delay between readings
except KeyboardInterrupt:
print("Stopping...")
finally:
ser.close() # Close the serial connection
Hey, @MaximoEsfuerzo I did look into this I currently have it set up on Mode 5 as the guide and have it reading with a serial analyzer but when I use this script. It doesn't work
import serial
import time
import sys
ser = serial.Serial('/dev/ttyUSB0') # open serial port
byte = b'\xff' # xff is the start byte
while True:
x = ser.read()
if x == byte: #starbyte found
b1 = ser.read(1)
b2 = ser.read(1)
x1 = int.from_bytes(b1, sys.byteorder)
dist = (((x1 << 8) + int.from_bytes(b2, sys.byteorder)) / 10) # some bitshift magic, no idea what's happening here
print(dist - 5) # for some reason the distance value is 5cm off, remove them before printing the value
clear = ser.read_all()
ser.flushOutput()
time.sleep(2)
Hey @horace so I have the AJ-SR04M set up in mode 5 from this article. But when I try to write the python code to read distance data it returns nothing. Not sure if my code is incorrect.
@aliarifat794 I already had PySerial installed. I also tried your code and it doesn't work but I also made my own script and it also doesn't work could it be I don't have the USB serial port configured correctly? I have this USB TTL HW597 from electrodes. I have attached the script I made
import serial
import time
import sys
ser = serial.Serial('/dev/ttyUSB0') # open serial port
byte = b'\xff' # xff is the start byte
while True:
x = ser.read()
if x == byte: #starbyte found
b1 = ser.read(1)
b2 = ser.read(1)
x1 = int.from_bytes(b1, sys.byteorder)
dist = (((x1 << 8) + int.from_bytes(b2, sys.byteorder)) / 10) # some bitshift magic, no idea what's happening here
print(dist - 5) # for some reason the distance value is 5cm off, remove them before printing the value
clear = ser.read_all()
ser.flushOutput()
time.sleep(2)
yes because it needs to read the distance continuously, that's why I have it there, and it does read the distance but the numbers are not accurate at all maybe like 2 out 20 reads are good.
Here is my set up I have the sensor connected to the usb using wires connected to TX --> RXD and RX --> TXD. I also have the sensor on mode 5 per this forums instructions.
Is there anything I'm missing or anything going over my head. I'm not sure if it's the sensor or something I'm doing wrong. I tried it using a raspberry pico w and it worked so I don't believe it's the sensor. Any help is appreciated. Thank You all who have contributed
I soldered a 10Kohm resistor across the R7 pads to enable the UART
I understand that there are different versions of the jsn_sr04m - the one I have uses a 24bit distance (3 bytes) but there are 16bit versions and 24bit versions which use 4byte (3data+checksum)
if yours has a checksum you need to read it otherwise you may read it as part of the next data bytes and get results like you have in post 14
I currently don't have a picture of the Raspberry Pico W with me because I left it at friend's house but it's just a standard one looks something like this. I used GPIO pins to connect trig and echo and copied and pasted sample ultrasonic sensor code to get the distance and it worked. Pico-series Microcontrollers - Raspberry Pi Documentation
Here's the code I used to test the sensor:
from machine import Timer,Pin, PWM, ADC
#from machine import time_pulse_us
import time, array
import math
#This moves the servo to different angles
class Ultrasonic():
# Define output(trig) and input(echo) pins.
def __init__(self, trig, echo):
self._trig = Pin(trig, Pin.OUT)
self._echo = Pin(echo, Pin.IN)
def get_distance(self):
# Generate 10us square wave.
self._trig.low()
time.sleep_us(2)
self._trig.high()
time.sleep_us(10)
self._trig.low()
while self._echo.value() == 0:
start = time.ticks_us()
while self._echo.value() == 1:
end = time.ticks_us()
dis = (end - start) * 0.0343 / 2
# round to two decimal places.
return round(dis, 2)
if __name__ == '__main__':
# Ultrasonic pins. trig:GPIO3, echo:GPIO2
ultrasonic = Ultrasonic(4,5)
while True:
value = ultrasonic.get_distance()
print("Distance: {:.2f}cm" .format(value))
time.sleep(1)
clearly your jsn_sr04m is different from mine
the document referenced in post 16 does not mention the serial format
it is probably 3data bytes + checksum
possibly you read a block of four bytes, calculate the checksum and if it is correct you have the distance if not discard first byte and calculate again