// programa ejemplo Joystick + servo
// Define Joystick pins for the x and y axis and the button pins
#define pin_xAxis 34
#define pin_yAxis 35
#define pin_btn 33
double frecuencia=50; // señal de 50 Hz
const int periodo_ms=1000/frecuencia; // 20 mseg
const uint8_t channel_0 = 0; // canal HW para controlar el servo
const uint8_t resolucion = 16; // variacion del PWM - 2^16 "pasos"
const uint8_t pin_PWM_0 = 14; // pin a conectar la señal del servo
const int LED_pin = 27;
void setup() {
pinMode(LED_pin, OUTPUT);
// Mode Joystick button pin to input
pinMode(pin_btn, INPUT);
// Initialize serial communication at 115200 bits per second:
Serial.begin(115200);
ledcSetup( channel_0, frecuencia, resolucion);
ledcAttachPin( pin_PWM_0, channel_0);
delay(1000);
}
void posicion_servo(float angulo){
// ecuacion recta tiempos 0.5 a 2.4 para 0 - 180 grados
float ton = 0.5 + 1.9*angulo/180.0;
uint32_t duty_0=((ton/periodo_ms)*((1<<resolucion)-1)); // valor de 0 a 2^16-1
ledcWrite(channel_0, duty_0);
Serial.printf("ang: %3.0f - t_on: %2.2f\n", angulo, ton);
}
void loop() {
static int val_led = LOW;
val_led = val_led?LOW:HIGH;
digitalWrite(LED_pin, val_led);
// Read the analog value for x,y axis
int xValue = analogRead(pin_xAxis);
int yValue = analogRead(pin_yAxis);
// Read the digital value from the button pin
int btnValue = digitalRead(pin_btn);
// el servo se pone a un valor en grados 0 - 180 en funcion de 0 - 4096
posicion_servo(xValue*180/4096);
// print out the values
Serial.printf("Joystick value is %d , %d , %d \n",xValue,yValue,btnValue);
delay(300); // Delay between reads
}