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.

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