#include <LiquidCrystal.h>
#include <Servo.h>
// Pin Definitions
#define JOY_X PA0 // X-axis (Analog)
#define JOY_Y PA1 // Y-axis (Analog)
#define JOY_SW PA2 // Joystick Button (Digital Input Pull-down)
#define LED_PIN PC13 // Built-in LED
#define SERVO_PIN PB6 // Proper PWM-capable pin (TIM4_CH1)
#define LCD_RS PB10
#define LCD_EN PB11
#define LCD_D4 PB12
#define LCD_D5 PB13
#define LCD_D6 PB14
#define LCD_D7 PB15
// Objects
Servo myServo;
LiquidCrystal lcd(LCD_RS, LCD_EN, LCD_D4, LCD_D5, LCD_D6, LCD_D7);
// Variables
bool ledState = false;
bool lastButtonState = HIGH;
unsigned long lastDebounceTime = 0;
const unsigned long debounceDelay = 50;
void setup() {
// Initialize serial for debugging
Serial.begin(9600);
// Initialize pins
pinMode(JOY_SW, INPUT_PULLDOWN);
pinMode(LED_PIN, OUTPUT);
// Initialize servo (using proper PWM pin)
myServo.attach(SERVO_PIN);
myServo.write(90); // Center position
// Initialize LCD
lcd.begin(16, 2);
lcd.print("System Ready");
delay(1000);
lcd.clear();
}
void loop() {
// Read inputs
int xVal = analogRead(JOY_X);
int yVal = analogRead(JOY_Y);
bool buttonState = digitalRead(JOY_SW);
// Map joystick X to servo angle (0-180°)
int angle = map(xVal, 0, 4095, 0, 180);
myServo.write(angle); // Direct position setting
// Button debounce and LED toggle
if (buttonState != lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (buttonState == HIGH && lastButtonState == LOW) {
ledState = !ledState;
digitalWrite(LED_PIN, ledState);
}
}
lastButtonState = buttonState;
// Update LCD display (optimized to minimize flicker)
static unsigned long lastUpdate = 0;
if (millis() - lastUpdate > 200) { // Update every 200ms
lcd.setCursor(0, 0);
lcd.print("X:");
lcd.print(xVal);
lcd.print(" Y:");
lcd.print(yVal);
lcd.print(" "); // Clear remaining characters
lcd.setCursor(0, 1);
lcd.print("S:");
lcd.print(angle);
lcd.print((char)223); // Degree symbol
lcd.print(" L:");
lcd.print(ledState ? "ON " : "OFF");
lcd.print(" ");
lastUpdate = millis();
}
delay(10); // Small delay for stability
}Loading
stm32-bluepill
stm32-bluepill