Search code examples
pythonaudiopygameraspberry-pi3sensors

Plugging Audio Jack from Raspberry Pi to Audio Interface Stops Sensor From Working


I'm running a very simple Python script to register and print distance using the HC-SR04 ultrasonic distance sensor. The script works when the 3.5mm cable is plugged out of the Raspberry and not plugged into the audio interface.
But when the cable is plugged into the audio interface as well, the gpiozero library throws me the error

/usr/lib/python3/dist-packages/gpiozero/input_devices.py:978: DistanceSensorNoEcho: no echo received 

warnings.warn(DistanceSensorNoEcho('no echo received'))

Could this maybe be a grounding issue?.. I also thought maybe a power delivery problem? ie, when the audio jack is plugged in, there isn't enough power to run the sensor as the amplifier has to start working?... But the code runs when my headphones are plugged in. So that should discount that.

Got about two weeks to figure this one out before the deadline for an exhibition... So any help or pointers would be much appreciated!

This is the python code:

#!/usr/bin/python3
# https://www.youtube.com/watch?v=JvQKZXCYMUM

import RPi.GPIO as GPIO
import pygame
from threading import Thread
from signal import signal, SIGTERM, SIGHUP, pause
from time import sleep
from gpiozero import DistanceSensor

pygame.mixer.init()
pygame.mixer.Sound("raspi-files/audio/1khz.wav")

reading = True
sensor = DistanceSensor(echo=24, trigger=21)

def safe_exit(signum, frame):
    exit(1)

    

def read_distance():
    while reading:
        print("Distance: ", sensor.distance)
        sleep(0.1)


signal(SIGTERM, safe_exit)
signal(SIGHUP, safe_exit)

try:
    reader = Thread(target=read_distance, daemon=True)
    reader.start()


    pause()

except KeyboardInterrupt:
    pass

finally:
    reading = False
    sensor.close()

Solution

  • So in the end, the trigger pin numbering in the code was wrong... Trigger should've been 23.

    But the crazy thing is that the code and sensor still worked (but only when the audio cable was left unplugged)! The sensor still registered distance continuously and reported it back to the console as expected... So I had no real reason to think the code was wrong...

    Also on the gpiozero github people stumped by that. Very odd.