Removed some magic numbers

This commit is contained in:
2026-03-11 14:23:31 -04:00
parent feaed67e8f
commit e579eb136f
+27 -16
View File
@@ -3,19 +3,25 @@
#include <LiquidCrystal_I2C.h>
#include <cstdint>
// Initialize Encoder Variables
static constexpr uint8_t ENCODER_PIN_A{2};
static constexpr uint8_t ENCODER_PIN_B{3};
// LCD Address is 0x27
LiquidCrystal_I2C lcd(0x27, 16, 2);
Encoder encoder(ENCODER_PIN_A, ENCODER_PIN_B);
unsigned long encoder_timer = 0;
uint32_t encoder_timer = 0;
float encoder_old = 0;
float frequency = 0;
static constexpr uint32_t onTime{100};
uint32_t timer;
// Initialize LCD Variables
static constexpr uint8_t I2C_LCD_ADDRESS{0x27};
static constexpr uint8_t LCD_COLUMNS{16};
static constexpr uint8_t LCD_ROWS{16};
LiquidCrystal_I2C lcd(I2C_LCD_ADDRESS, LCD_COLUMNS, LCD_ROWS);
// Initialize LED Variables
static constexpr uint8_t LED_PIN{5};
static constexpr uint32_t ON_TIME{100};
uint32_t led_timer;
/**
* @brief Update a display with the frequency and RPM information
@@ -32,14 +38,19 @@ void UpdateDisplay(LiquidCrystal_I2C &display, float new_frequency) {
display.print(new_frequency * 60);
}
inline void SetPin5() { PORTD = PORTD | 0b00100000; }
template <uint8_t pinNumber> inline void SetPin5() {
PORTD |= (1U << pinNumber);
}
inline void ClearPin5() { PORTD = PORTD & 0b11011111; }
template <uint8_t pinNumber> inline void ClearPin5() {
PORTD &= (0xFF - (1U << pinNumber));
}
float UpdateFrequency(Encoder &encoder, float oldFrequency, float &encoderOld) {
float UpdateFrequency(Encoder &encoder, uint32_t &encoderTimer,
float oldFrequency, float &encoderOld) {
float newFrequency = oldFrequency;
float encoderNew = float(encoder.read()) / 8;
if (encoderNew != encoderOld && millis() - encoder_timer > 100) {
if (encoderNew != encoderOld && millis() - encoderTimer > 100) {
float difference = encoderNew - encoderOld;
newFrequency = oldFrequency + pow(difference, 3);
@@ -52,7 +63,7 @@ float UpdateFrequency(Encoder &encoder, float oldFrequency, float &encoderOld) {
}
UpdateDisplay(lcd, newFrequency);
encoder_timer = millis();
encoderTimer = millis();
}
return newFrequency;
}
@@ -84,11 +95,11 @@ void Flash(bool &isOn, uint32_t &timer, float frequency, uint32_t onTime) {
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(5, OUTPUT);
pinMode(LED_PIN, OUTPUT);
// Turn off pin 5
SetPin5();
encoder_old = encoder.read();
timer = micros();
led_timer = micros();
encoder_timer = millis();
lcd.init();
@@ -99,8 +110,8 @@ void setup() {
void loop() {
// Get the new frequency from the encoder
frequency = UpdateFrequency(encoder, frequency, encoder_old);
frequency = UpdateFrequency(encoder, encoder_timer, frequency, encoder_old);
// Turn on or off the LED at the right time
Flash(frequency, timer, onTime);
Flash(frequency, led_timer, ON_TIME);
}