Skip to content

Instantly share code, notes, and snippets.

@TG9541
Created January 5, 2019 23:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TG9541/f3a3ce83c9a04e743353ddf46ab745a8 to your computer and use it in GitHub Desktop.
Save TG9541/f3a3ce83c9a04e743353ddf46ab745a8 to your computer and use it in GitHub Desktop.
MODBUS protocol implementation
#require UARTISR
#require CRC16
#require ]B!
#require WIPE
NVM
: mbslv ( -- c )
;
\ get MODBUS FC
: mbfc ( -- c )
;
\ 1st MODBUS FC parameter
: mbp1 ( -- n )
rxbuf 2+ @
;
\ 2nd MODBUS FC parameter
: mbp2 ( -- n )
rxbuf 4 + @
;
\ calc CRC16 from buffer a0 to a1
: MBCRC ( a1 a0 -- crc-le )
-1 ROT ROT ( -1 a1 a0 ) DO
I C@ CRC16
LOOP
( CRC16 ) EXG ( CRC-LE )
;
\ flag MODBUS Exception and set Code
: MBEC ( ec -- )
[ 1 txbuf 1+ 7 ]B!
( ec ) txc+
;
\ default FC handler - raise EC 1 "ILLEGAL FUNCTION"
: FCNUL ( -- )
1 MBEC
;
\ FC-XT Table
CREATE FCXT ' FCNUL
DUP , DUP , DUP , DUP , DUP , DUP , DUP , DUP ,
DUP , DUP , DUP , DUP , DUP , DUP , DUP , ,
\ turn FC into XT
: FC>XT ( fc -- xt )
1- 2* FCXT +
;
: MBPROTO ( -- )
rxbuf rxp @ - ( rx )
1 TIM tstamp @ - < AND ( message trigger )
IF
rxp @ 2- ( a1 ) DUP rxbuf ( a1 a1 a0 )
MBCRC ( a1 crc-le ) SWAP @ =
( crc-ok ) IF
rxbuf C@ ( DUP ." S: " . CR ) txc+
rxbuf 1+ C@ ( DUP ." F: " . CR ) DUP txc+ ( fc )
DUP 1 17 WITHIN IF
FC>XT @ EXECUTE
ELSE
FCNUL
THEN
tbp @ txbuf ( a1 a0 ) MBCRC ( CRC-LE ) tx+
\ ELSE
\ ." CRC!" CR
THEN
start-tx rxres
\ bufdump
THEN
;
WIPE RAM
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment