Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //If you found my video helpful, please SUBSCRIBE: https://www.youtube.com/c/CuriousScientist?sub_confirmation=1
- //The code belongs to this tutorial video: https://youtu.be/Zjyif7TKC0A
- //Please visit https://curiousscientist.tech
- //16x2 LCD
- #include <LiquidCrystal_I2C.h>
- LiquidCrystal_I2C lcd(0x27, 16, 2);
- //Pins
- const byte Analog_X_pin = A0; //x-axis readings
- const byte Analog_Y_pin = A1; //y-axis readings
- const byte Analog_Button_pin = 2; //attachinterrupt compatible pin
- //Variables
- int Analog_X = 0; //x-axis value
- int Analog_Y = 0; //y-axis value
- bool Analog_Button = false; //button status
- float timeNow; //timer for printing on the LCD
- void setup()
- {
- //SERIAL
- Serial.begin(115200);
- //-----------------
- //LCD
- lcd.begin();
- lcd.setCursor(0,0); //Defining positon to write from first row,first column .
- lcd.print("Analog joystick");
- lcd.setCursor(0,1);
- lcd.print("Demonstration"); //You can write 16 Characters per line .
- //
- delay(3000); //wait 3 sec
- PrintLCD();
- //----------------------------------------------------------------------------
- //PINS
- pinMode(Analog_X_pin, INPUT);
- pinMode(Analog_Y_pin, INPUT);
- pinMode(Analog_Button_pin, INPUT_PULLUP);
- attachInterrupt(digitalPinToInterrupt(Analog_Button_pin), ButtonPressed ,FALLING);
- //----------------------------------------------------------------------------
- timeNow = millis();
- }
- void loop()
- {
- ReadAnalog();
- if(millis() - timeNow > 200) //updating the LCD every 200 ms (this does not block the code!)
- {
- UpdateLCD();
- timeNow = millis(); //resetting timer
- }
- }
- void ReadAnalog()
- {
- Analog_X = analogRead(Analog_X_pin);
- delay(10); //allowing a little time between two readings
- Analog_Y = analogRead(Analog_Y_pin);
- }
- void PrintLCD()
- {
- //printing on the LCD
- lcd.clear();
- lcd.setCursor(0,0);
- lcd.print("X-axis: ");
- lcd.setCursor(8,0);
- lcd.print(Analog_X); //Print the value
- //
- lcd.setCursor(0,1);
- lcd.print("Y-axis: ");
- lcd.setCursor(8,1);
- lcd.print(Analog_Y); //Print the value
- }
- void UpdateLCD()
- {
- //We only update the values that are changing
- lcd.setCursor(8,0);
- lcd.print(" ");
- lcd.setCursor(8,0);
- lcd.print(Analog_X); //Print the value
- //Turn off serial if you do not use it with the PC
- Serial.print("X: ");
- Serial.println(Analog_X);
- //
- lcd.setCursor(8,1);
- lcd.print(" ");
- lcd.setCursor(8,1);
- lcd.print(Analog_Y); //Print the value
- //Turn off serial if you do not use it with the PC
- Serial.print("Y: ");
- Serial.println(Analog_Y);
- if(Analog_Button == true)
- {
- lcd.setCursor(15,1);
- lcd.print("1");
- Serial.println("Button pressed");
- Analog_Button = false; //reset button's status
- }
- else
- {
- lcd.setCursor(15,1);
- lcd.print("0");
- }
- }
- void ButtonPressed()
- {
- Analog_Button = true; //flip the variable
- }
Add Comment
Please, Sign In to add comment