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

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