feat: I2C drivers

This commit is contained in:
2026-03-05 17:37:20 +00:00
parent 393128c197
commit 5a7d3a9864
20 changed files with 3836 additions and 8682 deletions

View File

@@ -1,7 +1,87 @@
#include "main.h"
#include "i2c.h"
#include "stm32f411xe.h"
#include "stm32f4xx_hal.h"
#include "stm32f4xx_hal_gpio.h"
#include "stm32f4xx_ll_i2c.h"
#include "gen_wrapper.h"
#include "circular_buffer.h"
#define CIRC_BUF_SIZE (2*1024)
CIRCULAR_BUFFER_ALL(circ_buff, uint8_t, CIRC_BUF_SIZE)
static volatile circ_buff_t i2c_buf;
void I2C1_EV_IRQHandler()
{
if (!LL_I2C_IsActiveFlag_ADDR(I2C1))
Error_Handler();
//Skip checking matched addr (should only be one)
//Skip checking if receiving or transmitting (should always be false)
LL_I2C_ClearFlag_ADDR(I2C1);
//Allow buffer to grow until full
while (i2c_buf.count < _CB_COUNT(&i2c_buf))
{
//Wait for data or stop flag
while (!LL_I2C_IsActiveFlag_STOP(I2C1) && !LL_I2C_IsActiveFlag_RXNE(I2C1));
if (LL_I2C_IsActiveFlag_STOP(I2C1))
{
LL_I2C_ClearFlag_STOP(I2C1);
break;
}
else //Data received
{
uint8_t data = LL_I2C_ReceiveData8(I2C1);
circ_buff_append_range(&i2c_buf, &data, 1);
}
}
//Overflow or stop condition reached
if (i2c_buf.count >= _CB_COUNT(&i2c_buf))
Error_Handler();
}
bool I2C1_transmit_master(uint8_t addr, uint8_t *buf, uint8_t count)
{
while (LL_I2C_IsActiveFlag_BUSY(I2C1));
//Transmit start
LL_I2C_GenerateStartCondition(I2C1);
while (!LL_I2C_IsActiveFlag_SB(I2C1));
//Transmit address + write
LL_I2C_TransmitData8(I2C1, addr << 1);
while (!LL_I2C_IsActiveFlag_ADDR(I2C1));
LL_I2C_ClearFlag_ADDR(I2C1);
for (int i = 0; i < count; ++i)
{
while (!LL_I2C_IsActiveFlag_TXE(I2C1));
if (LL_I2C_IsActiveFlag_AF(I2C1))
{
//REVIEW: Anything else neeeded?
LL_I2C_Disable(I2C1);
LL_I2C_Enable(I2C1);
return false;
}
LL_I2C_TransmitData8(I2C1, buf[i]);
}
LL_I2C_GenerateStopCondition(I2C1);
while (LL_I2C_IsActiveFlag_STOP(I2C1));
LL_I2C_Disable(I2C1);
LL_I2C_Enable(I2C1);
return true;
}
int my_main()
{