The I2C interface is a software bit-banging system using PIO bits PA1 for SCL and PA2 for SDA. The initialisation code sets up these bits as open drain outputs.
The driver code in I2CEB55DRV.FTH must be compiled before the generic drive code in I2CBASE.FTH and the device specific files (e.g. AT24C512.FTH) are compiled.
0 equ TestI2C? \ -- n
Set this equate non-zero to include the test code at the end of the file. This equate also controls the compilation of I2C test code in other files.
: initI2C \ --
Initialise the I2C hardware.
20 equ I2CPeriod \ -- us
Define the I2C bit time in microseconds.
I2Cperiod system-speed 1000000 */ equ I2Cclocks \ -- n
The number of CPU clocks in a bit time.
10 equ clocks/ins \ -- n
The number of CPU clocks per instruction. Tune this to your hardware set up (memory width and speed)
12 clocks/ins * equ clocks/DO
the number of clocks needed to execute DO at the start of DO..LOOP including parameter passing.
3 clocks/ins * equ clocks/LOOP
the number of clocks needed to execute LOOP at the end of DO..LOOP.
I2Cclocks 4 / clocks/DO - clocks/LOOP / equ /I2Cqbit \ -- n
The number n for "n 0 DO LOOP" to generate an I2C quarter bit time.
: I2Cdelay \ --
Wait one quarter of an I2C bit. Tune the equates above for a one quarter bit time.
: read_scl \ -- bit
Read SCL bit and return in l.s. bit. No delays.
: write_scl \ b -- ; output clock bit
Write to SCL with no delays.
: SCL_low \ --
Set SCL low. A quarter cycle delay is performed before and after the transition.
: SCL_high \ --
Set SCL high. A quarter cycle delay is performed before and after the transition.
: read_sda \ -- bit
Read SCL bit and return in l.s. bit.
: write_sda \ b -- ; output to SDA
Write the SDA bit.
: sda_low \ --
Set SDA low.
: sda_high \ --
Set SDA high.