Just spent a few days creating a 12c state engine 18f25k42 (would suit all K42 microcontrollers).
The library provides an ISR to implement of am state I2C hardware slave for these microcontrollers.
This is a Great Cow BASIC implementation of Microchip Application Note AN734 and TB3159 but this is easily, very easily, portable... now I have got it working.
The library and the demonstration responds to a write and reads of bytes to I2C address (the four K42 addresses are supported).
According to AN734, there are 5 possible I2C states, however there is an additional state that is required when AN734 is implemented in anger.
During defined ISR, each 'of these states are detected. The ISR provides a standard skeleton to implement an I2C hardware slaves, while client code must implement several callbacks the ISR is expecting to call while processing states.
Callbacks:
HI2C_Process_In_Message ( in HI2CMESSAGESIZE as byte ) called when slave has recieved a complete I2C write packet
HI2C_Process_Out_Message called when slave is requested to respond to a masters request, the slave needs to send an I2C packet.
In my test code I have a Pot attached and 4 LEDS. The Master will request the value of the Pot and then, the Master will set 3 LEDs to the proportional value of the Pot - and, the Master will set the LEDS to the same value - these LEDs are attached the Master microcontroller.
The test code supports two transactions but this can be easily expanded to support 100s of transaction types.
Transaction #1. Master send I2C packet to address, address, value. as follows to set the LEDs:
0x70, 0x23, 0x00 - turn off all the LEDS
0x70, 0x23, 0x01 - turn on one LED
0x70, 0x23, 0x02 - turn on one LED
0x70, 0x23, 0x03 - turn on two LEDs
0x70, 0x23, 0x04..0xff - turn on LEDs
Transaction #2. Master wants to read the value of the ADC
0x70, 0x81, 0x04, 0x71, 0xNN. Where 0x81 will instruct this slave to read the ADC, where 0x04 equates to ADC4 and then the READ operation will return the single byte value of the Slave ADC to the Master. Any other ADC port request will be returned as 0x00.
To add your own slave commands - simply expand these the example methods.
Findings
AN734 is a very useful architecture of how to create a state engine.
TB3159 is useful but pointless. TB3159 contains three serious errors but at least you can get the microntroller to respond to I2C discovery.
The Great Cow BASIC library, which is based upon the 'Legacy I2C module', shows a reference solution that uses AN734 and completes the approach provided in TB3159.
See
https://sourceforge.net/p/gcbasic/discussion/629990/thread/310f10c6/?limit=250#216d for more details.
Thank you.
This thread helped me adapt the existing 'Legacy I2C module' library to support K42 I2C module. With this thread I would have been unable to complete.