get touch buttons working (maybe)

This commit is contained in:
true 2024-08-03 11:43:18 -07:00
parent bc7a378dcd
commit c060bcc236
2 changed files with 22 additions and 16 deletions

View File

@ -21,20 +21,24 @@ uint16_t touch_read_adc(u8 adc_ch)
TBTN_ADC->IDATAR1 = 0x10; // charging time TBTN_ADC->IDATAR1 = 0x10; // charging time
TBTN_ADC->RDATAR = 0x08; // discharging time TBTN_ADC->RDATAR = 0x08; // discharging time
ADC_SoftwareStartConvCmd(TBTN_ADC, ENABLE);
while(!ADC_GetFlagStatus(TBTN_ADC, ADC_FLAG_EOC)); while(!ADC_GetFlagStatus(TBTN_ADC, ADC_FLAG_EOC));
return (uint16_t)TBTN_ADC->RDATAR; return (uint16_t)TBTN_ADC->RDATAR;
} }
uint16_t touch_read(u8 btn_ch) uint16_t touch_read(u8 btn_ch)
{ {
if (btn_ch < 2) return touch_read_adc(tbtn_adc_ch[btn_ch]); if (btn_ch < TBTN_COUNT) return touch_read_adc(tbtn_adc_ch[btn_ch]);
else return 0xffff; else return 0xffff;
} }
uint8_t touch_read_pushed(uint8_t btn_ch) uint8_t touch_read_pushed(uint8_t btn_ch)
{ {
if (touch_read_adc(tbtn_adc_ch[btn_ch]) < tbtn_idle_cal[btn_ch] - TBTN_PUSHED_COUNTS) if (btn_ch > 1) return 0;
if (touch_read_adc(tbtn_adc_ch[btn_ch]) < tbtn_idle_cal[btn_ch] - TBTN_PUSHED_COUNTS) {
return 1; return 1;
}
return 0; return 0;
} }
@ -42,24 +46,26 @@ uint8_t touch_read_pushed(uint8_t btn_ch)
void touch_cal() void touch_cal()
{ {
uint8_t i, j; uint8_t i, j;
uint16_t val; uint32_t val;
for (i = 0; i < 2; i++) { for (i = 0; i < TBTN_COUNT; i++) {
val = 0xffff; // do a dummy read
while (val > TBTN_IDLE_WINDOW_HI) { touch_read(tbtn_adc_ch[i]);
// be warned,
// we can hang here until the buttons can be calibrated // hang until the button appears to be idle
val = 0;
while (val < TBTN_IDLE_LOW_VAL) {
val = touch_read(tbtn_adc_ch[i]); val = touch_read(tbtn_adc_ch[i]);
} }
// get average of 8 readings // get average of 4 readings and store as calibration value
val = 0; val = 0;
for (j = 0; j < 8; j++) { for (j = 0; j < 4; j++) {
val += touch_read(tbtn_adc_ch[i]); val += touch_read(tbtn_adc_ch[i]);
} }
val >>= 3; val >>= 2;
tbtn_idle_cal[i] = val; tbtn_idle_cal[i] = val & 0xfff;
} }
} }

View File

@ -12,13 +12,13 @@
#define TBTN_ADC ADC2 #define TBTN_ADC ADC2
#define TBTN_COUNT 2
#define TBTN1 ADC_Channel_4 // right button #define TBTN1 ADC_Channel_4 // right button
#define TBTN2 ADC_Channel_9 // left button #define TBTN2 ADC_Channel_9 // left button
#define TBTN_IDLE_WINDOW_LO 300 #define TBTN_IDLE_LOW_VAL 0xfd0 // values above this == not touched. used to calibrate
#define TBTN_IDLE_WINDOW_HI 500 #define TBTN_PUSHED_COUNTS 0x37f // counts must drop below tbtn_idle_cal-TBTN_THRESHOLD to be considered a press
#define TBTN_PUSHED_COUNTS 100
#define ADC_CTLR1_TKENABLE (1 << 24) #define ADC_CTLR1_TKENABLE (1 << 24)