\ -*- forth -*- \ \ This program uses a free-running timer to generate a square wave \ that will light the floor. Four sensors will get sampled n times \ while the led is on, and all values will be added, while n values \ will be sampled when the led if off and will be removed from the \ totals. needs basicprimitives.f needs moreprimitives.f needs nointerrupts.f needs tty_40.f ADCON0 2 bit GO/DONE PORTB 0 bit led \ XXXXX variable v0 variable v1 variable v2 variable v3 0 value led-on? \ Reset counters : reset ( -- ) 0 v0 ! 0 v1 ! 0 v2 ! 0 v3 ! ; \ Accumulate measured value to the n-th counter : accumulate ( v n -- ) dup + v0 + led-on? if +! else -! then ; \ Switch led on or off : led-on ( -- ) 1 to led-on? led bit-set ; : led-off ( -- ) 0 to led-on? led bit-clr ; \ Check whether time has been reached and reset the timer bit : time-reached? ( -- f ) TMR0IF bit-set? if TMR0IF bit-clr 1 else 0 then ; \ Signal a fatal error -- result will be wrong : error ( -- ) ." Warning: processor too slow -- led-on? = " led-on? . cr ; \ Select A/D channel to work with : select-channel ( n -- ) ADCON0 c@ $c7 and 8 * or ADCON0 c! ; \ Perform a A/D conversion and return the 10 bits result : conversion ( -- r ) GO/DONE bit-set begin GO/DONE bit-clr? until ADRESH c@ swap-mlsb ADRESL c@ or ; \ Measure successively all four channels : measure ( -- ) 4 0 do i select-channel conversion i accumulate loop ; \ Do n measures in a row and wait for time to be reached -- signal a \ problem if we do not have enough computing power : measures ( n -- ) 0 do measure loop time-reached? if error then begin time-reached? until ; \ Compute differences between active and passive detection by adding and \ substracting n measures : compute ( n -- ) led-on reset dup measures led-off measures ; \ Transmit results -- use serial output at this time : transmit-results ( -- ) v0 @ . cr ; \ Do four measures for each state and transmit results : step ( -- ) 4 compute transmit-results ; \ Initializations : inits ( -- ) \ A/D converter $81 ADCON0 c! $42 ADCON1 c! \ LED XXXXX TRISB 0 bit-clr \ CAN TRISB 3 bit-clr \ Timer 0, 8 bits mode, prescaler of 64 \ This gives an operating frequency of 305.18Hz for a square wave $c5 T0CON c! ; : greetings ( -- ) ." Welcome to the sensors program\n" ; \ Main program : main ( -- ) inits greetings begin step again ;