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 {
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 );
59 uint8_t I2C_Send( uint8_t *data, uint8_t sendLen, uint8_t recvLen );
63 // ----- Variables -----
65 // Scan Module command dictionary
66 CLIDict_Entry( echo, "Example command, echos the arguments." );
67 CLIDict_Entry( i2cRecv, "Send I2C sequence of bytes and expect a reply of 1 byte on the last sequence. Use |'s to split sequences with a stop." );
68 CLIDict_Entry( i2cSend, "Send I2C sequence of bytes. Use |'s to split sequences with a stop." );
69 CLIDict_Entry( ledZero, "Zero out LED register pages (non-configuration)." );
71 CLIDict_Def( scanCLIDict, "Scan Module Commands" ) = {
73 CLIDict_Item( i2cRecv ),
74 CLIDict_Item( i2cSend ),
75 CLIDict_Item( ledZero ),
76 { 0, 0, 0 } // Null entry for dictionary end
79 // Number of scans since the last USB send
80 uint16_t Scan_scanCount = 0;
84 // Before sending the sequence, I2C_TxBuffer_CurLen is assigned and as each byte is sent, it is decremented
85 // Once I2C_TxBuffer_CurLen reaches zero, a STOP on the I2C bus is sent
86 #define I2C_TxBufferLength 300
87 #define I2C_RxBufferLength 8
88 volatile uint8_t I2C_TxBufferPtr[ I2C_TxBufferLength ];
89 volatile uint8_t I2C_RxBufferPtr[ I2C_TxBufferLength ];
91 volatile I2C_Buffer I2C_TxBuffer = { 0, 0, 0, I2C_TxBufferLength, (uint8_t*)I2C_TxBufferPtr };
92 volatile I2C_Buffer I2C_RxBuffer = { 0, 0, 0, I2C_RxBufferLength, (uint8_t*)I2C_RxBufferPtr };
96 // Enable I2C internal clock
97 SIM_SCGC4 |= SIM_SCGC4_I2C0; // Bus 0
99 // External pull-up resistor
100 PORTB_PCR0 = PORT_PCR_ODE | PORT_PCR_SRE | PORT_PCR_DSE | PORT_PCR_MUX(2);
101 PORTB_PCR1 = PORT_PCR_ODE | PORT_PCR_SRE | PORT_PCR_DSE | PORT_PCR_MUX(2);
103 // SCL Frequency Divider
104 // 400kHz -> 120 (0x85) @ 48 MHz F_BUS
107 I2C0_C1 = I2C_C1_IICEN;
108 I2C0_C2 = I2C_C2_HDRS; // High drive select
110 // Enable I2C Interrupt
111 NVIC_ENABLE_IRQ( IRQ_I2C0 );
116 // ----- Interrupt Functions -----
120 cli(); // Disable Interrupts
122 uint8_t status = I2C0_S; // Read I2C Bus status
124 // Master Mode Transmit
125 if ( I2C0_C1 & I2C_C1_TX )
127 // Check current use of the I2C bus
128 // Currently sending data
129 if ( I2C_TxBuffer.sequencePos > 0 )
131 // Make sure slave sent an ACK
132 if ( status & I2C_S_RXAK )
134 // NACK Detected, disable interrupt
135 erro_print("I2C NAK detected...");
136 I2C0_C1 = I2C_C1_IICEN;
139 I2C_TxBuffer.head = 0;
140 I2C_TxBuffer.tail = 0;
141 I2C_TxBuffer.sequencePos = 0;
146 I2C0_D = I2C_TxBufferPop();
150 else if ( I2C_RxBuffer.sequencePos > 0 )
152 // Master Receive, addr sent
153 if ( status & I2C_S_ARBL )
156 erro_print("Arbitration lost...");
159 I2C0_C1 = I2C_C1_IICEN;
160 I2C0_S = I2C_S_ARBL | I2C_S_IICIF; // Clear ARBL flag and interrupt
162 if ( status & I2C_S_RXAK )
164 // Slave Address NACK Detected, disable interrupt
165 erro_print("Slave Address I2C NAK detected...");
168 I2C0_C1 = I2C_C1_IICEN;
172 dbug_print("Attempting to read byte");
173 I2C0_C1 = I2C_RxBuffer.sequencePos == 1
174 ? I2C_C1_IICEN | I2C_C1_IICIE | I2C_C1_MST | I2C_C1_TXAK // Single byte read
175 : I2C_C1_IICEN | I2C_C1_IICIE | I2C_C1_MST; // Multi-byte read
182 printHex( I2C_BufferLen( (I2C_Buffer*)&I2C_TxBuffer ) );
186 // Delay around STOP to make sure it actually happens...
187 delayMicroseconds( 1 );
188 I2C0_C1 = I2C_C1_IICEN; // Send STOP
189 delayMicroseconds( 7 );
191 // If there is another sequence, start sending
192 if ( I2C_BufferLen( (I2C_Buffer*)&I2C_TxBuffer ) < I2C_TxBuffer.size )
194 // Clear status flags
195 I2C0_S = I2C_S_IICIF | I2C_S_ARBL;
197 // Wait...till the master dies
198 while ( I2C0_S & I2C_S_BUSY );
200 // Enable I2C interrupt
201 I2C0_C1 = I2C_C1_IICEN | I2C_C1_IICIE | I2C_C1_MST | I2C_C1_TX;
204 I2C0_D = I2C_TxBufferPop();
208 // Master Mode Receive
211 // XXX Do we need to handle 2nd last byte?
212 //I2C0_C1 = I2C_C1_IICEN | I2C_C1_IICIE | I2C_C1_MST | I2C_C1_TXAK; // No STOP, Rx, NAK on recv
215 if ( I2C_TxBuffer.sequencePos <= 1 )
218 I2C0_C1 = I2C_C1_IICEN | I2C_C1_MST | I2C_C1_TX;
221 I2C_BufferPush( I2C0_D, (I2C_Buffer*)&I2C_RxBuffer );
223 delayMicroseconds( 1 ); // Should be enough time before issuing the stop
224 I2C0_C1 = I2C_C1_IICEN; // Send STOP
229 I2C_BufferPush( I2C0_D, (I2C_Buffer*)&I2C_RxBuffer );
233 I2C0_S = I2C_S_IICIF; // Clear interrupt
235 sei(); // Re-enable Interrupts
240 // ----- Functions -----
242 void LED_zeroPages( uint8_t startPage, uint8_t numPages, uint8_t pageLen )
245 uint8_t pageSetup[] = { 0xE8, 0xFD, 0x00 };
247 // Max length of a page + chip id + reg start
248 uint8_t fullPage[ 0xB3 + 2 ] = { 0 };
249 fullPage[0] = 0xE8; // Set chip id, starting reg is already 0x00
251 // Iterate through given pages, zero'ing out the given register regions
252 for ( uint8_t page = startPage; page < startPage + numPages; page++ )
258 while ( I2C_Send( pageSetup, sizeof( pageSetup ), 0 ) == 0 )
262 while ( I2C_Send( fullPage, pageLen + 2, 0 ) == 0 )
269 inline void LED_setup()
273 // Zero out Frame Registers
274 LED_zeroPages( 0x00, 8, 0xB3 ); // LED Registers
275 LED_zeroPages( 0x0B, 1, 0x0C ); // Control Registers
277 // Disable Hardware shutdown of ISSI chip (pull high)
278 GPIOD_PDDR |= (1<<1);
279 PORTD_PCR1 = PORT_PCR_SRE | PORT_PCR_DSE | PORT_PCR_MUX(1);
280 GPIOD_PSOR |= (1<<1);
284 inline uint8_t I2C_BufferCopy( uint8_t *data, uint8_t sendLen, uint8_t recvLen, I2C_Buffer *buffer )
288 // If sendLen is greater than buffer fail right away
289 if ( sendLen > buffer->size )
292 // Calculate new tail to determine if buffer has enough space
293 // The first element specifies the expected number of bytes from the slave (+1)
294 // The second element in the new buffer is the length of the buffer sequence (+1)
295 uint16_t newTail = buffer->tail + sendLen + 2;
296 if ( newTail >= buffer->size )
297 newTail -= buffer->size;
299 if ( I2C_BufferLen( buffer ) < sendLen + 2 )
304 printHex( sendLen + 2 );
312 // If buffer is clean, return 1, otherwise 2
313 reTurn = buffer->head == buffer->tail ? 1 : 2;
315 // Add to buffer, already know there is enough room (simplifies adding logic)
316 uint8_t bufferHeaderPos = 0;
317 for ( uint16_t c = 0; c < sendLen; c++ )
319 // Add data to buffer
320 switch ( bufferHeaderPos )
323 buffer->buffer[ buffer->tail ] = recvLen;
329 buffer->buffer[ buffer->tail ] = sendLen;
335 buffer->buffer[ buffer->tail ] = data[ c ];
339 // Check for wrap-around case
340 if ( buffer->tail + 1 >= buffer->size )
355 inline uint16_t I2C_BufferLen( I2C_Buffer *buffer )
358 if ( buffer->tail >= buffer->head )
359 return buffer->head + buffer->size - buffer->tail;
362 return buffer->head - buffer->tail;
366 void I2C_BufferPush( uint8_t byte, I2C_Buffer *buffer )
368 // Make sure buffer isn't full
369 if ( buffer->tail + 1 == buffer->head || ( buffer->head > buffer->tail && buffer->tail + 1 - buffer->size == buffer->head ) )
371 warn_msg("I2C_BufferPush failed, buffer full: ");
377 // Check for wrap-around case
378 if ( buffer->tail + 1 >= buffer->size )
388 // Add byte to buffer
389 buffer->buffer[ buffer->tail ] = byte;
393 uint8_t I2C_TxBufferPop()
395 // Return 0xFF if no buffer left (do not rely on this)
396 if ( I2C_BufferLen( (I2C_Buffer*)&I2C_TxBuffer ) >= I2C_TxBuffer.size )
398 erro_msg("No buffer to pop an entry from... ");
399 printHex( I2C_TxBuffer.head );
401 printHex( I2C_TxBuffer.tail );
403 printHex( I2C_TxBuffer.sequencePos );
408 // If there is currently no sequence being sent, the first entry in the RingBuffer is the length
409 if ( I2C_TxBuffer.sequencePos == 0 )
411 I2C_TxBuffer.sequencePos = 0xFF; // So this doesn't become an infinite loop
412 I2C_RxBuffer.sequencePos = I2C_TxBufferPop();
413 I2C_TxBuffer.sequencePos = I2C_TxBufferPop();
416 uint8_t data = I2C_TxBuffer.buffer[ I2C_TxBuffer.head ];
422 if ( I2C_TxBuffer.head >= I2C_TxBuffer.size )
423 I2C_TxBuffer.head = 0;
425 // Decrement buffer sequence (until next stop will be sent)
426 I2C_TxBuffer.sequencePos--;
429 dbug_msg("Popping: ");
432 printHex( I2C_TxBuffer.head );
434 printHex( I2C_TxBuffer.tail );
436 printHex( I2C_TxBuffer.sequencePos );
443 uint8_t I2C_Send( uint8_t *data, uint8_t sendLen, uint8_t recvLen )
445 // Check head and tail pointers
447 // If empty, start up I2C Master Tx
448 // If buffer is non-empty and non-full, just append to the buffer
449 switch ( I2C_BufferCopy( data, sendLen, recvLen, (I2C_Buffer*)&I2C_TxBuffer ) )
451 // Not enough buffer space...
454 erro_msg("Not enough Tx buffer space... ");
455 printHex( I2C_TxBuffer.head );
457 printHex( I2C_TxBuffer.tail );
461 printHex( I2C_TxBuffer.size );
466 // Empty buffer, initialize I2C
468 // Clear status flags
469 I2C0_S = I2C_S_IICIF | I2C_S_ARBL;
471 // Check to see if we already have control of the bus
472 if ( I2C0_C1 & I2C_C1_MST )
474 // Already the master (ah yeah), send a repeated start
475 I2C0_C1 = I2C_C1_IICEN | I2C_C1_MST | I2C_C1_RSTA | I2C_C1_TX;
477 // Otherwise, seize control
480 // Wait...till the master dies
481 while ( I2C0_S & I2C_S_BUSY );
483 // Now we're the master (ah yisss), get ready to send stuffs
484 I2C0_C1 = I2C_C1_IICEN | I2C_C1_MST | I2C_C1_TX;
487 // Enable I2C interrupt
488 I2C0_C1 = I2C_C1_IICEN | I2C_C1_IICIE | I2C_C1_MST | I2C_C1_TX;
490 // Depending on what type of transfer, the first byte is configured for R or W
491 I2C0_D = I2C_TxBufferPop();
496 // Dirty buffer, I2C already initialized
502 // LED State processing loop
503 inline uint8_t LED_loop()
514 inline void Scan_setup()
516 // Register Scan CLI dictionary
517 CLI_registerDictionary( scanCLIDict, scanCLIDictName );
519 // Setup GPIO pins for matrix scanning
530 // Main Detection Loop
531 inline uint8_t Scan_loop()
533 //Matrix_scan( Scan_scanCount++ );
540 // Signal from Macro Module that all keys have been processed (that it knows about)
541 inline void Scan_finishedWithMacro( uint8_t sentKeys )
546 // Signal from Output Module that all keys have been processed (that it knows about)
547 inline void Scan_finishedWithOutput( uint8_t sentKeys )
549 // Reset scan loop indicator (resets each key debounce state)
550 // TODO should this occur after USB send or Macro processing?
555 // ----- CLI Command Functions -----
557 // XXX Just an example command showing how to parse arguments (more complex than generally needed)
558 void cliFunc_echo( char* args )
562 char* arg2Ptr = args;
564 // Parse args until a \0 is found
567 print( NL ); // No \r\n by default after the command is entered
569 curArgs = arg2Ptr; // Use the previous 2nd arg pointer to separate the next arg from the list
570 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
572 // Stop processing args if no more are found
573 if ( *arg1Ptr == '\0' )
581 void cliFunc_i2cSend( char* args )
585 char* arg2Ptr = args;
587 // Buffer used after interpretting the args, will be sent to I2C functions
588 // NOTE: Limited to 8 bytes currently (can be increased if necessary
589 #define i2cSend_BuffLenMax 8
590 uint8_t buffer[ i2cSend_BuffLenMax ];
591 uint8_t bufferLen = 0;
593 // No \r\n by default after the command is entered
595 info_msg("Sending: ");
597 // Parse args until a \0 is found
598 while ( bufferLen < i2cSend_BuffLenMax )
600 curArgs = arg2Ptr; // Use the previous 2nd arg pointer to separate the next arg from the list
601 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
603 // Stop processing args if no more are found
604 if ( *arg1Ptr == '\0' )
607 // If | is found, end sequence and start new one
608 if ( *arg1Ptr == '|' )
611 I2C_Send( buffer, bufferLen, 0 );
616 // Interpret the argument
617 buffer[ bufferLen++ ] = (uint8_t)numToInt( arg1Ptr );
626 I2C_Send( buffer, bufferLen, 0 );
629 void cliFunc_i2cRecv( char* args )
633 char* arg2Ptr = args;
635 // Buffer used after interpretting the args, will be sent to I2C functions
636 // NOTE: Limited to 8 bytes currently (can be increased if necessary
637 #define i2cSend_BuffLenMax 8
638 uint8_t buffer[ i2cSend_BuffLenMax ];
639 uint8_t bufferLen = 0;
641 // No \r\n by default after the command is entered
643 info_msg("Sending: ");
645 // Parse args until a \0 is found
646 while ( bufferLen < i2cSend_BuffLenMax )
648 curArgs = arg2Ptr; // Use the previous 2nd arg pointer to separate the next arg from the list
649 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
651 // Stop processing args if no more are found
652 if ( *arg1Ptr == '\0' )
655 // If | is found, end sequence and start new one
656 if ( *arg1Ptr == '|' )
659 I2C_Send( buffer, bufferLen, 0 );
664 // Interpret the argument
665 buffer[ bufferLen++ ] = (uint8_t)numToInt( arg1Ptr );
674 I2C_Send( buffer, bufferLen, 1 ); // Only 1 byte is ever read at a time with the ISSI chip
677 void cliFunc_ledZero( char* args )
679 print( NL ); // No \r\n by default after the command is entered
680 LED_zeroPages( 0x00, 8, 0xB3 );