]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Scan/MD2/scan_loop.c
Initial I2C work for ISSI IS31FL3731
[kiibohd-controller.git] / Scan / MD2 / scan_loop.c
1 /* Copyright (C) 2014 by Jacob Alexander
2  *
3  * Permission is hereby granted, free of charge, to any person obtaining a copy
4  * of this software and associated documentation files (the "Software"), to deal
5  * in the Software without restriction, including without limitation the rights
6  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7  * copies of the Software, and to permit persons to whom the Software is
8  * furnished to do so, subject to the following conditions:
9  *
10  * The above copyright notice and this permission notice shall be included in
11  * all copies or substantial portions of the Software.
12  *
13  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19  * THE SOFTWARE.
20  */
21
22 // ----- Includes -----
23
24 // Compiler Includes
25 #include <Lib/ScanLib.h>
26
27 // Project Includes
28 #include <cli.h>
29 #include <led.h>
30 #include <print.h>
31 #include <matrix_scan.h>
32
33 // Local Includes
34 #include "scan_loop.h"
35 #include "macro.h"
36
37
38
39
40 typedef struct I2C_Buffer {
41         volatile uint16_t  head;
42         volatile uint16_t  tail;
43         volatile uint8_t   sequencePos;
44         volatile uint16_t  size;
45         volatile uint8_t  *buffer;
46 } I2C_Buffer;
47
48 // ----- Function Declarations -----
49
50 // CLI Functions
51 void cliFunc_echo( char* args );
52 void cliFunc_i2cRecv( char* args );
53 void cliFunc_i2cSend( char* args );
54 void cliFunc_ledZero( char* args );
55
56 uint8_t I2C_TxBufferPop();
57 void I2C_BufferPush( uint8_t byte, I2C_Buffer *buffer );
58 uint16_t I2C_BufferLen( I2C_Buffer *buffer );
59
60
61
62 // ----- Variables -----
63
64 // Scan Module command dictionary
65 CLIDict_Entry( echo,        "Example command, echos the arguments." );
66 CLIDict_Entry( i2cRecv,     "Send I2C sequence of bytes and expect a reply of 1 byte." );
67 CLIDict_Entry( i2cSend,     "Send I2C sequence of bytes." );
68 CLIDict_Entry( ledZero,     "Zero out LED register pages (non-configuration)." );
69
70 CLIDict_Def( scanCLIDict, "Scan Module Commands" ) = {
71         CLIDict_Item( echo ),
72         CLIDict_Item( i2cRecv ),
73         CLIDict_Item( i2cSend ),
74         CLIDict_Item( ledZero ),
75         { 0, 0, 0 } // Null entry for dictionary end
76 };
77
78 // Number of scans since the last USB send
79 uint16_t Scan_scanCount = 0;
80
81
82
83 // Before sending the sequence, I2C_TxBuffer_CurLen is assigned and as each byte is sent, it is decremented
84 // Once I2C_TxBuffer_CurLen reaches zero, a STOP on the I2C bus is sent
85 #define I2C_TxBufferLength 300
86 #define I2C_RxBufferLength 8
87 volatile uint8_t I2C_TxBufferPtr[ I2C_TxBufferLength ];
88 volatile uint8_t I2C_RxBufferPtr[ I2C_TxBufferLength ];
89
90 volatile I2C_Buffer I2C_TxBuffer = { 0, 0, 0, I2C_TxBufferLength, I2C_TxBufferPtr };
91 volatile I2C_Buffer I2C_RxBuffer = { 0, 0, 0, I2C_RxBufferLength, I2C_RxBufferPtr };
92
93 void I2C_setup()
94 {
95         // Enable I2C internal clock
96         SIM_SCGC4 |= SIM_SCGC4_I2C0; // Bus 0
97
98         // External pull-up resistor
99         PORTB_PCR0 = PORT_PCR_ODE | PORT_PCR_SRE | PORT_PCR_DSE | PORT_PCR_MUX(2);
100         PORTB_PCR1 = PORT_PCR_ODE | PORT_PCR_SRE | PORT_PCR_DSE | PORT_PCR_MUX(2);
101
102         // SCL Frequency Divider
103         // 400kHz -> 120 (0x85) @ 48 MHz F_BUS
104         I2C0_F = 0x85;
105         I2C0_FLT = 4;
106         I2C0_C1 = I2C_C1_IICEN;
107         I2C0_C2 = I2C_C2_HDRS; // High drive select
108
109         // Enable I2C Interrupt
110         NVIC_ENABLE_IRQ( IRQ_I2C0 );
111 }
112
113
114
115 // ----- Interrupt Functions -----
116
117 void i2c0_isr()
118 {
119         cli(); // Disable Interrupts
120
121         uint8_t status = I2C0_S; // Read I2C Bus status
122
123         // Master Mode Transmit
124         if ( I2C0_C1 & I2C_C1_TX )
125         {
126                 // Check current use of the I2C bus
127                 // Currently sending data
128                 if ( I2C_TxBuffer.sequencePos > 0 )
129                 {
130                         // Make sure slave sent an ACK
131                         if ( status & I2C_S_RXAK )
132                         {
133                                 // NACK Detected, disable interrupt
134                                 erro_print("I2C NAK detected...");
135                                 I2C0_C1 = I2C_C1_IICEN;
136
137                                 // Abort Tx Buffer
138                                 I2C_TxBuffer.head = 0;
139                                 I2C_TxBuffer.tail = 0;
140                                 I2C_TxBuffer.sequencePos = 0;
141                         }
142                         else
143                         {
144                                 // Transmit byte
145                                 I2C0_D = I2C_TxBufferPop();
146                         }
147                 }
148                 // Receiving data
149                 else if ( I2C_RxBuffer.sequencePos > 0 )
150                 {
151                         // Master Receive, addr sent
152                         if ( status & I2C_S_ARBL )
153                         {
154                                 // Arbitration Lost
155                                 erro_print("Arbitration lost...");
156                                 // TODO Abort Rx
157
158                                 I2C0_C1 = I2C_C1_IICEN;
159                                 I2C0_S = I2C_S_ARBL | I2C_S_IICIF; // Clear ARBL flag and interrupt
160                         }
161                         if ( status & I2C_S_RXAK )
162                         {
163                                 // Slave Address NACK Detected, disable interrupt
164                                 erro_print("Slave Address I2C NAK detected...");
165                                 // TODO Abort Rx
166
167                                 I2C0_C1 = I2C_C1_IICEN;
168                         }
169                         else
170                         {
171                                 I2C0_C1 = I2C_RxBuffer.sequencePos == 1
172                                         ? I2C_C1_IICEN | I2C_C1_IICIE | I2C_C1_MST | I2C_C1_TXAK // Single byte read
173                                         : I2C_C1_IICEN | I2C_C1_IICIE | I2C_C1_MST; // Multi-byte read
174                         }
175                 }
176                 else
177                 {
178                         dbug_msg("STOP - ");
179                         printHex( I2C_BufferLen( (I2C_Buffer*)&I2C_TxBuffer ) );
180                         print(NL);
181
182                         // If there is another sequence, start sending
183                         if ( I2C_BufferLen( (I2C_Buffer*)&I2C_TxBuffer ) < I2C_TxBuffer.size )
184                         {
185                                 // Check to see if we already have control of the bus
186                                 if ( I2C0_C1 & I2C_C1_MST )
187                                 {
188                                         // Already the master (ah yeah), send a repeated start
189                                         I2C0_C1 = I2C_C1_IICEN | I2C_C1_MST | I2C_C1_RSTA | I2C_C1_TX;
190                                 }
191                                 // Otherwise, seize control
192                                 else
193                                 {
194                                         // Wait...till the master dies
195                                         while ( I2C0_S & I2C_S_BUSY );
196
197                                         // Now we're the master (ah yisss), get ready to send stuffs
198                                         I2C0_C1 = I2C_C1_IICEN | I2C_C1_MST | I2C_C1_TX;
199                                 }
200
201                                 // Enable I2C interrupt
202                                 I2C0_C1 = I2C_C1_IICEN | I2C_C1_IICIE | I2C_C1_MST | I2C_C1_TX;
203
204                                 // Transmit byte
205                                 I2C0_D = I2C_TxBufferPop();
206                         }
207                         // Issue STOP
208                         else
209                         {
210                                 delayMicroseconds( 1 ); // Should be enough time before issuing STOP
211                                 I2C0_C1 = I2C_C1_IICEN; // Send STOP
212                         }
213                 }
214         }
215         // Master Mode Receive
216         else
217         {
218                 // XXX Do we need to handle 2nd last byte?
219                 //I2C0_C1 = I2C_C1_IICEN | I2C_C1_IICIE | I2C_C1_MST | I2C_C1_TXAK; // No STOP, Rx, NAK on recv
220
221                 // Last byte
222                 if ( I2C_TxBuffer.sequencePos <= 1 )
223                 {
224                         // Change to Tx mode
225                         I2C0_C1 = I2C_C1_IICEN | I2C_C1_MST | I2C_C1_TX;
226
227                         // Grab last byte
228                         I2C_BufferPush( I2C0_D, (I2C_Buffer*)&I2C_RxBuffer );
229
230                         delayMicroseconds( 1 ); // Should be enough time before issuing the stop
231                         I2C0_C1 = I2C_C1_IICEN; // Send STOP
232                 }
233                 else
234                 {
235                         // Retrieve data
236                         I2C_BufferPush( I2C0_D, (I2C_Buffer*)&I2C_RxBuffer );
237                 }
238         }
239
240         I2C0_S = I2C_S_IICIF; // Clear interrupt
241
242         sei(); // Re-enable Interrupts
243 }
244
245
246
247 // ----- Functions -----
248
249 // Setup
250 inline void LED_setup()
251 {
252         I2C_setup();
253 }
254
255
256 inline uint8_t I2C_BufferCopy( uint8_t *data, uint8_t sendLen, uint8_t recvLen, I2C_Buffer *buffer )
257 {
258         uint8_t reTurn = 0;
259
260         // If sendLen is greater than buffer fail right away
261         if ( sendLen > buffer->size )
262                 return 0;
263
264         // Calculate new tail to determine if buffer has enough space
265         // The first element specifies the expected number of bytes from the slave (+1)
266         // The second element in the new buffer is the length of the buffer sequence (+1)
267         uint16_t newTail = buffer->tail + sendLen + 2;
268         if ( newTail >= buffer->size )
269                 newTail -= buffer->size;
270
271         if ( I2C_BufferLen( buffer ) < sendLen + 2 )
272                 return 0;
273
274 /*
275         print("|");
276         printHex( sendLen + 2 );
277         print("|");
278         printHex( *tail );
279         print("@");
280         printHex( newTail );
281         print("@");
282 */
283
284         // If buffer is clean, return 1, otherwise 2
285         reTurn = buffer->head == buffer->tail ? 1 : 2;
286
287         // Add to buffer, already know there is enough room (simplifies adding logic)
288         uint8_t bufferHeaderPos = 0;
289         for ( uint16_t c = 0; c < sendLen; c++ )
290         {
291                 // Add data to buffer
292                 switch ( bufferHeaderPos )
293                 {
294                 case 0:
295                         buffer->buffer[ buffer->tail ] = recvLen;
296                         bufferHeaderPos++;
297                         c--;
298                         break;
299
300                 case 1:
301                         buffer->buffer[ buffer->tail ] = sendLen;
302                         bufferHeaderPos++;
303                         c--;
304                         break;
305
306                 default:
307                         buffer->buffer[ buffer->tail ] = data[ c ];
308                         break;
309                 }
310
311                 // Check for wrap-around case
312                 if ( buffer->tail + 1 >= buffer->size )
313                 {
314                         buffer->tail = 0;
315                 }
316                 // Normal case
317                 else
318                 {
319                         buffer->tail++;
320                 }
321         }
322
323         return reTurn;
324 }
325
326
327 inline uint16_t I2C_BufferLen( I2C_Buffer *buffer )
328 {
329         // Tail >= Head
330         if ( buffer->tail >= buffer->head )
331                 return buffer->head + buffer->size - buffer->tail;
332
333         // Head > Tail
334         return buffer->head - buffer->tail;
335 }
336
337
338 void I2C_BufferPush( uint8_t byte, I2C_Buffer *buffer )
339 {
340         // Make sure buffer isn't full
341         if ( buffer->tail + 1 == buffer->head || ( buffer->head > buffer->tail && buffer->tail + 1 - buffer->size == buffer->head ) )
342         {
343                 warn_msg("I2C_BufferPush failed, buffer full: ");
344                 printHex( byte );
345                 print( NL );
346                 return;
347         }
348
349         // Check for wrap-around case
350         if ( buffer->tail + 1 >= buffer->size )
351         {
352                 buffer->tail = 0;
353         }
354         // Normal case
355         else
356         {
357                 buffer->tail++;
358         }
359
360         // Add byte to buffer
361         buffer->buffer[ buffer->tail ] = byte;
362 }
363
364
365 uint8_t I2C_TxBufferPop()
366 {
367         // Return 0xFF if no buffer left (do not rely on this)
368         if ( I2C_BufferLen( (I2C_Buffer*)&I2C_TxBuffer ) >= I2C_TxBuffer.size )
369         {
370                 erro_msg("No buffer to pop an entry from... ");
371                 printHex( I2C_TxBuffer.head );
372                 print(" ");
373                 printHex( I2C_TxBuffer.tail );
374                 print(" ");
375                 printHex( I2C_TxBuffer.sequencePos );
376                 print(NL);
377                 return 0xFF;
378         }
379
380         // If there is currently no sequence being sent, the first entry in the RingBuffer is the length
381         if ( I2C_TxBuffer.sequencePos == 0 )
382         {
383                 I2C_TxBuffer.sequencePos = 0xFF; // So this doesn't become an infinite loop
384                 I2C_RxBuffer.sequencePos = I2C_TxBufferPop();
385                 I2C_TxBuffer.sequencePos = I2C_TxBufferPop();
386         }
387
388         uint8_t data = I2C_TxBuffer.buffer[ I2C_TxBuffer.head ];
389
390         // Prune head
391         I2C_TxBuffer.head++;
392
393         // Wrap-around case
394         if ( I2C_TxBuffer.head >= I2C_TxBuffer.size )
395                 I2C_TxBuffer.head = 0;
396
397         // Decrement buffer sequence (until next stop will be sent)
398         I2C_TxBuffer.sequencePos--;
399
400         dbug_msg("Popping: ");
401         printHex( data );
402         print(" ");
403         printHex( I2C_TxBuffer.head );
404         print(" ");
405         printHex( I2C_TxBuffer.tail );
406         print(" ");
407         printHex( I2C_TxBuffer.sequencePos );
408         print(NL);
409         return data;
410 }
411
412
413 uint8_t I2C_Send( uint8_t *data, uint8_t sendLen, uint8_t recvLen )
414 {
415         // Check head and tail pointers
416         // If full, return 0
417         // If empty, start up I2C Master Tx
418         // If buffer is non-empty and non-full, just append to the buffer
419         switch ( I2C_BufferCopy( data, sendLen, recvLen, (I2C_Buffer*)&I2C_TxBuffer ) )
420         {
421         // Not enough buffer space...
422         case 0:
423                 /*
424                 erro_msg("Not enough Tx buffer space... ");
425                 printHex( I2C_TxBuffer.head );
426                 print(":");
427                 printHex( I2C_TxBuffer.tail );
428                 print("+");
429                 printHex( sendLen );
430                 print("|");
431                 printHex( I2C_TxBuffer.size );
432                 print( NL );
433                 */
434                 return 0;
435
436         // Empty buffer, initialize I2C
437         case 1:
438                 // Clear status flags
439                 I2C0_S = I2C_S_IICIF | I2C_S_ARBL;
440
441                 // Check to see if we already have control of the bus
442                 if ( I2C0_C1 & I2C_C1_MST )
443                 {
444                         // Already the master (ah yeah), send a repeated start
445                         I2C0_C1 = I2C_C1_IICEN | I2C_C1_MST | I2C_C1_RSTA | I2C_C1_TX;
446                 }
447                 // Otherwise, seize control
448                 else
449                 {
450                         // Wait...till the master dies
451                         while ( I2C0_S & I2C_S_BUSY );
452
453                         // Now we're the master (ah yisss), get ready to send stuffs
454                         I2C0_C1 = I2C_C1_IICEN | I2C_C1_MST | I2C_C1_TX;
455                 }
456
457                 // Enable I2C interrupt
458                 I2C0_C1 = I2C_C1_IICEN | I2C_C1_IICIE | I2C_C1_MST | I2C_C1_TX;
459
460                 // Depending on what type of transfer, the first byte is configured for R or W
461                 I2C0_D = I2C_TxBufferPop();
462                 return 1;
463         }
464
465         // Dirty buffer, I2C already initialized
466         return 2;
467 }
468
469
470 void LED_zeroPages( uint8_t startPage, uint8_t numPages, uint8_t pageLen )
471 {
472         // Page Setup
473         uint8_t pageSetup[] = { 0xE8, 0xFD, 0x00 };
474
475         // Max length of a page + chip id + reg start
476         uint8_t fullPage[ 0xB3 + 2 ] = { 0 };
477         fullPage[0] = 0xE8; // Set chip id, starting reg is already 0x00
478
479         // Iterate through given pages, zero'ing out the given register regions
480         for ( uint8_t page = startPage; page < startPage + numPages; page++ )
481         {
482                 // Set page
483                 pageSetup[2] = page;
484
485                 // Setup page
486                 while ( I2C_Send( pageSetup, sizeof( pageSetup ), 0 ) == 0 )
487                         delay(1);
488
489                 // Zero out page
490                 while ( I2C_Send( fullPage, pageLen + 2, 0 ) == 0 )
491                         delay(1);
492         }
493 }
494
495
496
497 // LED State processing loop
498 inline uint8_t LED_loop()
499 {
500
501         // I2C Busy
502         // S & I2C_S_BUSY
503         //I2C_S_BUSY
504 }
505
506
507
508 // Setup
509 inline void Scan_setup()
510 {
511         // Register Scan CLI dictionary
512         CLI_registerDictionary( scanCLIDict, scanCLIDictName );
513
514         // Setup GPIO pins for matrix scanning
515         //Matrix_setup();
516
517         // Reset scan count
518         Scan_scanCount = 0;
519
520         // Setup LED Drivers
521         LED_setup();
522 }
523
524
525 // Main Detection Loop
526 inline uint8_t Scan_loop()
527 {
528         //Matrix_scan( Scan_scanCount++ );
529         //LED_scan();
530
531         return 0;
532 }
533
534
535 // Signal from Macro Module that all keys have been processed (that it knows about)
536 inline void Scan_finishedWithMacro( uint8_t sentKeys )
537 {
538 }
539
540
541 // Signal from Output Module that all keys have been processed (that it knows about)
542 inline void Scan_finishedWithOutput( uint8_t sentKeys )
543 {
544         // Reset scan loop indicator (resets each key debounce state)
545         // TODO should this occur after USB send or Macro processing?
546         Scan_scanCount = 0;
547 }
548
549
550 // ----- CLI Command Functions -----
551
552 // XXX Just an example command showing how to parse arguments (more complex than generally needed)
553 void cliFunc_echo( char* args )
554 {
555         char* curArgs;
556         char* arg1Ptr;
557         char* arg2Ptr = args;
558
559         // Parse args until a \0 is found
560         while ( 1 )
561         {
562                 print( NL ); // No \r\n by default after the command is entered
563
564                 curArgs = arg2Ptr; // Use the previous 2nd arg pointer to separate the next arg from the list
565                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
566
567                 // Stop processing args if no more are found
568                 if ( *arg1Ptr == '\0' )
569                         break;
570
571                 // Print out the arg
572                 dPrint( arg1Ptr );
573         }
574 }
575
576 void cliFunc_i2cSend( char* args )
577 {
578         char* curArgs;
579         char* arg1Ptr;
580         char* arg2Ptr = args;
581
582         // Buffer used after interpretting the args, will be sent to I2C functions
583         // NOTE: Limited to 8 bytes currently (can be increased if necessary
584         #define i2cSend_BuffLenMax 8
585         uint8_t buffer[ i2cSend_BuffLenMax ];
586         uint8_t bufferLen = 0;
587
588         // No \r\n by default after the command is entered
589         print( NL );
590         info_msg("Sending: ");
591
592         // Parse args until a \0 is found
593         while ( bufferLen < i2cSend_BuffLenMax )
594         {
595                 curArgs = arg2Ptr; // Use the previous 2nd arg pointer to separate the next arg from the list
596                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
597
598                 // Stop processing args if no more are found
599                 if ( *arg1Ptr == '\0' )
600                         break;
601
602                 // Interpret the argument
603                 buffer[ bufferLen++ ] = (uint8_t)numToInt( arg1Ptr );
604
605                 // Print out the arg
606                 dPrint( arg1Ptr );
607                 print(" ");
608         }
609
610         print( NL );
611
612         I2C_Send( buffer, bufferLen, 0 );
613 }
614
615 void cliFunc_i2cRecv( char* args )
616 {
617         char* curArgs;
618         char* arg1Ptr;
619         char* arg2Ptr = args;
620
621         // Buffer used after interpretting the args, will be sent to I2C functions
622         // NOTE: Limited to 8 bytes currently (can be increased if necessary
623         #define i2cSend_BuffLenMax 8
624         uint8_t buffer[ i2cSend_BuffLenMax ];
625         uint8_t bufferLen = 0;
626
627         // No \r\n by default after the command is entered
628         print( NL );
629         info_msg("Sending: ");
630
631         // Parse args until a \0 is found
632         while ( bufferLen < i2cSend_BuffLenMax )
633         {
634                 curArgs = arg2Ptr; // Use the previous 2nd arg pointer to separate the next arg from the list
635                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
636
637                 // Stop processing args if no more are found
638                 if ( *arg1Ptr == '\0' )
639                         break;
640
641                 // Interpret the argument
642                 buffer[ bufferLen++ ] = (uint8_t)numToInt( arg1Ptr );
643
644                 // Print out the arg
645                 dPrint( arg1Ptr );
646                 print(" ");
647         }
648
649         print( NL );
650
651         I2C_Send( buffer, bufferLen, 1 ); // Only 1 byte is ever read at a time with the ISSI chip
652 }
653
654 void cliFunc_ledZero( char* args )
655 {
656         print( NL ); // No \r\n by default after the command is entered
657         LED_zeroPages( 0x00, 8, 0xB3 );
658 }
659