I have a simple connection to an ultrasonic sensor (HC-SR04) connected to an USB 1208LS, I have tried 5 different sensors from different manufacturers and have had no success on getting them to work so I can mostly rule out the sensors.
The connection diagram is very straightforward and is as follows:
PortA Channel 0 -> Trigger pin#21
PortB Channel 8 (or per documentation PortA Channel 15) -> Echo pin#39
Vcc = 5V coming from pin #30
Gnd coming from pin #40
Here is my python script to run a the sensor. I took mostly from this site and adjusted for the USB-1208LS.
import time
from mcculw import ul
from mcculw.enums import DigitalPortType, DigitalIODirection
from mcculw.device_info import DaqDeviceInfo
from console.console_examples_util import config_first_detected_device
board_num = 0
dev_id_list = []
config_first_detected_device(board_num, dev_id_list)
bit_num_out = 0
bit_num_in = 15
bit_value = 0
daq_dev_info = DaqDeviceInfo(board_num)
dio_info = daq_dev_info.get_dio_info()
port_out = dio_info.port_info[0]
port_in = dio_info.port_info[1]
ul.d_config_port(board_num, DigitalPortType.FIRSTPORTA, DigitalIODirection.OUT)
ul.d_config_port(board_num, DigitalPortType.FIRSTPORTB, DigitalIODirection.IN)
def distance():
# set Trigger to HIGH
bit_value_low = 0
bit_value_high = 1
StartTime = 0
StopTime = 0
ul.d_bit_out(board_num, port_out.type, bit_num_out, bit_value_high)
time.sleep(0.00001)
ul.d_bit_out(board_num, port_out.type, bit_num_out, bit_value_low)
# save StartTime
while ul.d_bit_in(board_num, port_out.type, bit_num_in) == 0:
StartTime = time.time()
print(f'Echoe = 0: {StartTime}')
# save time of arrival
while ul.d_bit_in(board_num, port_out.type, bit_num_in) == 1:
StopTime = time.time()
print(f'Echo = 1: {StopTime}')
# time difference between start and arrival
TimeElapsed = StopTime - StartTime
# multiply with the sonic speed (34300 cm/s)
# and divide by 2, because there and back
distance_traveled = (TimeElapsed * 34300) / 2
return distance_traveled
if __name__ == '__main__':
try:
while True:
dist = distance()
print (f"Measured Distance = {dist:0.1f}")
time.sleep(1)
# Reset by pressing CTRL + C
except KeyboardInterrupt:
print("Measurement stopped by User")
The script endlessly loops on "while ul.d_bit_in(board_num, port_out.type, bit_num_in) == 0:" so it seems that the echo never receives the HIGH value back to exit the loop.
Output:
I have no idea what could be wrong. Does anyone have an idea on what I might be doing wrong? I have already tried to troubleshoot this over and over with no success.
I would greatly appreciate any help.