#include <stdio.h>
#include "pico/stdlib.h"
#include "pico/cyw43_arch.h"
#define ROWS 4
#define COLS 4
#define LENGTH(arr) (sizeof(arr) / sizeof(arr[0]))
// Definição de pinos do teclado matricial e dos LEDs RGB
const uint8_t row_pins[ROWS] = {8 , 7, 6, 5};
const uint8_t col_pins[COLS] = {4 , 3, 2, 1};
const uint8_t targetLedPins[3] = {28, 27, 26}; // Pinos para R, G, B do LED RGB
// Máscaras de cor para LEDs RGB
const uint8_t red_mask = 0b001;
const uint8_t green_mask = 0b010;
const uint8_t blue_mask = 0b100;
const uint8_t black_mask = 0b000;
// Função para controlar LED RGB
void write_rgb_led(uint8_t mask) {
for (int pin = 0; pin < LENGTH(targetLedPins); pin++) {
gpio_put(targetLedPins[pin], (bool)(mask >> pin & 1));
}
}
// Mapa de teclas do teclado matricial
const char key_map[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
// Inicialização do teclado matricial
void keypad_init() {
for (int i = 0; i < ROWS; i++) {
gpio_init(row_pins[i]);
gpio_set_dir(row_pins[i], GPIO_OUT);
gpio_put(row_pins[i], 0);
}
for (int i = 0; i < COLS; i++) {
gpio_init(col_pins[i]);
gpio_set_dir(col_pins[i], GPIO_IN);
}
}
// Função para ler a tecla pressionada no teclado matricial
char read_keypad() {
for (int row = 0; row < ROWS; row++) {
gpio_put(row_pins[row], 1);
for (int col = 0; col < COLS; col++) {
if (gpio_get(col_pins[col])) {
gpio_put(row_pins[row], 0);
return key_map[row][col];
}
}
gpio_put(row_pins[row], 0);
}
return '\0';
}
// Macros para criação de funções que acendem LED RGB conforme teclas
#define HANDLER(color, key1, key2, key3, key4) \
void color##_Handler(char key) { \
switch (key) { \
case key1: \
case key2: \
case key3: \
case key4: \
write_rgb_led(color##_mask); \
break; \
default: \
return; \
} \
}
HANDLER(red, '1', '4', '7', '*')
HANDLER(green, '2', '5', '8', '0')
HANDLER(blue, '3', '6', '9', '#')
HANDLER(black, 'A', 'B', 'C', 'D')
int main() {
stdio_init_all();
keypad_init();
for (int ii = 0; ii < LENGTH(targetLedPins); ii++) {
gpio_init(targetLedPins[ii]);
gpio_set_dir(targetLedPins[ii], GPIO_OUT);
}
printf("Pressione uma tecla!\n");
while (true) {
char key = read_keypad();
if (key != '\0') {
printf("Tecla pressionada: %c\n", key);
red_Handler(key);
green_Handler(key);
blue_Handler(key);
black_Handler(key);
}
sleep_ms(200);
}
return 0;
}