Skip to content

Instantly share code, notes, and snippets.

@ArdWar
Created December 7, 2022 12:42
Show Gist options
  • Save ArdWar/47e73c7dd6bda8f602bddcb8bbd311f1 to your computer and use it in GitHub Desktop.
Save ArdWar/47e73c7dd6bda8f602bddcb8bbd311f1 to your computer and use it in GitHub Desktop.
I2C Slave
#include "main.h"
#define I2C_DEVICE_NODE DT_NODELABEL(i2c1)
#define UART_DEVICE_NODE DT_NODELABEL(usart1)
#define LED0_NODE DT_ALIAS(led0)
static const struct device *const i2c_dev = DEVICE_DT_GET(I2C_DEVICE_NODE);
static const struct device *const uart_dev = DEVICE_DT_GET(UART_DEVICE_NODE);
static const struct gpio_dt_spec led = GPIO_DT_SPEC_GET(LED0_NODE, gpios);
char fifo_tx[128];
int txlen = 0;
char fifo_rx[128];
uint8_t i2c_rx[128];
uint8_t i2c_rxlen = 0;
void serial_cb(const struct device *dev, void *user_data)
{
if (uart_irq_tx_ready(uart_dev)) {
if (--txlen > 0) {
uart_fifo_fill(uart_dev, &fifo_tx[txlen], 1);
} else {
uart_irq_tx_disable(uart_dev);
}
}
if (uart_irq_rx_ready(uart_dev)) {
uart_fifo_read(uart_dev, fifo_rx, 1);
}
}
void sertx(char *dat, int len) {
for(len; len >= 0;) {
fifo_tx[txlen++] = dat[len--];
}
uart_irq_tx_enable(uart_dev);
}
int wrreq_cb(struct i2c_target_config *config){
gpio_pin_set_dt(&led, 1);
i2c_rxlen = 0;
return 0;
}
int rdreq_cb(struct i2c_target_config *config, uint8_t *val){}
int wrrec_cb(struct i2c_target_config *config, uint8_t val){
i2c_rx[i2c_rxlen++] = val;
return 0;
}
int rdpro_cb(struct i2c_target_config *config){}
int stop_cb(struct i2c_target_config *config){
sertx(i2c_rx, i2c_rxlen);
gpio_pin_set_dt(&led, 0);
return 0;
}
struct i2c_target_callbacks i2ccb = {
wrreq_cb,
rdreq_cb,
wrrec_cb,
rdpro_cb,
stop_cb,
};
struct i2c_target_config i2ccfg;
void main(void) {
i2ccfg.address = 0x29;
i2ccfg.callbacks = &i2ccb;
uart_irq_callback_user_data_set(uart_dev, serial_cb, NULL);
uart_irq_rx_enable(uart_dev);
i2c_target_register(i2c_dev, &i2ccfg);
gpio_pin_configure_dt(&led, GPIO_OUTPUT_ACTIVE);
while (1) {
k_sleep(K_MSEC(1));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment