NodeMCU LDR ThingSpeak

Z2M Part: EMS-00017-A

Log LDR readings to ThingSpeak cloud with NodeMCU.

Circuit Diagram
Circuit diagram for NodeMCU LDR ThingSpeak
Wire Connections & Pin Configuration

Wire Color Connections:

Yellow → NodeMCU A0 to LDR–resistor junction
Red → 3.3V to LDR
Black → GND to 10kΩ resistor

Pin Configuration:

NodeMCU Analog Pin A0 → LDR (voltage divider)
NodeMCU 3.3V → LDR
NodeMCU GND → GND
Arduino Code
Edit
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ThingSpeak.h>

// Replace with your WiFi credentials
const char* ssid = \"Your_SSID_Here\";       // WiFi Name
const char* password = \"Your_Password_Here\"; // WiFi Password

// ThingSpeak credentials
unsigned long myChannelNumber = YYYYYY;     // Replace with your ThingSpeak Channel Number
const char* myWriteAPIKey = \"XXXXXXXXXXXXXXX\"; // Replace with your Write API Key

// Sensor configuration
int LDRpin = A0;   // LDR sensor connected to A0 pin
int value = 0;     // Variable to store LDR reading

WiFiClient client;

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

  Serial.println(\"Connecting to WiFi...\");
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(\".\");
  }

  Serial.println(\"\");
  Serial.println(\"WiFi connected\");
  Serial.print(\"IP address: \");
  Serial.println(WiFi.localIP());

  ThingSpeak.begin(client);
}

void loop() {
  value = analogRead(LDRpin);  // Read LDR sensor value
  Serial.print(\"LDR Value: \");
  Serial.println(value);

  // Send data to ThingSpeak
  int response = ThingSpeak.writeField(myChannelNumber, 1, value, myWriteAPIKey);

  if (response == 200) {
    Serial.println(\"Data sent to ThingSpeak successfully.\");
  } else {
    Serial.print(\"Error sending data. HTTP error code: \");
    Serial.println(response);
  }

  delay(15000); // ThingSpeak allows updates every 15 seconds
}

Instruction Details

Wiring: Connect LDR one leg to 3.3V, other to 10kΩ to GND. Connect junction to NodeMCU A0.
Library: Sketch → Include Library → Manage Libraries → search "ThingSpeak" → Install.
Upload Code: Tools → Board → NodeMCU 1.0. Tools → Port → select your COM port. Click Upload button. Set WiFi SSID, password, and ThingSpeak API key in code.
View Output: Create ThingSpeak channel. Open Serial Monitor for IP. Light data logs to cloud. View on ThingSpeak dashboard.

How to Use

  1. Connect the required components as per the Pin Configuration above
  2. Open Arduino IDE and create a new sketch
  3. Copy and paste the code above
  4. Select your Arduino board and COM port from Tools menu
  5. Click the Upload button to upload the code to your Arduino
  6. Open Serial Monitor (if applicable) to see the output

Components Required

  • NodeMCU/ESP8266
  • LDR (Light Dependent Resistor)
  • 10kΩ Resistor
  • Micro USB Cable
  • Breadboard
  • Jumper Wires

Category: Sensors