99 lines
2.7 KiB
C
99 lines
2.7 KiB
C
#include <stdio.h>
|
|
#include "pico/stdlib.h"
|
|
#include "pico/multicore.h"
|
|
#include "hardware/i2c.h"
|
|
#include "hardware/pwm.h"
|
|
#include "i2c_fifo.h"
|
|
#include "i2c_slave.h"
|
|
|
|
#define I2C0_SDA_PIN 18
|
|
#define I2C0_SCL_PIN 19
|
|
|
|
#define I2C_SLAVE_ADDRESS 0x10
|
|
|
|
static const uint I2C_SLAVE_SDA_PIN = I2C0_SDA_PIN;
|
|
static const uint I2C_SLAVE_SCL_PIN = I2C0_SCL_PIN;
|
|
|
|
// The slave implements a 256 byte memory. To write a series of bytes, the master first
|
|
// writes the memory address, followed by the data. The address is automatically incremented
|
|
// for each byte transferred, looping back to 0 upon reaching the end. Reading is done
|
|
// sequentially from the current memory address.
|
|
static struct
|
|
{
|
|
uint8_t mem[256];
|
|
uint8_t mem_address;
|
|
bool mem_address_written;
|
|
} context;
|
|
|
|
// Our handler is called from the I2C ISR, so it must complete quickly. Blocking calls /
|
|
// printing to stdio may interfere with interrupt handling.
|
|
static void i2c_slave_handler(i2c_inst_t *i2c, i2c_slave_event_t event) {
|
|
switch (event) {
|
|
case I2C_SLAVE_RECEIVE: // master has written some data
|
|
if (!context.mem_address_written) {
|
|
// writes always start with the memory address
|
|
context.mem_address = i2c_read_byte(i2c);
|
|
context.mem_address_written = true;
|
|
} else {
|
|
// save into memory
|
|
context.mem[context.mem_address] = i2c_read_byte(i2c);
|
|
context.mem_address++;
|
|
}
|
|
break;
|
|
case I2C_SLAVE_REQUEST: // master is requesting data
|
|
// load from memory
|
|
i2c_write_byte(i2c, context.mem[context.mem_address]);
|
|
context.mem_address++;
|
|
break;
|
|
case I2C_SLAVE_FINISH: // master has signalled Stop / Restart
|
|
context.mem_address_written = false;
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
}
|
|
|
|
void i2c_set_slave_mode_perso(i2c_inst_t *i2c, uint8_t addr) {
|
|
i2c->hw->enable = 0;
|
|
|
|
//while( !(i2c->hw->enable_status & 0x1) );
|
|
|
|
i2c->hw->sar = addr;
|
|
i2c->hw->con = 0;
|
|
|
|
i2c->hw->enable = 1;
|
|
}
|
|
|
|
static void setup_slave() {
|
|
gpio_init(I2C_SLAVE_SDA_PIN);
|
|
gpio_set_function(I2C_SLAVE_SDA_PIN, GPIO_FUNC_I2C);
|
|
gpio_pull_up(I2C_SLAVE_SDA_PIN);
|
|
|
|
gpio_init(I2C_SLAVE_SCL_PIN);
|
|
gpio_set_function(I2C_SLAVE_SCL_PIN, GPIO_FUNC_I2C);
|
|
gpio_pull_up(I2C_SLAVE_SCL_PIN);
|
|
|
|
i2c_slave_init(i2c0, I2C_SLAVE_ADDRESS, &i2c_slave_handler);
|
|
}
|
|
|
|
|
|
|
|
void main(void)
|
|
{
|
|
stdio_init_all();
|
|
setup_slave();
|
|
|
|
gpio_set_function(0, GPIO_FUNC_PWM);
|
|
uint slice_num = pwm_gpio_to_slice_num(0);
|
|
pwm_set_wrap(slice_num, 255);
|
|
pwm_set_enabled(slice_num, true);
|
|
|
|
while(1){
|
|
printf(">adc:%d\n", context.mem[0]);
|
|
pwm_set_chan_level(slice_num, PWM_CHAN_A, context.mem[0]);
|
|
sleep_ms(10);
|
|
}
|
|
}
|
|
|
|
|