avr/touch-sensor/main.c

64 lines
1.6 KiB
C

#include <dio.h>
#include <stdio.h>
#include <display.h>
uint32_t read_capacitance(dio_t *dio) {
uint32_t i;
dio_set_direction(dio, LINE_OUT);
dio_set(dio, 1);
i = 0;
dio_set_direction(dio, LINE_IN);
while (dio_read(dio) > 0) i++;
return i;
}
int main(void) {
dio_t sensor = (dio_t){ .ddr = &DDRB, .port = &PORTB, .pin = &PINB, .addr = 0 };
display_t display = {
.reg = {
.output = { .ddr = &DDRB, .port = &PORTB, .pin = &PINB, .addr = 4 },
.shift_clock = { .ddr = &DDRB, .port = &PORTB, .pin = &PINB, .addr = 3 },
.latch_clock = { .ddr = &DDRB, .port = &PORTB, .pin = &PINB, .addr = 2 },
},
};
display_init(&display);
display_enable(&display);
display_clear(&display);
display_set_location(&display, 0, 0);
display_write_message(&display, "Ready");
// calibration
//
// 100 times:
// Output 1
// Switch to Input
// measure in a loop until the input is 0
// save the measurement
//
// normal function
// Output 1
// Switch to input
// measure in a loop until the input is 0
// check against the saved measurement
// enable pin if significantly higher than the saved measurement
// update the average
MCUCR |= _BV(PUD);
while (1) {
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);
_delay_ms(100);
}
}