Unit C · Telling a machine what you want
What we are making: a joystick you can read — two numbers that change as you push it, printed in the Serial Monitor.
A button gives you one of two answers: pressed, or not. A knob gives you a whole range — any number from 0 to 1023, depending on how far round it is turned. That is the difference between digital and analogue, and it is worth ten seconds of your attention because it never stops mattering.
A joystick is simply two knobs mounted at right angles, with a button underneath. Push it left and one number changes; push it forward and the other does. There is nothing else in there.
"LEFT" when x drops below 300.digitalRead(4) and print when it is pressed.x == 512 — test for a range, like ‘below 300’, and your program works on everybody's hardware, not just yours.| What you see | Why | What to do |
|---|---|---|
| Both numbers stuck at 0 | No power to the module. | Check +5V and GND. Almost always this. |
| Both numbers stuck at 1023 | GND is not connected. | Trace the black wire from the module to a GND pin. |
| The numbers drift by a few counts | Analogue readings always wobble. | Normal. It is why you test ranges, not exact values. |
| The button reads pressed constantly | The pin is floating. | Add pinMode(4, INPUT_PULLUP); it then reads LOW when pressed. |
analogRead() always gives 0 to 1023, whatever the sensor.In this session