#include “mbed.h”
Serial uart4(PB_6, PA_10);
#define DEBUG 1 // change value to 1 to enable debuging using serial monitor
//---------for delay----------------------------------------------
unsigned long previousTime = 0;
//-------CO2 Variable and calibration command, co2 concentration declaration.----------------------------------#define INTERVAL 5000
unsigned int response [9];
int packetlenght =9;
typedef unsigned char byte;
const byte *mhzResp[9]; // 9 bytes bytes response
const byte mhzCmdCalibrateZero[9] = {0xFF,0x01,0x87,0x00,0x00,0x00,0x00,0x00,0x78};
const byte mhzCmdABCEnable[9] = {0xFF,0x01,0x79,0xA0,0x00,0x00,0x00,0x00,0xE6};
const byte mhzCmdABCDisable[9] = {0xFF,0x01,0x79,0x00,0x00,0x00,0x00,0x00,0x86};
const byte mhzCmdMeasurementRange5000[9] = {0xFF,0x01,0x99,0x00,0x00,0x00,0x13,0x88,0xCB};
int shifts=0,co2ppm;
long previousMillis = 0;
unsigned int checksum (unsigned int response[9]){
unsigned int crc = 0;
for (int i = 1; i < 8; i++) {
crc += response[i];
}
crc = 255 - crc + 1;
return crc;
}
void disableABC() {
uart4.write(mhzCmdABCDisable, 9, false);
}
void enableABC() {
uart4.write(mhzCmdABCEnable, 9, false);
}
void setRange5000() {
uart4.write(mhzCmdMeasurementRange5000, 9, false);
}
void calibrateZero(){
uart4.write(mhzCmdCalibrateZero, 9, false);
}
int readCO2() {
byte cmd[9] = {0xFF, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79};
uart4.write(cmd, 9, false);
while(uart4.readable()) {
uart4.getc();
shifts++;
}
memset(response, 0, 9);
uart4.putc(packetlenght[response]);
for (int i=0; i<9; i++) {
//Serial.print(" 0x");
//Serial.print(response[i], HEX);
}
if (response[1] != 0x86)
{
printf(" Invalid response from co2 sensor! \n\r");
return -1;
}
if (response[8] == checksum(response)) {
int responseHigh = (int) response[2];
int responseLow = (int) response[3];
int ppm = (256 * responseHigh) + responseLow;
return ppm;
} else
{
printf(“CRC error!\n\r”);
return -1;
}
}
//----------------Timers auxiliar variables--------------------
Timer timer;
long now = timer.read_ms();
long lastMeasure = 0;
DigitalOut myled(LED1);
int main() {
uart4.baud(9600); // Setting baud rate to 9600
int i = 1;
printf(“Hello World !”);
while(1) {
wait(1);
unsigned long currentMillis = now;
if (co2ppm > 10000) {
printf(“Zero was calibrated \n\r”);
// disableABC();
wait(1800000);
//calibrateZero();
enableABC();
}
else if ((currentMillis - previousMillis) > INTERVAL) {
previousMillis = currentMillis;
co2ppm=-999;
co2ppm = readCO2();
}
printf(“CO2= %d.\n\r”, co2ppm);
i++;
myled = !myled;
}
}
here i am interfacing the mhz-14a co2 sensor with nucleo L152re board and co2 sensor is working on uart communication, this code is error free and gives the co2 value is 0 in all time.please help me where is problem in my code as soon as possible.