byte i2c_addr ' device address byte i2c_ack ' byte i2c_data ' byte i2c_sreg byte i2c_sval ' ' initialize the i2c assuming 400Hz xfer speed ' proc i2c_init() _sspadd = _freq / 400 / 4 - 1 _sspstat = _sspstat & ~%11000000 ' i2c input levels _trisc = _trisc | %00011000 ' SCL/SDA are inputs _sspcon = %00111000 ' master mode, ssp enable end proc ' ' wait for the i2c bus to go idle ' proc i2c_wait_for_idle() ' wait for write complete while _sspstat & (1 << _r_w) ' empty loop end while ' wait for 0 status while _sspcon2 & $1f ' empty loop end while end proc ' ' start condition enable ' proc i2c_start() call i2c_wait_for_idle() _sspcon2 = _sspcon2 | (1 << _SEN) end proc ' ' repeating start condition enable ' proc i2c_rep_start() call i2c_wait_for_idle() _sspcon2 = _sspcon2 | (1 << _RSEN) end proc ' ' stop ' proc i2c_stop() call i2c_wait_for_idle() _sspcon2 = _sspcon2 | (1 << _PEN) end proc ' ' read some data, set i2c_ack to 0 for no ACK, ' non-0 for ACK. result is in i2c_data ' proc i2c_read(i2c_ack) call i2c_wait_for_idle() _sspcon2 = _sspcon2 | (1 << _RCEN) call i2c_wait_for_idle() i2c_data = _sspbuf call i2c_wait_for_idle() if (i2c_ack) then _sspcon2 = _sspcon2 & ~(1 << _ackdt) else _sspcon2 = _sspcon2 | (1 << _ackdt) end if _sspcon2 = _sspcon2 | (1 << _acken) end proc ' ' write some data ' on exit, i2c_ack is 1 if acknowledged, 0 if not ' proc i2c_write(i2c_data) 'print "i2c_write(", i2c_data, ")\r\n" call i2c_wait_for_idle() _sspbuf = i2c_data i2c_ack = !(_sspcon2 & _ackstat) end proc