tinygo.org/x/drivers@v0.27.1-0.20240509133757-7dbca2a54349/hcsr04/hcsr04.go (about) 1 // Package hcsr04 provides a driver for the HC-SR04 ultrasonic distance sensor 2 // 3 // Datasheet: 4 // https://cdn.sparkfun.com/datasheets/Sensors/Proximity/HCSR04.pdf 5 package hcsr04 6 7 import ( 8 "machine" 9 "time" 10 ) 11 12 const TIMEOUT = 23324 // max sensing distance (4m) 13 14 // Device holds the pins 15 type Device struct { 16 trigger machine.Pin 17 echo machine.Pin 18 } 19 20 // New returns a new ultrasonic driver given 2 pins 21 func New(trigger, echo machine.Pin) Device { 22 return Device{ 23 trigger: trigger, 24 echo: echo, 25 } 26 } 27 28 // Configure configures the pins of the Device 29 func (d *Device) Configure() { 30 d.trigger.Configure(machine.PinConfig{Mode: machine.PinOutput}) 31 d.echo.Configure(machine.PinConfig{Mode: machine.PinInput}) 32 } 33 34 // ReadDistance returns the distance of the object in mm 35 func (d *Device) ReadDistance() int32 { 36 pulse := d.ReadPulse() 37 38 // sound speed is 343000 mm/s 39 // pulse is roundtrip measured in microseconds 40 // distance = velocity * time 41 // 2 * distance = 343000 * (pulse/1000000) 42 return (pulse * 1715) / 10000 //mm 43 } 44 45 // ReadPulse returns the time of the pulse (roundtrip) in microseconds 46 func (d *Device) ReadPulse() int32 { 47 t := time.Now() 48 d.trigger.Low() 49 time.Sleep(2 * time.Microsecond) 50 d.trigger.High() 51 time.Sleep(10 * time.Microsecond) 52 d.trigger.Low() 53 i := uint8(0) 54 for { 55 if d.echo.Get() { 56 t = time.Now() 57 break 58 } 59 i++ 60 if i > 10 { 61 if time.Since(t).Microseconds() > TIMEOUT { 62 return 0 63 } 64 i = 0 65 } 66 } 67 i = 0 68 for { 69 if !d.echo.Get() { 70 return int32(time.Since(t).Microseconds()) 71 } 72 i++ 73 if i > 10 { 74 if time.Since(t).Microseconds() > TIMEOUT { 75 return 0 76 } 77 i = 0 78 } 79 } 80 return 0 81 }