Hi HA users!
I’m trying to get my ultrasonic sensor to work with ESPHome. The sensor is a JSN-SR04T-AJ-SR04M which is similar to the HC-SR04 but not exactly the same. So using the default ESPHome template ‘ultrasonic’ doesn’t work (wrong distance values are show, only 2 out of 10measurements are somewhat correct).
The SR04 has different modes, I soldered a 47kΩ resistor into the R27 Pin to enable the “contious mode”. In this mode the distance calculation is done on device all the time. To get the distance on can use the UART to retrieve the data.
Now I’m struggling with implementing this in ESPHome. I read that it is possible to add custom UART components, but I’m not sure if this is necessary in my case, or if I’m able to just receive the data using the regular uart integration.
The code to read the data from the sensor every two seconds looks like this in Python:
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)
There is also a german blogpost with some arduino examples for the different modes of the sensor, which I used to implement my python example above:
I hope that someone could give me a hint in the right direction since I’m not an arduino pro as you can probably see, thanks in advance for helping me out