Last active
March 3, 2022 07:31
-
-
Save TG9541/617c9c719eee3c9c2345d69a505491a7 to your computer and use it in GitHub Desktop.
A W1209 thermostat displays distance captured by an HC-SR04 ultrasonic sensor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
\ The HC-SR04 "trig" pin is connected to the SET key input (PC3). | |
\ The "echo" pin is connected to the same GPIO with a 1k resistor | |
\ Uses TIM1 with 1µs clock -> 3.4mm resolution. | |
#require ]B! | |
\res MCU: STM8S103 | |
\res export PC_DDR PC_ODR PC_CR1 | |
\res export TIM1_PSCRH TIM1_SR1 TIM1_CCMR3 TIM1_CCMR4 TIM1_CCER2 TIM1_CR1 | |
\res export TIM1_CCR3HTIM1_CCR4H | |
NVM | |
: T1Init ( -- ) | |
\ Init Timer1 with prescaler ( n=15 -> 1 MHz) | |
15 TIM1_PSCRH 2C! | |
\ CC3,CC4: pulse width measurement rising and falling edge | |
$01 TIM1_CCMR3 C! \ CC3S=TIM1_CCMR3.1-0=01 | |
$20 TIM1_CCER2 C! \ x.1 CC3P=0, x.5 CC4P=1 | |
$02 TIM1_CCMR4 C! \ CC4S=TIM1_CCMR4.1-0=10 | |
$31 TIM1_CCER2 C! \ x.1 CC3P=0, x.5 CC4P=1, CC3E=1, CC4E=1 | |
1 TIM1_CR1 C! \ enable TIM1 | |
[ 1 PC_ODR 3 ]B! \ initialize PC3 output for "trig" pulse | |
; | |
: delay ( -- ) \ loop a little | |
8 FOR NEXT | |
; | |
: bgtask ( -- ) \ background task | |
TIM 15 AND 0= IF | |
\ 16*5ms = 80ms between measurments | |
[ 1 PC_DDR 3 ]B! | |
[ 1 PC_CR1 3 ]B! | |
delay | |
[ 0 PC_CR1 3 ]B! | |
[ 0 PC_DDR 3 ]B! | |
delay | |
0 TIM1_SR1 C! \ guard CC3 and CC4 | |
ELSE \ wait for CC3 and CC4 capture | |
$18 TIM1_SR1 C@ OVER AND = IF | |
TIM1_CCR4H 2C@ TIM1_CCR3H 2C@ | |
- 100 580 */ . \ scale to mm and print | |
0 TIM1_SR1 C! | |
THEN | |
THEN | |
; | |
: startup ( -- ) | |
T1Init | |
[ ' bgtask ] LITERAL BG ! | |
; | |
' startup 'BOOT ! | |
RAM |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
STM8 eForth W1209 based HC-SR04 Ultrasonic Distance Display
This code uses a W1209 and a HC-SR04 (or a compatible device for $0.75) to create an ultrasonic distance display. By controlling the relay, building an approximation detector, fill level controller, or some other embedded control device is easy.
Also see the discussion in Issue #136:
I received a HC-SR04 and connected it to a W1209 through PC3/TIM1_CH3 (the set key input). With the STM8S Timer1 puls-width measurement feature it works surprisingly well (up to about 3m).
The W1219 doesn't have an input that's equally well suited, but I'm sure that something can be hacked with PD4/TIM2_CH1 (although the background task might have to use TIM1 then).