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

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