Skip to content

Instantly share code, notes, and snippets.

@TG9541
Created March 3, 2021 21:01
Show Gist options
  • Save TG9541/348abfae54c79f1c1c5a4f4ed0dcfdf5 to your computer and use it in GitHub Desktop.
Save TG9541/348abfae54c79f1c1c5a4f4ed0dcfdf5 to your computer and use it in GitHub Desktop.
1-Wire with STM8 eForth: using CamelForth "onewire.f"

The first 1-wire low level sketch was nice - but since Brad J. Rodriguez has implemented high level code, e.g. the 0F0h "ROM Search" algorithm, for CamelForth it's maybe a better idea to re-use it!

The "onewire" source archive contains the CamelForth source file "onewire.f", MSP430 assembler code and some documentation. The assembler code implements the primitives OWRESET (reset the bus) and OWSLOT (write and read a bit).

Unlike the MSP430 files the low-level code doesn't need to be compiled into the kernel, and the configuration doesn't need to be fixed.

Here are the primitives in STM8 eForth (the words gpio.d and gpio.i carry the GPIO configuration into the code):

\ STM8 eForth "1-Wire" communication primitives
#require ]B!
#require ]B?
#require ]CB
#require ]BC
#require :NVM
#require ALIAS

:NVM ( -- )    \ GPIO low / dominant
  [ 1 gpio.d ]B!
;RAM ALIAS 1w.l

:NVM ( -- )    \ GPIO floating / input
  [ 0 gpio.d ]B!
;RAM ALIAS 1w.f

:NVM ( n -- )  \ wait (n+1) * 2us @16MHz
  FOR [ $9d9d , $9d9d , $9d9d , $9d C, ] NEXT
;RAM ALIAS x2us

NVM
  : OWRESET ( -- f ) \ 1-wire reset with presence check
    1w.l 240 x2us  1w.f 30 x2us  [ gpio.i ]B? NOT 210 x2us
  ;

  : OWSLOT ( c -- c ) \ 1-wire transfer 1 bit c -> c
    [ $9B  C, ]      \  SIM        ; disable interrupts
    1w.l  1 x2us
    [ $E601 ,       \   LD   A,(1,X)
      $44  C,       \   SRL  A
      $8C  C,       \   CCF        ; enable gpio.d when low
      gpio.d ]CB
    3 x2us
    [ gpio.i ]BC
    [ $9A  C,       \   RIM        ; enable interrupts  
      $6601 , ]     \   RRC  (1,X)
    12 x2us  1w.f  1 x2us
  ;
RAM

Besides the primitives the high-level code in onewire.f needs some additional word like LSHIFT and INVERT needs to be an "alias" for NOT. Due to a non-standard commment stile the copyright notice needs some extra love.

\res MCU: STM8S103
\res export PB_DDR PB_IDR
: gpio.d ( -- a c ) PB_DDR 4 ;  \ literals for DDR GPIO
: gpio.i ( -- a c ) PB_IDR 4 ;  \ literals IDR GPIO

#require OWSLOT
#require LSHIFT
#require ALIAS
#require PAD

' NOT ALIAS INVERT
: HOWEVER ;
: IN ;
: ARISING ;

NVM
  #require >
  #include onewire.f
RAM

The result works well. The performance of ROMSEARCH isn't optimal (but why should it be that).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment