/*
 * i2c.h
 *
 *  Created on: Oct 13, 2024
 *      Author: true
 */

#ifndef USER_COMM_I2C_H_
#define USER_COMM_I2C_H_



#include "global.h"


#ifdef SOFT_I2C_MASTER


#include "soft_i2c_master.h"

/* known bugs / limitations:
 * - there is no ack on address. code always assumes slave is responding.
 */
#define i2c_init()          i2cm_init()
#define i2c_start()         { SetSysClock(SYSCLK_FREQ_USEI2C); i2cm_start(); }
#define i2c_restart()       i2cm_restart()
#define i2c_stop()          { i2cm_stop(); SetSysClock(SYSCLK_FREQ_NORMAL); }
#define i2c_rd(ack)         i2cm_rd(ack)
#define i2c_wr(dat)         i2cm_wr(dat)
#define i2c_addr(a, w)      i2c_start(); i2cm_addr(a, w)

#define i2c_rdbuf(d, s)     i2cm_rdbuf(d, s); i2c_stop()
#define i2c_wrbuf(d, s)     i2cm_wrbuf(d, s); i2c_stop()


#define i2c_read(a, d, s)   i2c_start();            \
                            i2cm_addr(a, 1);        \
                            i2cm_rdbuf(d, s);       \
                            i2c_stop()

#define i2c_read_reg8(a, r, d, s)   i2c_start();    \
                            i2cm_addr(a, 0);        \
                            i2cm_wr(r);             \
                            i2cm_restart();         \
                            i2cm_addr(a, 1);        \
                            i2cm_rdbuf(d, s);       \
                            i2c_stop()

#define i2c_read_reg16(a, r, d, s)  i2c_start();    \
                            i2cm_addr(a, 0);        \
                            i2cm_wr(r >> 8);        \
                            i2cm_wr(r & 0xff);      \
                            i2cm_restart();         \
                            i2cm_addr(a, 1);        \
                            i2cm_rdbuf(d, s);       \
                            i2c_stop()


#define i2c_write(a, d, s)  i2c_start();            \
                            i2cm_addr(a, 0);        \
                            i2cm_wrbuf(d, s);       \
                            i2c_stop()

#define i2c_write_reg8(a, r, d, s)  i2c_start();    \
                            i2cm_addr(a, 0);        \
                            i2cm_wr(r);             \
                            i2cm_wrbuf(d, s);       \
                            i2c_stop()

#define i2c_write_reg16(a, r, d, s) i2c_start();    \
                            i2cm_addr(a, 0);        \
                            i2cm_wr(r >> 8);        \
                            i2cm_wr(r & 0xff);      \
                            i2cm_wrbuf(d, s);       \
                            i2c_stop()


#else


#error HW I2C NOT YET IMPLEMENTED!


#endif



#endif /* USER_COMM_I2C_H_ */
