Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

#include <SoftwareSerial.

h>

SoftwareSerial espSerial(2, 3); // Arduino RX pin to ESP8266 module TX pin

String apiKey = "E2YE5I4TGU4RUB5U"; // Replace with your ThingSpeak API key


String ssid = "BestProject"; // WiFi network SSID
String password = "12345678"; // WiFi network password

const int gasSensorPin = A0; // Gas sensor MQ8 pin connected to Arduino A0 pin

void setup() {
Serial.begin(9600);

espSerial.begin(9600); // Enable software serial


// Connect to WiFi network
espSerial.println("AT+CWJAP=\"" + ssid + "\",\"" + password + "\"");
delay(8000); // Wait for connection
}

void loop() {
// Read gas sensor data
int gasValue = analogRead(gasSensorPin);
float gasPercentage = map(gasValue, 0, 1023, 0, 100); // Convert raw sensor
value to percentage

// Call sendDataToThingSpeak function with gas sensor data included


sendDataToThingSpeak(gasPercentage, 0, 0, 0);

// Your additional code logic goes here


}

void sendDataToThingSpeak(float value1, float value2, float value3, float value4)


{
String cmd = "AT+CIPSTART=\"TCP\",\"api.thingspeak.com\",80";
espSerial.println(cmd);
delay(500);

if (espSerial.find("Error")) {
Serial.println("AT+CIPSTART error");
return;
}

String getStr = "GET /update?api_key=" + apiKey;


getStr += "&field1=" + String(value1);
String sendCmd = "AT+CIPSEND=";
espSerial.print(sendCmd);
espSerial.println(getStr.length());
delay(500);

if (espSerial.find(">")) {
espSerial.print(getStr);
} else {
espSerial.println("AT+CIPCLOSE");
Serial.println("AT+CIPCLOSE");
}
}

You might also like