fossasia / pslab-firmware

Firmware for PSLab Open Hardware Platform https://pslab.io
Apache License 2.0
1.56k stars 75 forks source link

feat: hcsr04 sensor implementation #118

Closed CloudyPadmal closed 2 years ago

CloudyPadmal commented 3 years ago

TODO:

bessman commented 2 years ago

Here is a software implementation in Python:

import time

from pslab.instrument.logic_analyzer import LogicAnalyzer
from pslab.instrument.waveform_generator import PWMGenerator

class HCSR04Soft(LogicAnalyzer, PWMGenerator):
    def __init__(self, device):
        self._device = device
        LogicAnalyzer.__init__(self, self._device)
        PWMGenerator.__init__(self, self._device)
        self._measure_period = 60e-3
        self._trigger_pulse_length = 10e-6

    def estimate_distance(
            self,
            trig="SQ1",
            echo="LA1",
            average=10,
            speed_of_sound=340
        ):
        self.capture(channels=echo, events=2*average, block=False)
        self.generate(
            channels=trig,
            frequency=self._measure_period ** -1,
            duty_cycles=self._trigger_pulse_length / self._measure_period
        )
        time.sleep(self._measure_period * average)
        self.set_state(**{trig.lower(): 0})
        (t,) = self.fetch_data()
        high_times = t[::2] - t[1::2]
        return speed_of_sound * high_times.mean() / 2 * 1e-6

Haven't tested it since I don't have the sensor, but it should work. This implementation has a number of benefits over the firmware:

CloudyPadmal commented 2 years ago

@bessman sorry I didn't see the question of implementing this in Python earlier. I think that's a good idea and I just checked the code snippet you shared and it works! It's a neat trick to use the logic analyser to capture multiple samples to average the result. I like to go ahead with the Python path. Let me close this PR and link it to python-repo as an issue.