Skip to content

Instantly share code, notes, and snippets.

@TG9541
Created April 25, 2020 12:51
Show Gist options
  • Save TG9541/8f7e153af4a28ed5560558899e2b4e98 to your computer and use it in GitHub Desktop.
Save TG9541/8f7e153af4a28ed5560558899e2b4e98 to your computer and use it in GitHub Desktop.
Minimal MODBUS RBU server for FC15 (using BF@ for LE and BF! for BE)
\ Minimal MODBUS server with a single FC handler
\
\ Features:
\ * implements FC15 "Write Multiple Coils"
\ * prints debug infos to the console
\
\ Example output for 96008N1, Node=1, FC=15 Addr=22, N=10, Data=111...
\
\ coils 10 0 fill ok
\ ok
\ -> Trigger QModMaster, SA1. FC=0x0f, SA=22, N=10
\ Write register: A: 22 Q: 10
\ Write bits from end: 0
\ 22
\ 0
\ 23
\ 1
\ 24
\ 2
\ 25
\ 3
\ 26
\ 4
\ 27
\ 5
\ 28
\ 6
\ 29
\ 7
\ 30
\ 8
\ 31
\ 9
\ MODBUS rxbuf: 11
\ 80 1 F 0 16 0 A 2 FF 3 E6 3F 0 0 0 0 0 __________?_____
\ MODBUS txbuf: 8
\ 98 1 F 0 16 0 A 34 8 0 0 0 0 0 0 0 0 ______4_________
\ coils 10 dump
\ B6 0 0 FF C0 0 0 0 0 0 0 0 0 0 0 0 0 ________________ ok
\ check if the MODBUS protocol core is already present
\ hint: the development cycle will be faster if you PERSIST it
#require MBPROTO
\ Resetting the FC handler table can be helpful for development
#require WIPE
#require MBRESET
MBRESET \ Reset the MODBUS Function Code table
#require ALIAS
#require :NVM
#require 'IDLE
#require .OK
4 CONSTANT COILBYTES
NVM
#require MBDUMP
VARIABLE coils COILBYTES 2- ALLOT
\ --- FC15 "Write Multiple Coils"
\ MB test range mbp1,mbp2 in n*8 bits
:NVM ( n -- f )
8 * mbp1 mbp2 + - 0< NOT
;RAM ALIAS mbprange? NVM
\ FC15 Write Multiple Coils write transfer
:NVM ( i -- 1 )
DUP . CR
( i ) rxbuf 7 + OVER mbp1 - ( i a i0 ) DUP . CR BF@ SWAP ( b i )
coils SWAP ( b a i ) BF!
1 ( inc )
;RAM ALIAS FC15ACT NVM
\ FC15 handler
:NVM ( -- )
\ write register address and value to the console
." Write register: A:" mbp1 . ." Q:" mbp2 . CR
." Write bits from end:" COILBYTES 8 * mbp1 mbp2 + - . CR
COILBYTES mbprange? IF
[ ' FC15ACT ] LITERAL ( xt ) mbloop
MBSWR
ElSE
2 MBEC
THEN
;NVM ( xth ) 15 FC>XT !
: showfc ( -- )
rxbuf C@ ." FC:" . CR
1 MBEC \ set error code
;
: init ( -- )
0 UARTISR \ init UART handler w/ default baud rate
1 mbnode ! \ set node address
[ ' showfc ] LITERAL mbdef ! \ FC default action (optional feature)
[ ' MBDUMP ] LITERAL mbact ! \ show buffers (debug demo)
[ ' MBPROTO ] LITERAL 'IDLE ! \ run MB protocol handler as idle task
.OK
;
' init 'BOOT !
WIPE RAM
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment