I'm using a STM32F030 board to communicate with a LSM303D sensor board via I2C using the ChibiOS I2CDriver. I want to read data periodically from the sensor. Everything works fine as long as I use the main thread for the I2C communication. Now I tried to create a second thread to read the data. But this second thread gets stuck on the i2cMasterTransmit method.
Here is the code that I used:
Code: Select all
#include <hal.h>
#include <ch.hpp>
using namespace chibios_rt;
#define DEVICE_ADR 0x1D
#define CTRL1_SETTINGS 0x07
static THD_WORKING_AREA(waThd1, 128);
static I2CConfig i2cdConfig = {
STM32_TIMINGR_PRESC(0xBU) | // fI2CCLK = 48MHz
STM32_TIMINGR_SCLDEL(0x4U) | STM32_TIMINGR_SDADEL(0x2U) |
STM32_TIMINGR_SCLH(0xC3U) | STM32_TIMINGR_SCLL(0xC7U),
0,
0
};
void configureAccelerometer(uint16_t freq) {
uint8_t writeBuffer[2];
writeBuffer[0] = 0x20;
writeBuffer[1] = (freq << 4) | CTRL1_SETTINGS;
i2cMasterTransmit(&I2CD1, DEVICE_ADR, writeBuffer, 2, NULL, 0);
}
static THD_FUNCTION(thd1, arg) {
(void) arg;
while(true) {
uint8_t subAddr = 0x0F; // WHO_AM_I register
uint8_t receiveBuffer;
i2cMasterTransmit(&I2CD1, DEVICE_ADR, &subAddr, 1 , &receiveBuffer, 1);
chThdSleepMilliseconds(1000);
}
}
int main() {
halInit();
System::init();
i2cStart(&I2CD1, &i2cdConfig);
configureAccelerometer(10); // 10 = frequency 1600 Hz
chThdCreateStatic(waThd1, sizeof(waThd1), NORMALPRIO + 1, thd1, NULL);
while(true) {}
}With the code I try to read the WHO_AM_I register.
If I move the while loop to the main thread the read is successful and the correct value (0x49) is returned. I also made sure that the THD_FUNCTION is executed (I was able to blink an LED with it). Just the I2C communication won't work.
I'm quite new to multithreading in ChibiOS, so forgive me if I made a rookie mistake
Thanks in advance for your help
Jan