The Circuit:
The Code:
1 /********************************************************************** 2 * Filename : Joystick.cpp 3 * Description : Read Joystick 4 * Author : www.freenove.com 5 * modification: 2020/03/09 6 **********************************************************************/ 7 #include <wiringPi.h> 8 #include <stdio.h> 9 #include <softPwm.h> 10 #include <ADCDevice.hpp> 11 12 #define Z_Pin 1 // Define pin for axis Z 13 14 ADCDevice *adc; // Define an ADC Device class object 15 16 int main(void){ 17 adc = new ADCDevice(); // Varaible for what hardware we are using 18 int val_z; // Variable for Z axis 19 int val_Y; // Variable for Y axis 20 int val_X; // Variable for X axis 21 printf("Program is starting ... \n"); 22 23 if(adc->detectI2C(0x48)){ // Are we using the pcf8591. 24 delete adc; // Reset adc 25 adc = new PCF8591(); // Set adc to hardware 26 } 27 else if(adc->detectI2C(0x4b)){ // Are we using the ads7830 28 delete adc; // Reset adc 29 adc = new ADS7830(); // Set adc to hardware 30 } 31 else{ 32 printf("No correct I2C address found, \n" 33 "Please use command 'i2cdetect -y 1' to check the I2C address! \n" 34 "Program Exit. \n"); 35 return -1; 36 } 37 wiringPiSetup(); 38 pinMode(Z_Pin,INPUT); // Set Z_Pin as input pin and pull-up mode 39 pullUpDnControl(Z_Pin,PUD_UP); 40 while(1){ 41 val_Z = digitalRead(Z_Pin); // Read digital value of axis Z 42 val_Y = adc->analogRead(0); // Read analog value of Y axis 43 val_X = adc->analogRead(1); // Read analog value of X axis 44 printf("val_X: %d ,\tval_Y: %d ,\tval_Z: %d \n",val_X,val_Y,val_Z); 45 delay(100); 46 } 47 return 0; 48 }
This project requires you set up the board with an ADC device, either the PCF8591 or the ADS7830, just like the previous projects of: Softlight, Nightlamp, and Thermometer. Then you have to hook up the joystick to the board which requires 5 male to female jumpers since the joystick has pins on it and one more 10kohm resistor. After setting it up and running the program we are given readings on the joystick's direction which can change when you push the joystick in any direction. Now that will change the x and y directional values, but we are also reading a z value which changes if you press the button. As for the code I aligned the comments, made the conditional comments to not rely on the hardware jargon to much, and I moved the declaration of the variables to be outside of the while loop.