Created
May 24, 2020 09:32
-
-
Save matoushybl/4137cfc563f7de3e4e29d68f86e299d1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define BUFFER_SIZE 10 | |
enum SlaveMode { | |
Receiving, | |
Transmitting, | |
Listening | |
} slaveMode = Listening; | |
uint8_t receivingBuffer[BUFFER_SIZE] = {0}; | |
uint8_t receivingBufferDataSize = 0; | |
uint8_t transmittingBuffer[BUFFER_SIZE] = {0}; | |
uint8_t transmittingBufferDataSize = 0; | |
void transmit(const uint8_t *data, uint8_t dataSize) { | |
if (dataSize > BUFFER_SIZE) { | |
dataSize = BUFFER_SIZE; | |
} | |
for (int i = 0; i < dataSize; ++i) { | |
transmittingBuffer[i] = data[i]; | |
} | |
transmittingBufferDataSize = dataSize; | |
} | |
void HAL_I2C_AddrCallback(I2C_HandleTypeDef *hi2c, uint8_t transferDirection, uint16_t addressMatchCode) { | |
if (transferDirection == I2C_DIRECTION_RECEIVE) { | |
slaveMode = Transmitting; | |
transmittingBuffer[0] = 0x55; | |
transmittingBufferDataSize = 1; | |
HAL_I2C_Slave_Seq_Transmit_DMA(hi2c, transmittingBuffer, transmittingBufferDataSize, I2C_LAST_FRAME); | |
} else { | |
slaveMode = Receiving; | |
HAL_I2C_Slave_Seq_Receive_DMA(hi2c, receivingBuffer + receivingBufferDataSize, 1, I2C_NEXT_FRAME); | |
} | |
} | |
void HAL_I2C_ListenCpltCallback(I2C_HandleTypeDef *hi2c) { | |
slaveMode = Listening; | |
receivingBufferDataSize = 0; | |
HAL_I2C_EnableListen_IT(hi2c); | |
} | |
void HAL_I2C_SlaveRxCpltCallback(I2C_HandleTypeDef *hi2c) { | |
if (receivingBufferDataSize >= BUFFER_SIZE) { | |
return; | |
} | |
receivingBufferDataSize++; | |
if (slaveMode == Receiving) { | |
HAL_I2C_Slave_Seq_Receive_DMA(hi2c, receivingBuffer + receivingBufferDataSize, 1, I2C_NEXT_FRAME); | |
} | |
} | |
void HAL_I2C_SlaveTxCpltCallback(I2C_HandleTypeDef *hi2c) { | |
transmittingBufferDataSize = 0; | |
} | |
void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c) { | |
HAL_I2C_EnableListen_IT(hi2c); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment