Created
December 5, 2022 19:48
-
-
Save LucasPlacentino/30e2dec3ebec9a0e75c282ce6192408c to your computer and use it in GitHub Desktop.
Key matrix scanning V4 (with rotary encoder for volume)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Import the HID library and the Raspberry Pi Pico crate | |
extern crate hid; | |
extern crate rppal; | |
// Use the RPi Pico crate to access the Pico's hardware | |
use rppal::gpio::Gpio; | |
use rppal::gpio::InputPin; | |
use rppal::gpio::OutputPin; | |
use rppal::gpio::Level; | |
use rppal::gpio::Interrupt; | |
// Define the number of rows and columns in the key matrix | |
const ROW_COUNT: usize = 4; | |
const COLUMN_COUNT: usize = 4; | |
// Define the pins that will be used for the rotary encoder | |
const ENCODER_A_PIN: u8 = 24; | |
const ENCODER_B_PIN: u8 = 25; | |
// Define the thresholds for the volume control | |
const VOLUME_UP_THRESHOLD: u8 = 128; | |
const VOLUME_DOWN_THRESHOLD: u8 = 128; | |
// Define a struct to represent the state of the keyboard's key matrix | |
struct KeyMatrix { | |
rows: [bool; ROW_COUNT], | |
columns: [bool; COLUMN_COUNT], | |
row_pins: [InputPin; ROW_COUNT], | |
column_pins: [OutputPin; COLUMN_COUNT], | |
} | |
impl KeyMatrix { | |
// Define a function that can read the state of the key matrix | |
fn read(&mut self) { | |
// Set all of the column output pins to low | |
for column_pin in self.column_pins.iter_mut() { | |
column_pin.set_low(); | |
} | |
// Iterate over the rows of the matrix | |
for (i, row) in self.rows.iter_mut().enumerate() { | |
// Set the value of each row to the state of the corresponding input pin | |
*row = self.row_pins[i].is_high(); | |
} | |
// Iterate over the columns of the matrix | |
for (i, column) in self.columns.iter_mut().enumerate() { | |
// Set the value of the column output pin to high | |
self.column_pins[i].set_high(); | |
// Set the value of each column to the state of the corresponding row input pin | |
*column = self.row_pins[i].is_high(); | |
} | |
} | |
} | |
// Define a function that can read the state of the rotary encoder | |
fn read_encoder(encoder_a: &InputPin, encoder_b: &InputPin) -> (Level, Level) { | |
// Read the state of the encoder A and B pins | |
let encoder_a_level = encoder_a.read(); | |
let encoder_b_level = encoder_b.read(); | |
// Return the encoder pin states as a tuple | |
(encoder_a_level, encoder_b_level) | |
} | |
// Define a function that can handle rotary encoder |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment