Its now working. This is the code I used:
#include <SoftwareSerial.h>
const int pinTx = 7;
const int pinRx = 8;
int gas, temp;
SoftwareSerial sensor(pinTx, pinRx);
const unsigned char cmd_get_sensor[] = {
0xff, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79
};
const unsigned char cmd_calibrate[] = {
0xff, 0x87, 0x87, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf2
};
bool sendCmdGetDta(){
for (int i = 0; i < sizeof(cmd_get_sensor); i++) {
sensor.write(cmd_get_sensor[i]);
}
long cnt_timeout = 0;
while (!sensor.available()){ // wait for data
delay(1);
cnt_timeout++;
if (cnt_timeout > 1000)return 0; // time out
}
int len = 0;
byte dta[20];
while (sensor.available()){
dta[len++] = sensor.read();
}
if ((9 == len) && (0xff == dta[0]) && (0x86 == dta[1])){ // data ok
gas = 256 * (int)dta[2] + (int)dta[3];
temp = (int)dta[4] - 40;
return 1;
}
return 0;
}
void setup(){
Serial.begin(115200);
sensor.begin(9600);
}
void loop(){
if (sendCmdGetDta()){ // get data ok
Serial.print("gas_strength = ");
Serial.println(gas);
Serial.print("temperature = ");
Serial.println(temp);
// 350~450ppm: General outdoor environment
// 350~1000ppm:The air is fresh and breathing smooth
// 1000~2000ppm:The air was stagnant and feel asleep
// 5000ppm:Permissible exposure limit for an 8h work day
}
else{
Serial.println(“get data error”);
}
delay(1000);
}
void serialEvent(){
}