cnlohr / ch32v003fun

Open source minimal stack for the ch32 line of WCH processors, including the ch32v003, a 10¢ 48 MHz RISC-V Microcontroller - as well as many other chips within the ch32v/x line.
MIT License
971 stars 148 forks source link

[proposal] Library with common base I2C functions #200

Open panciunio opened 1 year ago

panciunio commented 1 year ago

Just now I'm working on easy project which shall read some data from I2C bus and provide the results on display (also connected via I2C). There is two example related to I2C but one is concerned to hardware so deep.. and second example shown SLAVE mode.

It's little bit hard to understand how to connect other devices with own driver - e.g. I wrote in the past working code for RTC (PCF8583) dedicated to AVR and I want to rewrite it for RISC-V...

In case, I need some elementary functions/methods like:

// Prototypes: 
void TWI_init(void);
void    TWI_start(void);
void    TWI_stop(void);
uint8_t TWI_read(uint8_t ack);
void  TWI_write(uint8_t data);

It will be very easy to write driver related to any I2C device... for example for my PCF8583 read method:

uint8_t PCF8583_read(unsigned char address, unsigned char register)
{
uint8_t data;                   
    TWI_start();                                     // START sequence
    TWI_write(address)                         // send device's address
    TWI_write(register);                         // send register's address

    TWI_start();                    // START sequence
    TWI_write(address | 0x01);             // send device's address in read mode
    data = TWI_read(0);                        // read dat adrom I2C device and NACK
    TWI_stop();                                      // STOP sequence

    return data;                    
}
comps commented 2 months ago

I also ran into this - wanted to use a ch32v003 as a one-shot i2c configurator for a PMIC (current limits, various settings, etc.) and discovered that there's no easy API for it.

The only example I found is using low-level registers like ssd1306_i2c.h does, but nothing as straightfoward as Arduino's

Wire.begin();
Wire.beginTransmission(0x61);  // target
Wire.write(0xd1);  // CURRENT_LIMIT
Wire.write(0b11001111);  // 750mA
Wire.endTransmission();
prosper00 commented 2 months ago

Though not quite as simplified-down as Arduino, check out https://github.com/ADBeta/CH32V003_lib_i2c