2024-06-14 12:28 PM - last edited on 2024-06-25 07:12 AM by Amel NASRI
Good evening, I ask for help regarding the communication between stm32wb5mmght6tr and the scd41-d-r2 sensor.
I connected the sensor to pins PC0 (SCL) and PC1 (SDA) and powered the sensor but after loading the code I attach, the i2c communication gives me an error (they don't communicate). I checked the address of the sensor and it is correct and also the connections. Anyone know what it could be? Thank you in advance.
Codice:
#include "i2c.h"
#include "gpio.h"
#include "CO2.h"
#include "main.h"
#include <stdio.h>
#define SCD41_ADDR (0x62 << 1) // Indirizzo I2C del SCD41
// Comandi SCD41
#define SCD41_CMD_START_MEASUREMENT 0x21B1
#define SCD41_CMD_READ_MEASUREMENT 0xEC05
extern I2C_HandleTypeDef hi2c3; // periferica I2C utilizzata
// Funzione per iniziare la misurazione del SCD41
void SCD41_Start_Measurement() {
uint8_t cmd[2] = {SCD41_CMD_START_MEASUREMENT >> 8, SCD41_CMD_START_MEASUREMENT & 0xFF};
HAL_I2C_Master_Transmit(&hi2c3, SCD41_ADDR, cmd, 2, HAL_MAX_DELAY);
}
// Funzione per leggere i dati dal SCD41 (CO2, temperatura e umidità)
void SCD41_Read_Measurements(uint16_t *co2, float *temperature, float *humidity) {
uint8_t cmd[2] = {SCD41_CMD_READ_MEASUREMENT >> 8, SCD41_CMD_READ_MEASUREMENT & 0xFF};
uint8_t data[9];
// Invia il comando di lettura misurazione
HAL_I2C_Master_Transmit(&hi2c3, SCD41_ADDR, cmd, 2, HAL_MAX_DELAY);
// Attendi il completamento della misurazione (circa 50ms)
HAL_Delay(50);
// Leggi i dati dal sensore
HAL_I2C_Master_Receive(&hi2c3, SCD41_ADDR, data, 9, HAL_MAX_DELAY);
// Estrai i valori di CO2, temperatura e umidità
*co2 = (data[0] << | data[1];
uint16_t raw_temperature = (data[3] << | data[4];
uint16_t raw_humidity = (data[6] << | data[7];
// Converti i valori grezzi di temperatura e umidità in valori reali
*temperature = -45.0f + 175.0f * ((float)raw_temperature / 65535.0f);
*humidity = 100.0f * ((float)raw_humidity / 65535.0f);
// Arrotonda temperatura e umidità a due cifre decimali
*temperature = (int)((*temperature) * 100.0f + 0.5f) / 100.0f;
*humidity = (int)((*humidity) * 100.0f + 0.5f) / 100.0f;
}
int main_fumo(void) {
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_I2C3_Init();
// Avvia la misurazione
SCD41_Start_Measurement();
uint16_t co2;
float temperature, humidity;
while (1) {
SCD41_Read_Measurements(&co2, &temperature, &humidity);
HAL_Delay(5000); // Intervallo tra le misurazioni (es. 5s)
}
return 0; // Non dovrebbe mai essere raggiunto
}