From 0971859f463761c2845716ee08441184013fc429 Mon Sep 17 00:00:00 2001 From: Savanni D'Gerinel Date: Wed, 12 Jul 2023 22:32:53 -0400 Subject: [PATCH] Add calibration code --- touch-sensor/main.c | 47 +++++++++++++++++++++++++++++++++++++-------- 1 file changed, 39 insertions(+), 8 deletions(-) diff --git a/touch-sensor/main.c b/touch-sensor/main.c index 4a141ef..89f2e60 100644 --- a/touch-sensor/main.c +++ b/touch-sensor/main.c @@ -14,6 +14,18 @@ uint32_t read_capacitance(dio_t *dio) { return i; } +uint32_t calibrate(dio_t *dio) { + uint32_t max = 0; + + for (uint8_t i = 0; i < 100; i++) { + uint8_t cap = read_capacitance(dio); + max = cap > max ? cap : max; + _delay_ms(10); + } + + return max; +} + int main(void) { dio_t sensor = (dio_t){ .ddr = &DDRB, .port = &PORTB, .pin = &PINB, .addr = 0 }; display_t display = { @@ -28,10 +40,6 @@ int main(void) { display_enable(&display); display_clear(&display); - display_set_location(&display, 0, 0); - display_write_message(&display, "Ready"); - - // calibration // // 100 times: @@ -51,12 +59,35 @@ int main(void) { MCUCR |= _BV(PUD); + uint8_t calibration_countdown = 0; + uint32_t calibration = 0; + bool touch = false; while (1) { + if (calibration_countdown == 0 && !touch) { + calibration = calibrate(&sensor); + calibration_countdown = 100; + + char msg[20]; + snprintf(msg, 20, "calib: %6ld", calibration); + display_set_location(&display, 0, 0); + display_write_message(&display, msg); + } + uint32_t cap = read_capacitance(&sensor); - char msg[20]; - snprintf(msg, 20, "cap: %5ld", cap); - display_set_location(&display, 1, 0); - display_write_message(&display, msg); + + if (cap > calibration) { + display_set_location(&display, 1, 0); + display_write_message(&display, "touch!"); + touch = true; + } else if (touch) { + display_set_location(&display, 1, 0); + display_write_message(&display, " "); + touch = false; + } + + if (calibration_countdown > 0) { + calibration_countdown--; + } _delay_ms(100); }