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 23KB

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