Kiibohd Controller
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

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