Interfacing an analog joystick using Forth
pin import
adc import
26 constant x_pin ( GPIO pin of the X axis )
27 constant y_pin ( GPIO pin of the Y axis )
2 constant button_pin ( GPIO pin used for the button )
button_pin pull-up-pin ( Defining the button pin as pull-up )
: get-adc-chan pin-adc-chan ; ( Getting the ADC channel of the passed pin )
: x-pin-adc x_pin get-adc-chan ; ( Get the ADC channel of the x-axis pin )
: y-pin-adc y_pin get-adc-chan ; ( Likewise for the y-axis )
: read-adc default-adc adc@ ; ( Define the read word )
: joy_x x-pin-adc read-adc ." X: " . ; ( Constructing the output )
: joy_y y-pin-adc read-adc ." Y: " . ;
: button button_pin pin@ ." Button: " . ;
: print-joys joy_x joy_y button cr ; ( Concenating the outputs )
: joy ( -- )
begin key? not while print-joys 100 ms repeat ( print output repeatedly till a key gets pressed )
key drop ( then exit )
;
Example output:
X: 4013 Y: 1856 Button: 0
X: 2034 Y: 1552 Button: 0
X: 1807 Y: 1134 Button: -1
X: 1033 Y: 432 Button: 0
X: 324 Y: 25 Button: -1
In Forth -1 considered as true
while 0 is false
.