1 /* Copyright (C) 2014 by Jacob Alexander
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:
10 * The above copyright notice and this permission notice shall be included in
11 * all copies or substantial portions of the Software.
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
22 // ----- Includes -----
25 #include <Lib/ScanLib.h>
31 #include <matrix_scan.h>
34 #include "scan_loop.h"
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;
48 // ----- Function Declarations -----
51 void cliFunc_echo( char* args );
52 void cliFunc_i2cRecv( char* args );
53 void cliFunc_i2cSend( char* args );
54 void cliFunc_ledZero( char* args );
56 uint8_t I2C_TxBufferPop();
57 void I2C_BufferPush( uint8_t byte, I2C_Buffer *buffer );
58 uint16_t I2C_BufferLen( I2C_Buffer *buffer );
62 // ----- Variables -----
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)." );
70 CLIDict_Def( scanCLIDict, "Scan Module Commands" ) = {
72 CLIDict_Item( i2cRecv ),
73 CLIDict_Item( i2cSend ),
74 CLIDict_Item( ledZero ),
75 { 0, 0, 0 } // Null entry for dictionary end
78 // Number of scans since the last USB send
79 uint16_t Scan_scanCount = 0;
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 ];
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 };
95 // Enable I2C internal clock
96 SIM_SCGC4 |= SIM_SCGC4_I2C0; // Bus 0
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);
102 // SCL Frequency Divider
103 // 400kHz -> 120 (0x85) @ 48 MHz F_BUS
106 I2C0_C1 = I2C_C1_IICEN;
107 I2C0_C2 = I2C_C2_HDRS; // High drive select
109 // Enable I2C Interrupt
110 NVIC_ENABLE_IRQ( IRQ_I2C0 );
115 // ----- Interrupt Functions -----
119 cli(); // Disable Interrupts
121 uint8_t status = I2C0_S; // Read I2C Bus status
123 // Master Mode Transmit
124 if ( I2C0_C1 & I2C_C1_TX )
126 // Check current use of the I2C bus
127 // Currently sending data
128 if ( I2C_TxBuffer.sequencePos > 0 )
130 // Make sure slave sent an ACK
131 if ( status & I2C_S_RXAK )
133 // NACK Detected, disable interrupt
134 erro_print("I2C NAK detected...");
135 I2C0_C1 = I2C_C1_IICEN;
138 I2C_TxBuffer.head = 0;
139 I2C_TxBuffer.tail = 0;
140 I2C_TxBuffer.sequencePos = 0;
145 I2C0_D = I2C_TxBufferPop();
149 else if ( I2C_RxBuffer.sequencePos > 0 )
151 // Master Receive, addr sent
152 if ( status & I2C_S_ARBL )
155 erro_print("Arbitration lost...");
158 I2C0_C1 = I2C_C1_IICEN;
159 I2C0_S = I2C_S_ARBL | I2C_S_IICIF; // Clear ARBL flag and interrupt
161 if ( status & I2C_S_RXAK )
163 // Slave Address NACK Detected, disable interrupt
164 erro_print("Slave Address I2C NAK detected...");
167 I2C0_C1 = I2C_C1_IICEN;
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
179 printHex( I2C_BufferLen( (I2C_Buffer*)&I2C_TxBuffer ) );
182 // If there is another sequence, start sending
183 if ( I2C_BufferLen( (I2C_Buffer*)&I2C_TxBuffer ) < I2C_TxBuffer.size )
185 // Check to see if we already have control of the bus
186 if ( I2C0_C1 & I2C_C1_MST )
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;
191 // Otherwise, seize control
194 // Wait...till the master dies
195 while ( I2C0_S & I2C_S_BUSY );
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;
201 // Enable I2C interrupt
202 I2C0_C1 = I2C_C1_IICEN | I2C_C1_IICIE | I2C_C1_MST | I2C_C1_TX;
205 I2C0_D = I2C_TxBufferPop();
210 delayMicroseconds( 1 ); // Should be enough time before issuing STOP
211 I2C0_C1 = I2C_C1_IICEN; // Send STOP
215 // Master Mode Receive
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
222 if ( I2C_TxBuffer.sequencePos <= 1 )
225 I2C0_C1 = I2C_C1_IICEN | I2C_C1_MST | I2C_C1_TX;
228 I2C_BufferPush( I2C0_D, (I2C_Buffer*)&I2C_RxBuffer );
230 delayMicroseconds( 1 ); // Should be enough time before issuing the stop
231 I2C0_C1 = I2C_C1_IICEN; // Send STOP
236 I2C_BufferPush( I2C0_D, (I2C_Buffer*)&I2C_RxBuffer );
240 I2C0_S = I2C_S_IICIF; // Clear interrupt
242 sei(); // Re-enable Interrupts
247 // ----- Functions -----
250 inline void LED_setup()
256 inline uint8_t I2C_BufferCopy( uint8_t *data, uint8_t sendLen, uint8_t recvLen, I2C_Buffer *buffer )
260 // If sendLen is greater than buffer fail right away
261 if ( sendLen > buffer->size )
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;
271 if ( I2C_BufferLen( buffer ) < sendLen + 2 )
276 printHex( sendLen + 2 );
284 // If buffer is clean, return 1, otherwise 2
285 reTurn = buffer->head == buffer->tail ? 1 : 2;
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++ )
291 // Add data to buffer
292 switch ( bufferHeaderPos )
295 buffer->buffer[ buffer->tail ] = recvLen;
301 buffer->buffer[ buffer->tail ] = sendLen;
307 buffer->buffer[ buffer->tail ] = data[ c ];
311 // Check for wrap-around case
312 if ( buffer->tail + 1 >= buffer->size )
327 inline uint16_t I2C_BufferLen( I2C_Buffer *buffer )
330 if ( buffer->tail >= buffer->head )
331 return buffer->head + buffer->size - buffer->tail;
334 return buffer->head - buffer->tail;
338 void I2C_BufferPush( uint8_t byte, I2C_Buffer *buffer )
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 ) )
343 warn_msg("I2C_BufferPush failed, buffer full: ");
349 // Check for wrap-around case
350 if ( buffer->tail + 1 >= buffer->size )
360 // Add byte to buffer
361 buffer->buffer[ buffer->tail ] = byte;
365 uint8_t I2C_TxBufferPop()
367 // Return 0xFF if no buffer left (do not rely on this)
368 if ( I2C_BufferLen( (I2C_Buffer*)&I2C_TxBuffer ) >= I2C_TxBuffer.size )
370 erro_msg("No buffer to pop an entry from... ");
371 printHex( I2C_TxBuffer.head );
373 printHex( I2C_TxBuffer.tail );
375 printHex( I2C_TxBuffer.sequencePos );
380 // If there is currently no sequence being sent, the first entry in the RingBuffer is the length
381 if ( I2C_TxBuffer.sequencePos == 0 )
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();
388 uint8_t data = I2C_TxBuffer.buffer[ I2C_TxBuffer.head ];
394 if ( I2C_TxBuffer.head >= I2C_TxBuffer.size )
395 I2C_TxBuffer.head = 0;
397 // Decrement buffer sequence (until next stop will be sent)
398 I2C_TxBuffer.sequencePos--;
400 dbug_msg("Popping: ");
403 printHex( I2C_TxBuffer.head );
405 printHex( I2C_TxBuffer.tail );
407 printHex( I2C_TxBuffer.sequencePos );
413 uint8_t I2C_Send( uint8_t *data, uint8_t sendLen, uint8_t recvLen )
415 // Check head and tail pointers
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 ) )
421 // Not enough buffer space...
424 erro_msg("Not enough Tx buffer space... ");
425 printHex( I2C_TxBuffer.head );
427 printHex( I2C_TxBuffer.tail );
431 printHex( I2C_TxBuffer.size );
436 // Empty buffer, initialize I2C
438 // Clear status flags
439 I2C0_S = I2C_S_IICIF | I2C_S_ARBL;
441 // Check to see if we already have control of the bus
442 if ( I2C0_C1 & I2C_C1_MST )
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;
447 // Otherwise, seize control
450 // Wait...till the master dies
451 while ( I2C0_S & I2C_S_BUSY );
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;
457 // Enable I2C interrupt
458 I2C0_C1 = I2C_C1_IICEN | I2C_C1_IICIE | I2C_C1_MST | I2C_C1_TX;
460 // Depending on what type of transfer, the first byte is configured for R or W
461 I2C0_D = I2C_TxBufferPop();
465 // Dirty buffer, I2C already initialized
470 void LED_zeroPages( uint8_t startPage, uint8_t numPages, uint8_t pageLen )
473 uint8_t pageSetup[] = { 0xE8, 0xFD, 0x00 };
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
479 // Iterate through given pages, zero'ing out the given register regions
480 for ( uint8_t page = startPage; page < startPage + numPages; page++ )
486 while ( I2C_Send( pageSetup, sizeof( pageSetup ), 0 ) == 0 )
490 while ( I2C_Send( fullPage, pageLen + 2, 0 ) == 0 )
497 // LED State processing loop
498 inline uint8_t LED_loop()
509 inline void Scan_setup()
511 // Register Scan CLI dictionary
512 CLI_registerDictionary( scanCLIDict, scanCLIDictName );
514 // Setup GPIO pins for matrix scanning
525 // Main Detection Loop
526 inline uint8_t Scan_loop()
528 //Matrix_scan( Scan_scanCount++ );
535 // Signal from Macro Module that all keys have been processed (that it knows about)
536 inline void Scan_finishedWithMacro( uint8_t sentKeys )
541 // Signal from Output Module that all keys have been processed (that it knows about)
542 inline void Scan_finishedWithOutput( uint8_t sentKeys )
544 // Reset scan loop indicator (resets each key debounce state)
545 // TODO should this occur after USB send or Macro processing?
550 // ----- CLI Command Functions -----
552 // XXX Just an example command showing how to parse arguments (more complex than generally needed)
553 void cliFunc_echo( char* args )
557 char* arg2Ptr = args;
559 // Parse args until a \0 is found
562 print( NL ); // No \r\n by default after the command is entered
564 curArgs = arg2Ptr; // Use the previous 2nd arg pointer to separate the next arg from the list
565 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
567 // Stop processing args if no more are found
568 if ( *arg1Ptr == '\0' )
576 void cliFunc_i2cSend( char* args )
580 char* arg2Ptr = args;
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;
588 // No \r\n by default after the command is entered
590 info_msg("Sending: ");
592 // Parse args until a \0 is found
593 while ( bufferLen < i2cSend_BuffLenMax )
595 curArgs = arg2Ptr; // Use the previous 2nd arg pointer to separate the next arg from the list
596 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
598 // Stop processing args if no more are found
599 if ( *arg1Ptr == '\0' )
602 // Interpret the argument
603 buffer[ bufferLen++ ] = (uint8_t)numToInt( arg1Ptr );
612 I2C_Send( buffer, bufferLen, 0 );
615 void cliFunc_i2cRecv( char* args )
619 char* arg2Ptr = args;
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;
627 // No \r\n by default after the command is entered
629 info_msg("Sending: ");
631 // Parse args until a \0 is found
632 while ( bufferLen < i2cSend_BuffLenMax )
634 curArgs = arg2Ptr; // Use the previous 2nd arg pointer to separate the next arg from the list
635 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
637 // Stop processing args if no more are found
638 if ( *arg1Ptr == '\0' )
641 // Interpret the argument
642 buffer[ bufferLen++ ] = (uint8_t)numToInt( arg1Ptr );
651 I2C_Send( buffer, bufferLen, 1 ); // Only 1 byte is ever read at a time with the ISSI chip
654 void cliFunc_ledZero( char* args )
656 print( NL ); // No \r\n by default after the command is entered
657 LED_zeroPages( 0x00, 8, 0xB3 );