Created
July 30, 2020 21:20
-
-
Save andrewsclapp/b485d7861382763dc91a7d252b924f6d to your computer and use it in GitHub Desktop.
transmit and receive side of a serial connection
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
transmit side: | |
: send_byte ( n -- ) \ send byte as 8 bits | |
' TXP! 'EMIT ! | |
8 .R | |
' EMIT 'EMIT ! | |
; | |
VARIABLE STATE | |
VARIABLE REM | |
VARIABLE QUOT | |
: trans \ to be run in idle task | |
timer2 tTest IF | |
95 send_byte \ '_' - "do nothing" | |
ELSE | |
\ send average in 2 bytes plus 1 byte CRC | |
STATE @ 0= IF | |
\ send a byte each time called | |
\ scana ADCVAR @ DROP \ drop the first one | |
\ scana ADCVAR @ \ current | |
ADCVAR @ \ current | |
330 4095 */ \ scale for current - still more than one byte | |
255 /MOD ( REM QUOT ) \ split into bytes | |
DUP QUOT ! \ store quotient | |
send_byte \ send quotient | |
REM ! \ store remainder | |
1 STATE ! | |
THEN | |
STATE @ 1 = IF | |
REM @ \ fetch remainder | |
send_byte \ send remainder | |
2 STATE ! | |
THEN | |
STATE @ 2 = IF | |
REM @ \ fetch remainder | |
QUOT @ \ fetch quotient | |
-1 ROT ROT CRC16 | |
send_byte \ send remainder | |
0 STATE ! | |
THEN | |
timer2 3000 tSet count2 | |
THEN | |
; | |
receive side: | |
VARIABLE STATE | |
VARIABLE CURRENT | |
VARIABLE CTMPA | |
VARIABLE CTMPB | |
\ receiver: | |
\ wait? -> state 0 | |
\ receive X-> state1 | |
\ receive X-> state2 | |
\ receive C-> state3 | |
\ check. repeat | |
: rec1 | |
?RXP IF | |
DUP 95 = IF \ '_' (ascii 95) wait? -> state 0. | |
0 STATE ! | |
DROP | |
ELSE \ some incoming bits | |
STATE @ 0 = IF \ quotient on top of stack | |
CTMPA ! | |
1 STATE ! | |
THEN | |
STATE @ 1 = IF \ remainder on top of stack | |
CTMPB ! | |
2 STATE ! | |
THEN | |
STATE @ 2 = IF \ crc on top of stack | |
>R \ hold this please | |
CTMPB @ CTMPA @ 2DUP -1 ROT ROT ( CTMPB CTMPA -1 CTMPB CTMPA ) | |
CRC16 | |
R> \ thank you | |
= IF \ CRC MATCH | |
255 * + CURRENT ! | |
ELSE \ CRC FAIL | |
DROP \ keep present value for CURRENT | |
THEN | |
0 STATE ! | |
THEN | |
THEN | |
THEN | |
; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment