Using analog joystick boards to control components of electronic circuits
To control robots, or some electronic values we often need some potentiometers. One potentiometer is just one value. To make things easier for controlling multiple parameters at once joystick were invented. Nowadays you can get cheap "analog" joystick for your microcontroller that allows you to control signal from two axis - X and Y. That can be used for example to control where and how fast a robot-car is going. Such joystick has two potentiometers moving in perpendicular axis.
In this article I'll cover the basic 5-pin joystick boards. There are also Arduino shields or more advanced joystick boards that may have more pins and more features.
The board will have 5 pins: GND (-), VCC (+), one for X axis, one for Y axis, and one for button hidden on the side of the joystick mechanics. Depending on model the order may differ and the labels may be also different. If there is a manual for your board it's good to check it. I have two boards, and one has GNC, +5V, VRx, VRy, SW while the other +, X, R, Y, G (where G is GND and R is for the button).
X, Y pins need to be connected to analog pins, while button pin to a digital pin.
Potentiometers of the X and Y axis will give a value depending on the resistance they are current set to. It will change when we move the joystick knob. The button can be pressed when pressing the joystick knob. The digital pin must be set to high and when the button will be pressed it will fall to low state.Here is an example code for pyMCU that will read all the values:
from time import sleep import pymcu BUTTON_DIGITAL_PIN = 1 X_AXIS_ANALOG_PIN = 1 Y_AXIS_ANALOG_PIN = 2 mb = pymcu.mcuModule() mb.digitalState(BUTTON_DIGITAL_PIN, 'input') mb.pinHigh(BUTTON_DIGITAL_PIN) while True: print mb.analogRead(X_AXIS_ANALOG_PIN), mb.analogRead(Y_AXIS_ANALOG_PIN) if not mb.digitalRead(BUTTON_DIGITAL_PIN): print 'button pressed' sleep(0.1)
At start we have to set the digital pin to works as input, and set it to hight state. After that we can just loop and read the values.
When the joystick is in the start position both axis should give some intermediate value (in my case it was 498, 491 and 507, 517). When the knob is moved the values should change. In case of my pyMCU circuit the value could anywhere from 1 to a bit above 1000 (although only for one of the boards). You will have to check the start values of your board (and add +/- few points for stability) as well as max values. Having that you will be able to map that range correctly to values of motor, servo etc. that will be controlled by the joystick.