Kiibohd Controller
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

scan_loop.c 25KB

10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
10 vuotta sitten
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  1. /* Copyright (C) 2011-2013 by Joseph Makuch
  2. * Additions by Jacob Alexander (2013-2014)
  3. *
  4. * This library is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 3.0 of the License, or (at your option) any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public
  15. * License along with this library. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. // ----- Includes -----
  18. // Compiler Includes
  19. #include <Lib/ScanLib.h>
  20. // Project Includes
  21. #include <cli.h>
  22. #include <led.h>
  23. #include <macro.h>
  24. #include <print.h>
  25. // Local Includes
  26. #include "scan_loop.h"
  27. // ----- Defines -----
  28. // TODO dfj defines...needs commenting and maybe some cleaning...
  29. #define MAX_PRESS_DELTA_MV 450 // As measured from the Teensy ADC pin
  30. #define THRESHOLD_MV (MAX_PRESS_DELTA_MV >> 1)
  31. //(2560 / (0x3ff/2)) ~= 5
  32. #define MV_PER_ADC 5
  33. #define THRESHOLD (THRESHOLD_MV / MV_PER_ADC)
  34. #define STROBE_SETTLE 1
  35. #define ADHSM 7
  36. // Right justification of ADLAR
  37. #define ADLAR_BITS 0
  38. // full muxmask
  39. #define FULL_MUX_MASK ((1 << MUX0) | (1 << MUX1) | (1 << MUX2) | (1 << MUX3) | (1 << MUX4))
  40. // F0-f7 pins only muxmask.
  41. #define MUX_MASK ((1 << MUX0) | (1 << MUX1) | (1 << MUX2))
  42. // Strobe Masks
  43. #define D_MASK (0xff)
  44. #define E_MASK (0x03)
  45. #define C_MASK (0xff)
  46. // set ADC clock prescale
  47. #define PRESCALE_MASK ((1 << ADPS0) | (1 << ADPS1) | (1 << ADPS2))
  48. #define PRESCALE_SHIFT (ADPS0)
  49. #define PRESCALE 3
  50. // Max number of strobes supported by the hardware
  51. // Strobe lines are detected at startup, extra strobes cause anomalies like phantom keypresses
  52. #define MAX_STROBES 18
  53. // Number of consecutive samples required to pass debounce
  54. #define DEBOUNCE_THRESHOLD 5
  55. // Scans to remain idle after all keys were release before starting averaging
  56. // XXX So this makes the initial keypresses fast,
  57. // but it's still possible to lose a keypress if you press at the wrong time -HaaTa
  58. #define KEY_IDLE_SCANS 30000
  59. // Total number of muxes/sense lines available
  60. #define MUXES_COUNT 8
  61. #define MUXES_COUNT_XSHIFT 3
  62. // Number of warm-up loops before starting to scan keys
  63. #define WARMUP_LOOPS ( 1024 )
  64. #define WARMUP_STOP (WARMUP_LOOPS - 1)
  65. #define SAMPLE_CONTROL 3
  66. #define KEY_COUNT ((MAX_STROBES) * (MUXES_COUNT))
  67. #define RECOVERY_CONTROL 1
  68. #define RECOVERY_SOURCE 0
  69. #define RECOVERY_SINK 2
  70. #define ON 1
  71. #define OFF 0
  72. // mix in 1/4 of the current average to the running average. -> (@mux_mix = 2)
  73. #define MUX_MIX 2
  74. #define IDLE_COUNT_SHIFT 8
  75. // av = (av << shift) - av + sample; av >>= shift
  76. // e.g. 1 -> (av + sample) / 2 simple average of new and old
  77. // 2 -> (3 * av + sample) / 4 i.e. 3:1 mix of old to new.
  78. // 3 -> (7 * av + sample) / 8 i.e. 7:1 mix of old to new.
  79. #define KEYS_AVERAGES_MIX_SHIFT 3
  80. // ----- Macros -----
  81. // Select mux
  82. #define SET_FULL_MUX(X) ((ADMUX) = (((ADMUX) & ~(FULL_MUX_MASK)) | ((X) & (FULL_MUX_MASK))))
  83. // ----- Function Declarations -----
  84. // CLI Functions
  85. void cliFunc_avgDebug ( char* args );
  86. void cliFunc_echo ( char* args );
  87. void cliFunc_keyDebug ( char* args );
  88. void cliFunc_pressDebug ( char* args );
  89. void cliFunc_problemKeys( char* args );
  90. void cliFunc_senseDebug ( char* args );
  91. // Debug Functions
  92. void dumpSenseTable();
  93. // High-level Capsense Functions
  94. void setup_ADC();
  95. void capsense_scan();
  96. // Capsense Sense Functions
  97. void testColumn ( uint8_t strobe );
  98. void sampleColumn( uint8_t column );
  99. // Low-level Capsense Functions
  100. void strobe_w( uint8_t strobe_num );
  101. void recovery( uint8_t on );
  102. // ----- Variables -----
  103. // Buffer used to inform the macro processing module which keys have been detected as pressed
  104. volatile uint8_t KeyIndex_Buffer[KEYBOARD_BUFFER];
  105. volatile uint8_t KeyIndex_BufferUsed;
  106. // Scan Module command dictionary
  107. const char scanCLIDictName[] = "DPH Module Commands";
  108. const CLIDictItem scanCLIDict[] = {
  109. { "echo", "Example command, echos the arguments.", cliFunc_echo },
  110. { "avgDebug", "Enables/Disables averaging results." NL "\t\tDisplays each average, starting from Key 0x00, ignoring 0 valued averages.", cliFunc_avgDebug },
  111. { "keyDebug", "Enables/Disables long debug for each keypress." NL "\t\tkeycode - [strobe:mux] : sense val : threshold+delta=total : margin", cliFunc_keyDebug },
  112. { "pressDebug", "Enables/Disables short debug for each keypress.", cliFunc_pressDebug },
  113. { "problemKeys", "Display current list of problem keys,", cliFunc_problemKeys },
  114. { "senseDebug", "Prints out the current sense table N times." NL "\t\tsense:max sense:delta", cliFunc_senseDebug },
  115. { 0, 0, 0 } // Null entry for dictionary end
  116. };
  117. // CLI Control Variables
  118. uint8_t enableAvgDebug = 0;
  119. uint8_t enableKeyDebug = 0;
  120. uint8_t enablePressDebug = 1;
  121. uint8_t senseDebugCount = 3; // In order to get boot-time oddities
  122. // Variables used to calculate the starting sense value (averaging)
  123. uint32_t full_avg = 0;
  124. uint32_t high_avg = 0;
  125. uint32_t low_avg = 0;
  126. uint8_t high_count = 0;
  127. uint8_t low_count = 0;
  128. uint16_t samples[MAX_STROBES][MUXES_COUNT]; // Overall table of cap sense ADC values
  129. uint16_t sampleMax[MAX_STROBES][MUXES_COUNT]; // Records the max seen ADC value
  130. uint8_t key_activity = 0; // Increments for each detected key per each full scan of the keyboard, it is reset before each full scan
  131. uint16_t key_idle = 0; // Defines how scans after all keys were released before starting averaging again
  132. uint8_t key_release = 0; // Indicates if going from key press state to release state (some keys pressed to no keys pressed)
  133. uint16_t threshold = THRESHOLD;
  134. uint16_t keys_averages_acc[KEY_COUNT];
  135. uint16_t keys_averages [KEY_COUNT];
  136. uint8_t keys_debounce [KEY_COUNT]; // Contains debounce statistics
  137. uint8_t keys_problem [KEY_COUNT]; // Marks keys that should be ignored (determined by averaging at startup)
  138. // TODO: change this to 'booting', then count down.
  139. uint16_t boot_count = 0;
  140. uint8_t total_strobes = MAX_STROBES;
  141. uint8_t strobe_map[MAX_STROBES];
  142. // ----- Functions -----
  143. // Initial setup for cap sense controller
  144. inline void Scan_setup()
  145. {
  146. // Register Scan CLI dictionary
  147. CLI_registerDictionary( scanCLIDict, scanCLIDictName );
  148. // Scan for active strobes
  149. // NOTE1: On IBM PCBs, each strobe line that is *NOT* used is connected to GND.
  150. // This means, the strobe GPIO can be set to Tri-State pull-up to detect which strobe lines are not used.
  151. // NOTE2: This will *NOT* detect floating strobes.
  152. // NOTE3: Rev 0.4, the strobe numbers are reversed, so D0 is actually strobe 0 and C7 is strobe 17
  153. info_msg("Detecting Strobes...");
  154. DDRC = 0;
  155. PORTC = C_MASK;
  156. DDRD = 0;
  157. PORTD = D_MASK;
  158. DDRE = 0;
  159. PORTE = E_MASK;
  160. // Initially there are 0 strobes
  161. total_strobes = 0;
  162. // Iterate over each the strobes
  163. for ( uint8_t strobe = 0; strobe < MAX_STROBES; strobe++ )
  164. {
  165. uint8_t detected = 0;
  166. // If PIN is high, then strobe is *NOT* connected to GND and may be a strobe
  167. switch ( strobe )
  168. {
  169. // Strobe Mappings
  170. // Rev Rev
  171. // 0.2 0.4
  172. #ifndef REV0_4_DEBUG // XXX These pins should be reworked, and connect to GND on Rev 0.4
  173. case 0: // D0 0 n/c
  174. case 1: // D1 1 n/c
  175. #endif
  176. case 2: // D2 2 15
  177. case 3: // D3 3 14
  178. case 4: // D4 4 13
  179. case 5: // D5 5 12
  180. case 6: // D6 6 11
  181. case 7: // D7 7 10
  182. detected = PIND & (1 << strobe);
  183. break;
  184. case 8: // E0 8 9
  185. case 9: // E1 9 8
  186. detected = PINE & (1 << (strobe - 8));
  187. break;
  188. case 10: // C0 10 7
  189. case 11: // C1 11 6
  190. case 12: // C2 12 5
  191. case 13: // C3 13 4
  192. case 14: // C4 14 3
  193. case 15: // C5 15 2
  194. #ifndef REV0_2_DEBUG // XXX If not using the 18 pin connector on Rev 0.2, rework these pins to GND
  195. case 16: // C6 16 1
  196. case 17: // C7 17 0
  197. #endif
  198. detected = PINC & (1 << (strobe - 10));
  199. break;
  200. default:
  201. break;
  202. }
  203. // Potential strobe line detected
  204. if ( detected )
  205. {
  206. strobe_map[total_strobes] = strobe;
  207. total_strobes++;
  208. }
  209. }
  210. printInt8( total_strobes );
  211. print( " strobes found." NL );
  212. // Setup Pins for Strobing
  213. DDRC = C_MASK;
  214. PORTC = 0;
  215. DDRD = D_MASK;
  216. PORTD = 0;
  217. DDRE = E_MASK;
  218. PORTE = 0 ;
  219. // Initialize ADC
  220. setup_ADC();
  221. // Reset debounce table
  222. for ( int i = 0; i < KEY_COUNT; ++i )
  223. {
  224. keys_debounce[i] = 0;
  225. }
  226. // Warm things up a bit before we start collecting data, taking real samples.
  227. for ( uint8_t i = 0; i < total_strobes; ++i )
  228. {
  229. sampleColumn( strobe_map[i] );
  230. }
  231. }
  232. // Main Detection Loop
  233. // This is where the important stuff happens
  234. inline uint8_t Scan_loop()
  235. {
  236. capsense_scan();
  237. // Return non-zero if macro and USB processing should be delayed
  238. // Macro processing will always run if returning 0
  239. // USB processing only happens once the USB send timer expires, if it has not, Scan_loop will be called
  240. // after the macro processing has been completed
  241. return 0;
  242. }
  243. // Signal KeyIndex_Buffer that it has been properly read
  244. // NOTE: Only really required for implementing "tricks" in converters for odd protocols
  245. void Scan_finishedWithBuffer( uint8_t sentKeys )
  246. {
  247. return;
  248. }
  249. // Signal KeyIndex_Buffer that it has been properly read and sent out by the USB module
  250. // NOTE: Only really required for implementing "tricks" in converters for odd protocols
  251. void Scan_finishedWithUSBBuffer( uint8_t sentKeys )
  252. {
  253. return;
  254. }
  255. inline void capsense_scan()
  256. {
  257. // Accumulated average used for the next scan
  258. uint32_t cur_full_avg = 0;
  259. uint32_t cur_high_avg = 0;
  260. // Reset average counters
  261. low_avg = 0;
  262. low_count = 0;
  263. high_count = 0;
  264. // Reset key activity, if there is no key activity, averages will accumulate for sense deltas, otherwise they will be reset
  265. key_activity = 0;
  266. // Scan each of the mapped strobes in the matrix
  267. for ( uint8_t strober = 0; strober < total_strobes; ++strober )
  268. {
  269. uint8_t map_strobe = strobe_map[strober];
  270. // Sample the ADCs for the given column/strobe
  271. sampleColumn( map_strobe );
  272. // Only process sense data if warmup is finished
  273. if ( boot_count >= WARMUP_LOOPS )
  274. {
  275. testColumn( map_strobe );
  276. }
  277. uint8_t strobe_line = map_strobe << MUXES_COUNT_XSHIFT;
  278. for ( int mux = 0; mux < MUXES_COUNT; ++mux )
  279. {
  280. // discard sketchy low bit, and meaningless high bits.
  281. uint8_t sample = samples[map_strobe][mux] >> 1;
  282. keys_averages_acc[strobe_line + mux] += sample;
  283. }
  284. // Accumulate 3 total averages (used for determining starting average during warmup)
  285. // full_avg - Average of all sampled lines on the previous scan set
  286. // cur_full_avg - Average of all sampled lines for this scan set
  287. // high_avg - Average of all sampled lines above full_avg on the previous scan set
  288. // cur_high_avg - Average of all sampled lines above full_avg
  289. // low_avg - Average of all sampled lines below or equal to full_avg
  290. if ( boot_count < WARMUP_LOOPS )
  291. {
  292. for ( uint8_t mux = 0; mux < MUXES_COUNT; ++mux )
  293. {
  294. uint8_t sample = samples[map_strobe][mux] >> 1;
  295. // Sample is high, add it to high avg
  296. if ( sample > full_avg )
  297. {
  298. high_count++;
  299. cur_high_avg += sample;
  300. }
  301. // Sample is low, add it to low avg
  302. else
  303. {
  304. low_count++;
  305. low_avg += sample;
  306. }
  307. // If sample is higher than previous high_avg, then mark as "problem key"
  308. // XXX Giving a bit more margin to pass (high_avg vs. high_avg + high_avg - full_avg) -HaaTa
  309. keys_problem[strobe_line + mux] = sample > high_avg + (high_avg - full_avg) ? sample : 0;
  310. // Prepare for next average
  311. cur_full_avg += sample;
  312. }
  313. }
  314. } // for strober
  315. // Update total sense average (only during warm-up)
  316. if ( boot_count < WARMUP_LOOPS )
  317. {
  318. full_avg = cur_full_avg / (total_strobes * MUXES_COUNT);
  319. high_avg = cur_high_avg / high_count;
  320. low_avg /= low_count;
  321. // Update the base average value using the low_avg (best chance of not ignoring a keypress)
  322. for ( int i = 0; i < KEY_COUNT; ++i )
  323. {
  324. keys_averages[i] = low_avg;
  325. keys_averages_acc[i] = low_avg;
  326. }
  327. }
  328. // Warm up voltage references
  329. if ( boot_count < WARMUP_LOOPS )
  330. {
  331. boot_count++;
  332. switch ( boot_count )
  333. {
  334. // First loop
  335. case 1:
  336. // Show msg at first iteration only
  337. info_msg("Warming up the voltage references");
  338. break;
  339. // Middle iterations
  340. case 300:
  341. case 600:
  342. case 900:
  343. case 1200:
  344. print(".");
  345. break;
  346. // Last loop
  347. case WARMUP_STOP:
  348. print( NL );
  349. info_msg("Warmup finished using ");
  350. printInt16( WARMUP_LOOPS );
  351. print(" iterations" NL );
  352. // Display the final calculated averages of all the sensed strobes
  353. info_msg("Full average (");
  354. printInt8( total_strobes * MUXES_COUNT );
  355. print("): ");
  356. printHex( full_avg );
  357. print(" High average (");
  358. printInt8( high_count );
  359. print("): ");
  360. printHex( high_avg );
  361. print(" Low average (");
  362. printInt8( low_count );
  363. print("): ");
  364. printHex( low_avg );
  365. print(" Rejection threshold: ");
  366. printHex( high_avg + (high_avg - full_avg) );
  367. print( NL );
  368. // Display problem keys, and the sense value at the time
  369. for ( uint8_t key = 0; key < KEY_COUNT; key++ )
  370. {
  371. if ( keys_problem[key] )
  372. {
  373. warn_msg("Problem key detected: ");
  374. printHex( key );
  375. print(" (");
  376. printHex( keys_problem[key] );
  377. print(")" NL );
  378. }
  379. }
  380. info_print("If problem keys were detected, and were being held down, they will be reset as soon as let go.");
  381. info_print("Some keys have unusually high sense values, on the first press they should be re-enabled.");
  382. break;
  383. }
  384. }
  385. else
  386. {
  387. // No keypress, accumulate averages
  388. if( !key_activity )
  389. {
  390. // Only start averaging once the idle counter has counted down to 0
  391. if ( key_idle == 0 )
  392. {
  393. // Average Debugging
  394. if ( enableAvgDebug )
  395. {
  396. print("\033[1mAvg\033[0m: ");
  397. }
  398. // aggregate
  399. for ( uint8_t i = 0; i < KEY_COUNT; ++i )
  400. {
  401. uint16_t acc = keys_averages_acc[i];
  402. //uint16_t acc = keys_averages_acc[i] >> IDLE_COUNT_SHIFT; // XXX This fixes things... -HaaTa
  403. uint32_t av = keys_averages[i];
  404. av = (av << KEYS_AVERAGES_MIX_SHIFT) - av + acc;
  405. av >>= KEYS_AVERAGES_MIX_SHIFT;
  406. keys_averages[i] = av;
  407. keys_averages_acc[i] = 0;
  408. // Average Debugging
  409. if ( enableAvgDebug && av > 0 )
  410. {
  411. printHex( av );
  412. print(" ");
  413. }
  414. }
  415. // Average Debugging
  416. if ( enableAvgDebug )
  417. {
  418. print( NL );
  419. }
  420. // No key presses detected, set key_release indicator
  421. key_release = 1;
  422. }
  423. // Otherwise decrement the idle counter
  424. else
  425. {
  426. key_idle--;
  427. }
  428. }
  429. // Keypresses, reset accumulators
  430. else if ( key_release )
  431. {
  432. for ( uint8_t c = 0; c < KEY_COUNT; ++c ) { keys_averages_acc[c] = 0; }
  433. key_release = 0;
  434. }
  435. // If the debugging sense table is non-zero, display
  436. if ( senseDebugCount > 0 )
  437. {
  438. senseDebugCount--;
  439. print( NL );
  440. dumpSenseTable();
  441. }
  442. }
  443. }
  444. void setup_ADC()
  445. {
  446. // disable adc digital pins.
  447. DIDR1 |= (1 << AIN0D) | (1<<AIN1D); // set disable on pins 1,0.
  448. DDRF = 0x0;
  449. PORTF = 0x0;
  450. uint8_t mux = 0 & 0x1f; // 0 == first. // 0x1e = 1.1V ref.
  451. // 0 = external aref 1,1 = 2.56V internal ref
  452. uint8_t aref = ((1 << REFS1) | (1 << REFS0)) & ((1 << REFS1) | (1 << REFS0));
  453. uint8_t adate = (1 << ADATE) & (1 << ADATE); // trigger enable
  454. uint8_t trig = 0 & ((1 << ADTS0) | (1 << ADTS1) | (1 << ADTS2)); // 0 = free running
  455. // ps2, ps1 := /64 ( 2^6 ) ps2 := /16 (2^4), ps1 := 4, ps0 :=2, PS1,PS0 := 8 (2^8)
  456. uint8_t prescale = ( ((PRESCALE) << PRESCALE_SHIFT) & PRESCALE_MASK ); // 001 == 2^1 == 2
  457. uint8_t hispeed = (1 << ADHSM);
  458. uint8_t en_mux = (1 << ACME);
  459. ADCSRA = (1 << ADEN) | prescale; // ADC enable
  460. // select ref.
  461. //ADMUX |= ((1 << REFS1) | (1 << REFS0)); // 2.56 V internal.
  462. //ADMUX |= ((1 << REFS0) ); // Vcc with external cap.
  463. //ADMUX &= ~((1 << REFS1) | (1 << REFS0)); // 0,0 : aref.
  464. ADMUX = aref | mux | ADLAR_BITS;
  465. // set free-running
  466. ADCSRA |= adate; // trigger enable
  467. ADCSRB = en_mux | hispeed | trig | (ADCSRB & ~((1 << ADTS0) | (1 << ADTS1) | (1 << ADTS2))); // trigger select free running
  468. ADCSRA |= (1 << ADEN); // ADC enable
  469. ADCSRA |= (1 << ADSC); // start conversions q
  470. }
  471. void recovery( uint8_t on )
  472. {
  473. DDRB |= (1 << RECOVERY_CONTROL);
  474. PORTB &= ~(1 << RECOVERY_SINK); // SINK always zero
  475. DDRB &= ~(1 << RECOVERY_SOURCE); // SOURCE high imp
  476. if ( on )
  477. {
  478. // set strobes to sink to gnd.
  479. DDRC |= C_MASK;
  480. DDRD |= D_MASK;
  481. DDRE |= E_MASK;
  482. PORTC &= ~C_MASK;
  483. PORTD &= ~D_MASK;
  484. PORTE &= ~E_MASK;
  485. DDRB |= (1 << RECOVERY_SINK); // SINK pull
  486. PORTB |= (1 << RECOVERY_CONTROL);
  487. PORTB |= (1 << RECOVERY_SOURCE); // SOURCE high
  488. DDRB |= (1 << RECOVERY_SOURCE);
  489. }
  490. else
  491. {
  492. PORTB &= ~(1 << RECOVERY_CONTROL);
  493. DDRB &= ~(1 << RECOVERY_SOURCE);
  494. PORTB &= ~(1 << RECOVERY_SOURCE); // SOURCE low
  495. DDRB &= ~(1 << RECOVERY_SINK); // SINK high-imp
  496. }
  497. }
  498. void hold_sample( uint8_t on )
  499. {
  500. if ( !on )
  501. {
  502. PORTB |= (1 << SAMPLE_CONTROL);
  503. DDRB |= (1 << SAMPLE_CONTROL);
  504. }
  505. else
  506. {
  507. DDRB |= (1 << SAMPLE_CONTROL);
  508. PORTB &= ~(1 << SAMPLE_CONTROL);
  509. }
  510. }
  511. void strobe_w( uint8_t strobe_num )
  512. {
  513. PORTC &= ~(C_MASK);
  514. PORTD &= ~(D_MASK);
  515. PORTE &= ~(E_MASK);
  516. // Strobe table
  517. // Not all strobes are used depending on which are detected
  518. switch ( strobe_num )
  519. {
  520. case 0: PORTD |= (1 << 0); break;
  521. case 1: PORTD |= (1 << 1); break;
  522. case 2: PORTD |= (1 << 2); break;
  523. case 3: PORTD |= (1 << 3); break;
  524. case 4: PORTD |= (1 << 4); break;
  525. case 5: PORTD |= (1 << 5); break;
  526. case 6: PORTD |= (1 << 6); break;
  527. case 7: PORTD |= (1 << 7); break;
  528. case 8: PORTE |= (1 << 0); break;
  529. case 9: PORTE |= (1 << 1); break;
  530. case 10: PORTC |= (1 << 0); break;
  531. case 11: PORTC |= (1 << 1); break;
  532. case 12: PORTC |= (1 << 2); break;
  533. case 13: PORTC |= (1 << 3); break;
  534. case 14: PORTC |= (1 << 4); break;
  535. case 15: PORTC |= (1 << 5); break;
  536. case 16: PORTC |= (1 << 6); break;
  537. case 17: PORTC |= (1 << 7); break;
  538. default:
  539. break;
  540. }
  541. }
  542. inline uint16_t getADC(void)
  543. {
  544. ADCSRA |= (1 << ADIF); // clear int flag by writing 1.
  545. //wait for last read to complete.
  546. while ( !( ADCSRA & (1 << ADIF) ) );
  547. return ADC; // return sample
  548. }
  549. void sampleColumn( uint8_t column )
  550. {
  551. // ensure all probe lines are driven low, and chill for recovery delay.
  552. ADCSRA |= (1 << ADEN) | (1 << ADSC); // enable and start conversions
  553. PORTC &= ~C_MASK;
  554. PORTD &= ~D_MASK;
  555. PORTE &= ~E_MASK;
  556. PORTF = 0;
  557. DDRF = 0;
  558. recovery( OFF );
  559. strobe_w( column );
  560. hold_sample( OFF );
  561. SET_FULL_MUX( 0 );
  562. // Allow strobes to settle
  563. for ( uint8_t i = 0; i < STROBE_SETTLE; ++i ) { getADC(); }
  564. hold_sample( ON );
  565. uint8_t mux = 0;
  566. SET_FULL_MUX( mux );
  567. getADC(); // throw away; unknown mux.
  568. do {
  569. SET_FULL_MUX( mux + 1 ); // our *next* sample will use this
  570. // retrieve current read.
  571. uint16_t readVal = getADC();
  572. samples[column][mux] = readVal;
  573. // Update max sense sample table
  574. if ( readVal > sampleMax[column][mux] )
  575. {
  576. sampleMax[column][mux] = readVal;
  577. }
  578. mux++;
  579. } while ( mux < 8 );
  580. hold_sample( OFF );
  581. recovery( ON );
  582. // turn off adc.
  583. ADCSRA &= ~(1 << ADEN);
  584. // pull all columns' strobe-lines low.
  585. DDRC |= C_MASK;
  586. DDRD |= D_MASK;
  587. DDRE |= E_MASK;
  588. PORTC &= ~C_MASK;
  589. PORTD &= ~D_MASK;
  590. PORTE &= ~E_MASK;
  591. }
  592. void testColumn( uint8_t strobe )
  593. {
  594. uint16_t db_delta = 0;
  595. uint8_t db_sample = 0;
  596. uint16_t db_threshold = 0;
  597. uint8_t column = 0;
  598. uint8_t bit = 1;
  599. for ( uint8_t mux = 0; mux < MUXES_COUNT; ++mux )
  600. {
  601. uint16_t delta = keys_averages[(strobe << MUXES_COUNT_XSHIFT) + mux];
  602. uint8_t key = (strobe << MUXES_COUNT_XSHIFT) + mux;
  603. // Check if this is a bad key (e.g. test point, or non-existent key)
  604. if ( keys_problem[key] )
  605. {
  606. // If the sample value of the problem key goes above initally recorded result + threshold
  607. // re-enable the key
  608. if ( (db_sample = samples[strobe][mux] >> 1) > keys_problem[key] + threshold )
  609. //if ( (db_sample = samples[strobe][mux] >> 1) < high_avg )
  610. {
  611. info_msg("Re-enabling problem key: ");
  612. printHex( key );
  613. print( NL );
  614. keys_problem[key] = 0;
  615. }
  616. // Do not waste any more cycles processing, regardless, a keypress cannot be detected
  617. continue;
  618. }
  619. // Keypress detected
  620. // db_sample (uint8_t), discard meaningless high bit, and garbage low bit
  621. if ( (db_sample = samples[strobe][mux] >> 1) > (db_threshold = threshold) + (db_delta = delta) )
  622. {
  623. column |= bit;
  624. key_activity++; // No longer idle, stop averaging ADC data
  625. key_idle = KEY_IDLE_SCANS; // Reset idle count-down
  626. // Only register keypresses once the warmup is complete, or not enough debounce info
  627. if ( keys_debounce[key] <= DEBOUNCE_THRESHOLD )
  628. {
  629. // Add to the Macro processing buffer if debounce criteria met
  630. // Automatically handles converting to a USB code and sending off to the PC
  631. if ( keys_debounce[key] == DEBOUNCE_THRESHOLD )
  632. {
  633. // Debug message, pressDebug CLI
  634. if ( enablePressDebug )
  635. {
  636. print("0x");
  637. printHex_op( key, 2 );
  638. print(" ");
  639. }
  640. // Initial Keypress
  641. Macro_keyState( key, 0x01 );
  642. }
  643. else if ( keys_debounce[key] >= DEBOUNCE_THRESHOLD )
  644. {
  645. // Held Key
  646. Macro_keyState( key, 0x02 );
  647. }
  648. keys_debounce[key]++;
  649. }
  650. // Long form key debugging
  651. if ( enableKeyDebug )
  652. {
  653. // Debug message
  654. // <key> [<strobe>:<mux>] : <sense val> : <delta + threshold> : <margin>
  655. dbug_msg("0x");
  656. printHex_op( key, 1 );
  657. print(" [");
  658. printInt8( strobe );
  659. print(":");
  660. printInt8( mux );
  661. print("] : ");
  662. printHex( db_sample ); // Sense
  663. print(" : ");
  664. printHex( db_threshold );
  665. print("+");
  666. printHex( db_delta );
  667. print("=");
  668. printHex( db_threshold + db_delta ); // Sense compare
  669. print(" : ");
  670. printHex( db_sample - ( db_threshold + db_delta ) ); // Margin
  671. print( NL );
  672. }
  673. }
  674. // Clear debounce entry if no keypress detected
  675. else
  676. {
  677. // Release Key
  678. if ( KeyIndex_BufferUsed > 0 && keys_debounce[key] >= DEBOUNCE_THRESHOLD )
  679. {
  680. Macro_keyState( key, 0x03 );
  681. }
  682. // Clear debounce entry
  683. keys_debounce[key] = 0;
  684. }
  685. bit <<= 1;
  686. }
  687. }
  688. void dumpSenseTable()
  689. {
  690. // Initial table alignment, with base threshold used for every key
  691. print("\033[1m");
  692. printHex( threshold );
  693. print("\033[0m ");
  694. // Print out headers first
  695. for ( uint8_t mux = 0; mux < MUXES_COUNT; ++mux )
  696. {
  697. print(" Mux \033[1m");
  698. printInt8( mux );
  699. print("\033[0m ");
  700. }
  701. print( NL );
  702. // Display the full strobe/sense table
  703. for ( uint8_t strober = 0; strober < total_strobes; ++strober )
  704. {
  705. uint8_t strobe = strobe_map[strober];
  706. // Display the strobe
  707. print("Strobe \033[1m");
  708. printHex( strobe );
  709. print("\033[0m ");
  710. // For each mux, display sense:threshold:delta
  711. for ( uint8_t mux = 0; mux < MUXES_COUNT; ++mux )
  712. {
  713. uint8_t delta = keys_averages[(strobe << MUXES_COUNT_XSHIFT) + mux];
  714. uint8_t sample = samples[strobe][mux] >> 1;
  715. uint8_t max = sampleMax[strobe][mux] >> 1;
  716. // Indicate if the key is being pressed by displaying green
  717. if ( sample > delta + threshold )
  718. {
  719. print("\033[1;32m");
  720. }
  721. printHex_op( sample, 2 );
  722. print(":");
  723. printHex_op( max, 2 );
  724. print(":");
  725. printHex_op( delta, 2 );
  726. print("\033[0m ");
  727. }
  728. // New line for each strobe
  729. print( NL );
  730. }
  731. }
  732. // ----- CLI Command Functions -----
  733. // XXX Just an example command showing how to parse arguments (more complex than generally needed)
  734. void cliFunc_echo( char* args )
  735. {
  736. char* curArgs;
  737. char* arg1Ptr;
  738. char* arg2Ptr = args;
  739. // Parse args until a \0 is found
  740. while ( 1 )
  741. {
  742. print( NL ); // No \r\n by default after the command is entered
  743. curArgs = arg2Ptr; // Use the previous 2nd arg pointer to separate the next arg from the list
  744. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  745. // Stop processing args if no more are found
  746. if ( *arg1Ptr == '\0' )
  747. break;
  748. // Print out the arg
  749. dPrint( arg1Ptr );
  750. }
  751. }
  752. void cliFunc_avgDebug( char* args )
  753. {
  754. print( NL );
  755. // Args ignored, just toggling
  756. if ( enableAvgDebug )
  757. {
  758. info_print("Cap Sense averaging debug disabled.");
  759. enableAvgDebug = 0;
  760. }
  761. else
  762. {
  763. info_print("Cap Sense averaging debug enabled.");
  764. enableAvgDebug = 1;
  765. }
  766. }
  767. void cliFunc_keyDebug( char* args )
  768. {
  769. print( NL );
  770. // Args ignored, just toggling
  771. if ( enableKeyDebug )
  772. {
  773. info_print("Cap Sense key long debug disabled - pre debounce.");
  774. enableKeyDebug = 0;
  775. }
  776. else
  777. {
  778. info_print("Cap Sense key long debug enabled - pre debounce.");
  779. enableKeyDebug = 1;
  780. }
  781. }
  782. void cliFunc_pressDebug( char* args )
  783. {
  784. print( NL );
  785. // Args ignored, just toggling
  786. if ( enablePressDebug )
  787. {
  788. info_print("Cap Sense key debug disabled - post debounce.");
  789. enablePressDebug = 0;
  790. }
  791. else
  792. {
  793. info_print("Cap Sense key debug enabled - post debounce.");
  794. enablePressDebug = 1;
  795. }
  796. }
  797. void cliFunc_problemKeys( char* args )
  798. {
  799. print( NL );
  800. uint8_t count = 0;
  801. // Args ignored, just displaying
  802. // Display problem keys, and the sense value at the time
  803. for ( uint8_t key = 0; key < KEY_COUNT; key++ )
  804. {
  805. if ( keys_problem[key] )
  806. {
  807. if ( count++ == 0 )
  808. {
  809. warn_msg("Problem keys: ");
  810. }
  811. printHex( key );
  812. print(" (");
  813. printHex( keys_problem[key] );
  814. print(") " );
  815. }
  816. }
  817. }
  818. void cliFunc_senseDebug( char* args )
  819. {
  820. // Parse code from argument
  821. // NOTE: Only first argument is used
  822. char* arg1Ptr;
  823. char* arg2Ptr;
  824. CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
  825. // Default to a single print
  826. senseDebugCount = 1;
  827. // If there was an argument, use that instead
  828. if ( *arg1Ptr != '\0' )
  829. {
  830. senseDebugCount = numToInt( arg1Ptr );
  831. }
  832. }