#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/adc.h"
#include "hardware/timer.h"
// Definir os pinos ADC para os eixos do joystick
#define JOYSTICK_X_PIN 26 // ADC0
#define JOYSTICK_Y_PIN 27 // ADC1
volatile uint16_t joystick_x = 0;
volatile uint16_t joystick_y = 0;
// Função ISR chamada pelo temporizador
bool read_joystick(struct repeating_timer *t) {
// Ler o valor do eixo X
adc_select_input(0); // Selecionar ADC0
joystick_x = adc_read();
// Ler o valor do eixo Y
adc_select_input(1); // Selecionar ADC1
joystick_y = adc_read();
// Converter os valores para tensão e exibir no console
float voltage_x = (joystick_x / 4095.0) * 3.3; // Conversão para tensão (3.3V referência)
float voltage_y = (joystick_y / 4095.0) * 3.3;
// Determinar a direção com base nos valores
printf("Eixo X: %.2f V ", voltage_x);
printf("Eixo Y: %.2f V ", voltage_y);
if (voltage_x < 1.0) {
printf("-> Direita\n");
} else if (voltage_x > 2.3) {
printf("-> Esquerda\n");
} else if (voltage_y < 1.0) {
printf("-> Baixo\n");
} else if (voltage_y > 2.3) {
printf("-> Cima\n");
} else {
printf("-> Centro\n");
}
return true; // Retornar true para repetir o timer
}
int main() {
stdio_init_all(); // Inicializar comunicação serial
sleep_ms(1000); // Tempo para estabilizar a comunicação serial
printf("Monitorando o joystick...\n");
// Inicializar o ADC
adc_init();
adc_gpio_init(JOYSTICK_X_PIN); // Configurar GPIO26 como entrada ADC
adc_gpio_init(JOYSTICK_Y_PIN); // Configurar GPIO27 como entrada ADC
// Criar um timer periódico para leitura do joystick
struct repeating_timer timer;
add_repeating_timer_ms(500, read_joystick, NULL, &timer);
// Loop principal vazio (ISR gerencia as leituras)
while (true) {
tight_loop_contents(); // Economiza energia enquanto espera
}
}