1.
Program for sending a DIGITAL value to thingspeak
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
// --- Macro Definitions for Configuration ---
#define WIFI_SSID "ANITS"
#define WIFI_PASS "anits123"
#define THINGSPEAK_API_KEY "WGVG2C223R81XWP4" // REPLACE with your ThingSpeak Write API
Key
#define THINGSPEAK_SERVER "[Link]"
#define THINGSPEAK_FIELD_NUMBER "1"
#define PUSHBUTTON_PIN D3 // D3 corresponds to GPIO 0 on NodeMCU
// --- Globals ---
WiFiClient client;
// --- Setup ---
void setup() {
[Link](115200);
// Configure the pin: LOW=0 (Pressed), HIGH=1 (Unpressed)
pinMode(PUSHBUTTON_PIN, INPUT);
// Connect to WiFi
[Link]("\nConnecting to WiFi: ");
[Link](WIFI_SSID);
[Link](WIFI_SSID, WIFI_PASS);
while ([Link]() != WL_CONNECTED) {
delay(500);
[Link](".");
}
[Link]("\nWiFi connected!");
[Link]("IP Address: ");
[Link]([Link]());
}
// -------------------------------------------------------------------
// --- Loop ---
void loop() {
// 2. Read the pushbutton state (0 or 1)
int buttonState = digitalRead(PUSHBUTTON_PIN);
[Link]("\nButton State Read: ");
[Link](buttonState);
// 3. Connect to ThingSpeak if not already connected
if (![Link]()) {
[Link]("Connecting to ThingSpeak...");
if () {
[Link]("Connection to ThingSpeak failed.");
delay(1000);
return;
[Link]("Connected to ThingSpeak.");
if ([Link]()) {
[Link]("Sending data...");
// Start building the HTTP GET request string using concatenation
String command = "GET /update?api_key=";
// Add API Key, Field number, and Value
command += THINGSPEAK_API_KEY;
command += "&field";
command += THINGSPEAK_FIELD_NUMBER;
command += "=";
command += String(buttonState);
// Add HTTP protocol and Host headers
command += " HTTP/1.1\r\n";
command += "Host: ";
command += THINGSPEAK_SERVER;
command += "\r\n";
// End of request headers
command += "Connection: close\r\n\r\n";
// Print the request to the console for monitoring
[Link]("--- Request Sent ---");
[Link](command);
// Send the constructed command
[Link](command);
// Immediately close the connection after sending the request (for HTTP/1.1 with Connection:
close)
[Link]();
[Link]("Connection closed.");
}
// 5. Wait for the required ThingSpeak interval (minimum 15 seconds)
[Link]("Waiting 20 seconds for next update...");
delay(20000);
}
CODE EXPLANATION
1. Configuration (Macros)
● Definitions: The program starts by using #define to create macros (shortcuts) for all
critical settings, making them easy to change.
○ This includes the Wi-Fi SSID ("ANITS") and Password ("anits123").
○ It also includes the ThingSpeak API Key and server address.
○ The pushbutton is assigned to pin D3 (GPIO 0).
2. Setup (void setup())
● Serial: Initializes the serial monitor for debugging messages (like Wi-Fi status).
● Pin Mode: Sets the PUSHBUTTON_PIN to INPUT_PULLUP. This means the pin will read
HIGH (1) when the button is not pressed and LOW (0) when the button is pressed
(connected to ground).
● Wi-Fi Connection: The NodeMCU attempts to connect to the defined Wi-Fi network
(ANITS). It pauses and prints a dot (.) until a successful connection is established.
3. Main Logic (void loop())
The void loop() function runs continuously to manage the sensor reading and data
transmission.
● Wi-Fi Check: It first checks if the Wi-Fi is still connected. If not, it attempts to
reconnect and exits the current loop iteration.
● Read Sensor: It performs a simple digitalRead() on the pushbutton pin to get its
current state (0 or 1).
● ThingSpeak Connection Check: It checks if the client object is already
connected to the ThingSpeak server (![Link]()).
○ If it's not connected, it calls [Link]() to establish a connection. If
this fails, the loop stops and tries again later.
● Data Transmission (if connected): If the client is connected, the following happens:
○ Request Construction: A long text string is built step-by-step (string
concatenation) to form a complete HTTP GET request. This string includes
the API Key, the field number, and the current buttonState.
○ Sending: The complete request string is sent to the ThingSpeak server using
[Link](command).
○ Disconnection: Immediately after sending the data, the connection is closed
using [Link](). This is crucial for simple HTTP requests.
● Delay: Finally, the program waits for 20,000 milliseconds (20 seconds). This pause
is required to prevent the program from overloading the ThingSpeak API, which has a
minimum update interval of 15 seconds.
2. Program for sending an ANALOG value to thingspeak
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
// --- Macro Definitions for Configuration ---
#define WIFI_SSID "ANITS"
#define WIFI_PASS "anits123"
#define THINGSPEAK_API_KEY "WGVG2C223R81XWP4" // REPLACE with your ThingSpeak Write
API Key
#define THINGSPEAK_SERVER "[Link]"
#define THINGSPEAK_FIELD_NUMBER "1"
#define ANALOG_PIN A0 // MODIFICATION 1: Changed to A0 for Analog input
// --- Globals ---
WiFiClient client;
// --- Setup ---
void setup() {
[Link](115200);
// MODIFICATION 2: Removed pinMode(PUSHBUTTON_PIN, INPUT); as A0 is used for Analog
input
// Connect to WiFi
[Link]("\nConnecting to WiFi: ");
[Link](WIFI_SSID);
[Link](WIFI_SSID, WIFI_PASS);
while ([Link]() != WL_CONNECTED) {
delay(500);
[Link](".");
[Link]("\nWiFi connected!");
[Link]("IP Address: ");
[Link]([Link]());
// -------------------------------------------------------------------
// --- Loop ---
void loop() {
// 2. Read the analog value (0 to 1023)
int analogValue = analogRead(ANALOG_PIN);
[Link]("\nAnalog Value Read (0-1023): ");
[Link](analogValue);
// 3. Connect to ThingSpeak if not already connected
if (![Link]()) {
[Link]("Connecting to ThingSpeak...");
if () {
[Link]("Connection to ThingSpeak failed.");
delay(1000);
return;
[Link]("Connected to ThingSpeak.");
// 4. Send data (only runs if connected)
if ([Link]()) {
[Link]("Sending data...");
// Start building the HTTP GET request string using concatenation
String command = "GET /update?api_key=";
// Add API Key, Field number, and Value
command += THINGSPEAK_API_KEY;
command += "&field";
command += THINGSPEAK_FIELD_NUMBER;
command += "=";
command += String(analogValue); // MODIFICATION 4: Use the new variable name
// Add HTTP protocol and Host headers
command += " HTTP/1.1\r\n";
command += "Host: ";
command += THINGSPEAK_SERVER;
command += "\r\n";
// End of request headers
command += "Connection: close\r\n\r\n";
// Print the request to the console for monitoring
[Link]("--- Request Sent ---");
[Link](command);
// Send the constructed command
[Link](command);
// Close the connection
[Link]();
[Link]("Connection closed.");
// 5. Wait for the required ThingSpeak interval
[Link]("Waiting 20 seconds for next update...");
delay(20000);
CODE EXPLANATION
1. Configuration Setup
● Macros Define Settings: The program uses clear definitions (macros) for all crucial
information:
○ Wi-Fi Credentials: The network name (ANITS) and password (anits123).
○ ThingSpeak Details: The Write API Key and server address
([Link]).
○ Sensor Pin: The sensor is connected to the Analog input pin (A0).
● Initial Connection: In the setup() function, the NodeMCU connects to the Wi-Fi network
using the defined credentials.
2. Continuous Loop (void loop())
The program runs the following steps continuously:
1. Wi-Fi Check: It first checks if the Wi-Fi connection is active. If it finds that the Wi-Fi is
disconnected, it tries to reconnect immediately and then pauses before repeating the loop.
2. Read Analog Value: The code reads the voltage level from the A0 pin using the
analogRead() function. This returns a number between 0 and 1023.
3. ThingSpeak Connection: It checks if the program is already connected to the
ThingSpeak server.
○ If not connected, it attempts to establish a new connection. If this connection fails,
it prints an error and waits to try again.
4. Send Data (If Connected): If a connection to ThingSpeak is successful:
○ Build Request: It creates a long text string—an HTTP GET request—by piecing
together the server address, API key, field number, and the newly read
analogValue.
○ Transmit: This complete request string is sent to the ThingSpeak server using the
[Link]() command.
○ Close Connection: The connection to the server is immediately shut down using
[Link](). This conserves resources after the data packet is sent.
5. Wait: The program then waits for 20 seconds (delay(20000)) before the next cycle
begins. This delay prevents the program from sending data too quickly, which would violate
ThingSpeak's rate limit.