Upload Sensor Data to ThingSpeak using NodeMCU
ThingSpeak is an Open-Source IoT application and API to store and retrieve data from Hardware devices and Sensors. It uses HTTP Protocol over the Internet or LAN for its communication. The MATLAB analytics is included to analyze and visualize the data received from your Hardware or Sensor Devices.
We can create channels for each and every sensor data. These channels can be set as private channels or you can share the data publically through Public channels. The commercial features include additional features. But we will be using the free version as we doing it for educational purpose.
You can make projects like Weather Station, Tide Prediction, Counter and Many More.
Features:
- Collect data in private channels.
- Share Data with Public Channels
- REST API and MQTT APIS
- MATLAB® Analytics and Visualizations.
- Worldwide Community
In this tutorial, we will be using an LDR to plot its light Intensity level on ThingSpeak using NodeMCU. We will program the NodeMCU to read and store the LDR data into a variable and then upload it to ThingSpeak using its channel name and API key. The NodeMCU should be connected to the internet via Wi-Fi. We will see how to create ThingSpeak Channels and configure it on NodeMCU.
Hardware Required:
- NodeMCU
- LDR Module
- 10K Ohm Resistor
- Jumper Wires
- Breadboard (Optional)
Circuit Diagram:
Once the hardware is set up, We can go ahead and create our ThingSpeak Channel.
Step 1: Go to https://thingspeak.com/ and create your ThingSpeak Account if you don’t have. Login to Your Account.
Step 2: Create a Channel by clicking ’New Channel’.
Step 3: Enter the channel details.
Name: Any Name
Description: Optional
Field 1: Light Intensity LDR – This will be displayed on the analytics graph. If you need more than 1 Channels you can create for additional Sensor Data.
Save this setting.
Step 4: Now you can see the channels. Click on the ‘API Keys’ tab. Here you will get the Channel ID and API Keys. Note this down.
Step 5: Open Arduino IDE and Install the ThingSpeak Library. To do this go to Sketch>Include Library>Manage Libraries. Search for ThingSpeak and install the library.
Step 6: Now we need to modify the program with your credentials.
In the below code you need to change your Network SSID, Password and your ThingSpeak Channel and API Keys.
Replace the following content in the code,
‘Your SSID Here’ – Your Wi-Fi Name
‘Your Password Here’ – Your Wi-Fi Password
‘YYYYYY’ – Your ThingSpeak Channel Number (without Quotes)
‘XXXXXXXXXXX’ – Your Thing Speak API Key.
Code:
#include <ESP8266WiFi.h>; #include <WiFiClient.h>; #include <ThingSpeak.h>; const char* ssid = "Your SSID Here"; //Your Network SSID const char* password = "Your Password Here"; //Your Network Password int val; int LDRpin = A0; //LDR Pin Connected at A0 Pin WiFiClient client; unsigned long myChannelNumber = YYYYYY; //Your Channel Number (Without Brackets) const char * myWriteAPIKey = "XXXXXXXXXXXXXXX"; //Your Write API Key void setup() { Serial.begin(9600); delay(10); // Connect to WiFi network WiFi.begin(ssid, password); ThingSpeak.begin(client); } void loop() { val = analogRead(LDRpin); //Read Analog values and Store in val variable Serial.print(val); //Print on Serial Monitor delay(1000); ThingSpeak.writeField(myChannelNumber, 1,val, myWriteAPIKey); //Update in ThingSpeak delay(100); }
Upload the code. Once it is connected to Wi-Fi the data will start uploading to the ThingSpeak Channel. You can now open your Channel and see the data changes plotted on the ThingSpeak.
Comments (116)
thanks for the information, i need upload data in two filed i tried but it upload one filed only can you guide me
Did you added the Second Channel on your code.
Create one more channel as ‘myChannelnumber2 = 2ndYYYY’ and API Key variable 2ndXXXXXXXXXXX.
and then add one more thinngspeak writefield and put the myChannelnumber2 and myWriteAPIKey2.
Sir,
I want to read value of D0 and D1 of esp8266 and upload it on thingspeak channel.can you please provide code for same.I tired but channel is not updating with binary value,below is code.
#include ;
#include ;
#include ;
const char* ssid = “xxxxxx”; //Your Network SSID
const char* password = “xxxxxx”; //Your Network Password
int output1 = D0; // the number of the pushbutton pin
int output2 = D1; // the number of the LED pin
int output1State = 0; // variable for reading the pushbutton status
int output2State = 0; // variable for reading the pushbutton status
void setup() {
unsigned long myChannelNumber = xxxxx; //Your Channel Number (Without Brackets)
const char * myWriteAPIKey = “xxxxxxxx”; //Your Write API Key
Serial.begin(9600);
Serial.print(“begin”);
// initialize the LED pin as an output:
pinMode(output1, OUTPUT);
pinMode(output2, OUTPUT);
}
void loop() {
output1State = digitalRead(output1);
output2State = digitalRead(output2);
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if (output1State == HIGH) {
Serial.println(“High D0 “);
}
else {
Serial.println(“LOW D0 “);
ThingSpeak.writeField(myChannelNumber, 1,output1, myWriteAPIKey);
}
delay(30);
if (output2State == HIGH) {
Serial.println(“High D1 “);
}
else {
Serial.println(“LOW D1 “);
ThingSpeak.writeField(myChannelNumber, 1,output2, myWriteAPIKey);
}
}
You are updating the channel only when the pin is low. You also have to update if it is high. Then only it will show you both. Otherwise, it will update only the LOW Signals. Also, you are updating both values on the same channel. If you are aware then it will be fine.
Also, check out this blog, It actually works same, but it has both analog & digital – https://www.factoryforward.com/automatic-street-light-thingspeak-cloud/
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed
this error show in program
Check with another quality microUSB Cable (Original Phone cables preferred). If your cable is too long it might have some power loss & have high resistances so the data won’t be perfect and difficult to sync.
ple send your contact no
Tools -> Board: NodeMCU 0.9 (ESP 12 Module)
And
Tools -> Upload Speed: 115200
Hello,
Could you possibly help me with posting ECG value from the AD8232 Heart rate sensor using the nodemcu? I just need a little help with the code and sending the data to thingspeak
Did you have the Reset Problem in NodeMCU while using ThingSpeak?
how to send multiple data to thingspeak
#include "ThingSpeak.h"
#include
char ssid[] = "YourSSID"; // your network SSID (name)
char pass[] = "YourPassword"; // your network password
int keyIndex = 0; // your network key Index number (needed only for WEP)
WiFiClient client;
unsigned long myChannelNumber = YYYYYY; //Your Channel Number
const char * myWriteAPIKey = "XXXXXXXXXXXXXXXXX"; //Your API Key
// Initialize our values
int number1 = 0; //Dummy Values, consider it from sensors
int number2 = random(0,100); //Dummy random Values
int number3 = random(0,100); //Dummy random Values
int number4 = random(0,100); //Dummy random Values
String myStatus = "";
void setup() {
Serial.begin(115200); // Initialize serial
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client); // Initialize ThingSpeak
}
void loop() {
// set the fields with the values
ThingSpeak.setField(1, number1); //Number 1 Values updated to field 1
ThingSpeak.setField(2, number2); //to field 2
ThingSpeak.setField(3, number3); //to field 3
ThingSpeak.setField(4, number4); //to Field 4
// figure out the status message
if(number1 > number2){
myStatus = String("field1 is greater than field2");
}
else if(number1 < number2){ myStatus = String("field1 is less than field2"); } else{ myStatus = String("field1 equals field2"); } // set the status ThingSpeak.setStatus(myStatus); // write to the ThingSpeak channel int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey); if(x == 200){ Serial.println("Channel update successful."); } else{ Serial.println("Problem updating channel. HTTP error code " + String(x)); } // change the values number1++; if(number1 > 99){
number1 = 0;
}
number2 = random(0,100);
number3 = random(0,100);
number4 = random(0,100);
delay(20000); // Wait 20 seconds to update the channel again
}
I am getting error saying
‘client’ was not declared in this scope
Did you installed these Libraries?
ESP8266WiFi.h;
WiFiClient.h;
It will be available in the ‘Arduino Core for ESP8266 Library’ by default.
https://github.com/esp8266/Arduino
Download> Extract> Navigate to Libraries Folder>Copy and paste it in Arduino Libraries Folder (C:\Program Files (x86)\Arduino\libraries)
hello sir, i need code for street lights to on/off according to daylight using IR sensor, arduino, nodemcu and Ldr sending data to thingspeak. could you please help me here?
Create a variable for LED
int ledPin = 13;
Inside Setup:
pinmode(ledPin,OUTPUT);
Inside Loop: Create an if else loop according to your requirements
if(val<100){
Function you want to perfom when low light
LED ON/OFF //use digitalwrite
ThingSpeak.writeField(myChannelNumber, 1,val, myWriteAPIKey); //Update in ThingSpeak
}
else{
Function you want to perfom when High light
LED ON/OFF
}
oh my god you replied!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! thank you very much sir.
you’re really kind.
i’d use this code and let you know how it worked .
can i contact you Sir PLEASE from any other platform than this ? please let me know.
one more thing sir i am not using nodemcu instead using just ESP8266 wifi module the basic chip one, could i do it using arduino LDR and IR sensor with it? i have my project presentation on monday, need to complete by tomorrow. it would mean world to me if you helped sir.
I didn’t used the ESP8266 chip alone yet. I mostly prefer NodeMCU Dev Board because it has all the necessary circuitry for faster development and its cheap too. If we build that circuitry for flashing mode, voltage regulation & all it becomes costly and eats a lot of time.
For prototyping projects better go with NodeMCU. ESP8266 Chips are suitable for fully developed projects and for making large qty as they designed the PCB Specifically for that.
i got zero values distance in my thingspeal graph sir. can you help me?
im using nodemcu v3 sir.
Use Advanced IP Scanner in your phone or desktop to check whether your NodeMCU is connected to the Wi-Fi Network. Also, you have to update your Channel Number and API Key.
So you have to modify 4 things in the code before uploading.
sir, i am using nodemcu, LDR, IR Sensor, Led
street light which is our LED will glow when the LDR which will compare with the given threshold value,
then if IR sensor will detect any objects it will store the data on thingspeak and glow the LED.
Sir, coulld you please give the code for this? it would be realy helpful.
I’m unable to reply as I was on travel. Do you still need the code?
yes i really do sir..
https://create.arduino.cc/editor/sarathkumar341/84f2d3f5-046a-41f8-8ad3-4d1b8fb2fa2f/preview
Hello sir, how to send multiple data to thingspeak if I connect NodeMCU to Arduino Uno?
Check the previous comment, asked by Zigg. I replied it with the code.
hello sir, can you help me how to connect sound sensor with nodemcu 8266?
Sound sensor output will trigger within microseconds. So you need to use delay function and capture that event in a variable. It is same as the push-button example, just add a delay with that. You can use any digital pin like D1,D2,D5,D6,D7,D8.
can i have sample code for sound sensor connect with nodemcu sir?
can i have sample code for sound sensor connect with nodemcu sir?
int soundDetect;
//Add setup functions here
void loop(){
val = analogRead(LDRpin); //Read Analog values and Store in val variable
if (val>800){
soundDetect = HIGH;
Serial.print(val); //Print on Serial Monitor
//delay(200);
ThingSpeak.writeField(myChannelNumber, 1,soundDetect, myWriteAPIKey); //Update in ThingSpeak
}
int soundDetect = LOW;
}
the codes cannot ran in arduino ide. Is it the connection for circuit same like ldr circuit above?
Hello Sir, can you help me how to connect and send data water level sensor with nodemcu v3?
Which water level sensor you are using?
If it is a digital sensor (Full or Empty status) then
Change the A0 analog pin to any digital pin of these D1,D2,D5,D6,D7,D8.
Then, instead of analogRead you need to use digitalRead. That’s it.
val = analogRead(LDRpin); //Read Analog values and Store in val variable
val = digitalRead(LDRpin); //Read Digital values and Store in val variable
thank u sir, i have finish.
But can you help me how to connect and send data with nodeMCU to Thingspeak ?
please help me
It is the same tutorial only. Instead of LDR, you use the Waterlevel sensor.
ThingSpeak.writeField(myChannelNumber, 1,val, myWriteAPIKey);
The val is the variable that holds sensor data. Whatever you mentioned you can modify that variable here.
Hi! Can you help me on connecting the adxl 335 to the thingspeak? Thanks!!
Get the ADXL Values (X,Y,Z). Create three fields and update each axis values to thingspeak fields. Check this new tutorial for 2 channel update – https://www.factoryforward.com/automatic-street-light-thingspeak-cloud/
hello sir, i want to upload accelerometer data to thingspeak but i am not able to do so can you provide me the code please.
https://www.factoryforward.com/automatic-street-light-thingspeak-cloud/ – This tutorial has two channel update. You just need to add one more channel. If you look at the code comment, you can get the idea.
Arduino: 1.8.9 (Windows Store 1.8.21.0) (Windows 10), Board: “Arduino/Genuino Uno”
In file included from C:\Users\Thakur Ayush\Documents\Arduino\libraries\ESP8266WiFi\src/ESP8266WiFi.h:33:0,
from C:\Users\Thakur Ayush\Documents\Arduino\AQM_final\AQM\AQM.ino:1:
C:\Users\Thakur Ayush\Documents\Arduino\libraries\ESP8266WiFi\src/ESP8266WiFiType.h:26:19: fatal error: queue.h: No such file or directory
compilation terminated.
exit status 1
Error compiling for board Arduino/Genuino Uno.
This report would have more information with
“Show verbose output during compilation”
option enabled in File -> Preferences.
PLEASE HELP
You didn’t choose the Board type as ESP8266/NodeMCU (Wi-Fi related boards). Otherwise you didn’t installed the Arduino CORE Library.
Have a look at step 7 on this tutorial – https://www.factoryforward.com/iot-home-automation-using-blynk-nodemcu/
Hello!
I am doing my final year project on underground cable fault detection over IoT.
I am using an Arduino Uno as microcontroller and ESP8266-12E as WiFi module. Both are communicating serially. I have been able to send data from Arduino Uno to WiFi module that i have checked on the serial monitor of the ESP8266-12E. The WiFi module is also connected to ThingSpeak platform.
The only problem is that the IoT platform is displaying only zeros on all three fields even if the serial monitor of the WiFi module is receiving different data
Below is my code uploaded to the ESP8266-12E
my data from the arduino is uploaded to the WiFi module as follows :
*864#; it means that the wifi module will check if the string of data starts with ‘*’ and ends with ‘#’ if yes it takes the value in between as
8 to be data 1
6 to be data 2
4 to be data 3
ESP8266-12E Code
String apiKey = “GCC8OP2PI5JYIOY3”; // <<<<< YOUR API KEY
const char* ssid = "Telecom-YCTb"; // <<<<<<<< Your Wi-Fi SSID
const char* password = "n4mcE5mV"; // <<<<<<< 0)
{
delay(100);
while (Serial.available() > 0)
{
buffer1 = Serial.readString();
if (buffer1[0] == ‘*’)
{
if (buffer1[4] == ‘#’)
{
Serial.println(buffer1);
data1 = ((buffer1[1]- 0x30));
data2 = ((buffer1[2]- 0x30));
data3 = ((buffer1[3]- 0x30));
}
}
}
}
if (client.connect(server, 80))
{
String postStr = apiKey;
postStr += “&field1=”;
postStr += String(data1);
postStr += “&field2=”;
postStr += String(data2);
postStr += “&field3=”;
postStr += String(data3);
postStr += “\r\n\r\n\r\n”;
client.print(“POST /update HTTP/1.1\n”);
client.print(“Host: api.thingspeak.com\n”);
client.print(“Connection: close\n”);
client.print(“X-THINGSPEAKAPIKEY: ” + apiKey + “\n”);
client.print(“Content-Type: application/x-www-form-urlencoded\n”);
client.print(“Content-Length: “);
client.print(postStr.length());
client.print(“\n\n”);
client.print(postStr);
Serial.println(postStr);
}
client.stop();
Serial.println(“Waiting…”);
delay(20000);
Hello sir, How I can sent Serial monitor Arduino to Thingspeak using NodeMCU ?
byte myData = Serial.read();
ThingSpeak.writeField(myChannelNumber, 1,(char)val, myWriteAPIKey); //Update in ThingSpeak
I Upload this code and still not update . can you help me, i use RX TX pin arduino to Tx Rx pin Nodemcu for serial monitor.
#include ;
#include ;
#include ;
const char* ssid = “POCOPHONE”; //Your Network SSID
const char* password = “wsmining”; //Your Network Password
int val;
WiFiClient client;
unsigned long myChannelNumber = 783537; //Your Channel Number (Without Brackets)
const char * myWriteAPIKey = “25VJ25D5ANV43P9B”; //Your Write API Key
void setup()
{
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
delay(10);
// Connect to WiFi network
WiFi.begin(ssid, password);
ThingSpeak.begin(client);
}
void loop(){
if (Serial.available())
{
byte val = Serial.read();
delay(1000);
ThingSpeak.writeField(myChannelNumber, 1,(char)val, myWriteAPIKey);
delay(100);
}
}
With this info I can’t able to diagnose what error it will be.
Does the program shows any error?
Does the thingspeak field show the time/date of updated data? It will be shown on last updated field.
Can you please help in transferring data at faster rate to think speak,
The speed depends on internet speed, Thingspeak plans, etc. Check thingspeak paid plans for more details.
Sir how to upload mq 6 sensor data to thingsspeak cloud.
Same code instead of LDR, you have to connect MQ Sensor’s A0 Pin.
Sir how to upload gps data to thingsspeak cloud.
You have to store the GPS Data in a variable and use the ‘Numeric Display’ under widgets option on thingspeak. The value you write on this field and channel will be displayed in numeric.
how to add another sensor ? i want to use multiple sensor ? thank you before
Look at this tutorial. It covers both analog and digital – https://www.factoryforward.com/automatic-street-light-thingspeak-cloud/
…….I READ ALL YOUR COMMENTS YOU WERE REPLYING EVERYONE WITH LOT OF PATIENCE SO I’M EAGERLY WAITING FOR YOUR REPLY ………….ALSO YOU CAN MESSAGE ME AT MY WHATSAPP SIR …..I CAN GIVE IT IF U NEED ……………. I’m doing a project using esp8266-01 project costs 15k with all setup i.e hydroponics .Actually i a had code for this without esp8266 interface so i want to add up a extra code to this to send data to thingspeak .Here im using lot of sensors but i think it is not possible to connect many sensors to it 1st version of ESP. I at least want to connect min of 2 sensors to this please say me the possibility of the code
#include
#define DS3231_I2C_ADDRESS 0x68
#include “DHT.h”
#define DHTPIN 8 // what digital pin we’re connected to
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
#include
DHT dht(DHTPIN, DHTTYPE);
OneWire ds(12); // on pin 10 (a 4.7K resistor is necessary)
BH1750 lightMeter;
int relayIn1 = 2;
int relayIn2 = 3;
int relayIn3 = 4;
int relayIn4 = 5;
int flowSwitch1 = 9;
int flowSwitch2 = 10;
int flowSwitch3 = 11;
int soil = A3;
//Data variables
int flowSwitch1Read = -1; //0 need water, 1 enough water;
int flowSwitch2Read = -2; //0 need water, 1 enough water;
int flowSwitch3Read = -3; //0 need water, 1 enough water;
int lastMinute = -1;
int nowMinute = -2;
int nowHour = -1;
float temperature = -1;
float humidity = -1;
int soilHumidity = -1;
int soilHumidityLevel = 950;
uint16_t lux = 1;
void setup(){
int status;
Serial.begin(9600);
pinMode(relayIn1, OUTPUT);
pinMode(relayIn2, OUTPUT);
pinMode(relayIn3, OUTPUT);
pinMode(relayIn4, OUTPUT);
pinMode(flowSwitch1, INPUT_PULLUP);
pinMode(flowSwitch2, INPUT_PULLUP);
pinMode(flowSwitch3, INPUT_PULLUP);
digitalWrite(relayIn1, HIGH);
digitalWrite(relayIn2, HIGH);
digitalWrite(relayIn3, HIGH);
digitalWrite(relayIn4, HIGH);
pinMode(soil, INPUT);
Wire.begin();
dht.begin();
lightMeter.begin();
}
void loop(){
displayTime();
delay(2000);
if(lastMinute!=nowMinute){
readSensorStatus();
delay(2000);
if (nowHour<7){
//Night shift
Serial.println("Night!");
goto Night;
} else {
//Day shift
Serial.println("Day!");
if(luxsoilHumidityLevel){
if(flowSwitch1Read==0){
turnOnPump();
}
}
lastMinute=nowMinute;
}
delay(1000);
}
}
Night:;
}
void turnOnPump(){
while(flowSwitch1Read==0){
Serial.println(“Relay In 1 on”);
digitalWrite(relayIn1, LOW);
readSensorStatus();
};
Serial.println(“Relay In 1 off”);
turnOffPump();
}
void turnOffPump(){
digitalWrite(relayIn1, HIGH);
}
void turnOnLamp(){
digitalWrite(relayIn4, LOW);
}
void turnOffLamp(){
digitalWrite(relayIn4, HIGH);
}
void readSensorStatus(){
lux = lightMeter.readLightLevel();
Serial.print(“Light: “);
Serial.print(lux);
Serial.println(” lx”);
flowSwitch1Read = digitalRead(flowSwitch1);
Serial.print(“Water level in upper pipes: “);
Serial.println(flowSwitch1Read);
flowSwitch2Read = digitalRead(flowSwitch2);
Serial.print(“Water in tank: “);
Serial.println(flowSwitch2Read);
flowSwitch3Read = digitalRead(flowSwitch3);
Serial.print(“Minimum water in tank: “);
Serial.println(flowSwitch3Read);
//Serial.print(“Float Switch is “);
readDHT();
readWaterTemperature();
soilHumidity = analogRead(soil);
Serial.print(“Soil Humidity sensor value: “);
Serial.println(soilHumidity);
}
// Convert normal decimal numbers to binary coded decimal
byte decToBcd(byte val)
{
return( (val/10*16) + (val%10) );
}
// Convert binary coded decimal to normal decimal numbers
byte bcdToDec(byte val)
{
return( (val/16*10) + (val%16) );
}
void readDS3231time(byte *second,
byte *minute,
byte *hour,
byte *dayOfWeek,
byte *dayOfMonth,
byte *month,
byte *year)
{
Wire.beginTransmission(DS3231_I2C_ADDRESS);
Wire.write(0); // set DS3231 register pointer to 00h
Wire.endTransmission();
Wire.requestFrom(DS3231_I2C_ADDRESS, 7);
// request seven bytes of data from DS3231 starting from register 00h
*second = bcdToDec(Wire.read() & 0x7f);
*minute = bcdToDec(Wire.read());
*hour = bcdToDec(Wire.read() & 0x3f);
*dayOfWeek = bcdToDec(Wire.read());
*dayOfMonth = bcdToDec(Wire.read());
*month = bcdToDec(Wire.read());
*year = bcdToDec(Wire.read());
}
void displayTime()
{
byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;
// retrieve data from DS3231
readDS3231time(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month,
&year);
nowMinute = minute;
nowHour = hour;
// send it to the serial monitor
Serial.print(hour, DEC);
// convert the byte variable to a decimal number when displayed
Serial.print(“:”);
if (minute<10)
{
Serial.print("0");
}
Serial.print(minute, DEC);
Serial.print(":");
if (second<10)
{
Serial.print("0");
}
Serial.print(second, DEC);
Serial.print(" ");
Serial.print(dayOfMonth, DEC);
Serial.print("/");
Serial.print(month, DEC);
Serial.print("/");
Serial.print(year, DEC);
Serial.print(" Day of week: ");
switch(dayOfWeek){
case 1:
Serial.println("Sunday");
break;
case 2:
Serial.println("Monday");
break;
case 3:
Serial.println("Tuesday");
break;
case 4:
Serial.println("Wednesday");
break;
case 5:
Serial.println("Thursday");
break;
case 6:
Serial.println("Friday");
break;
case 7:
Serial.println("Saturday");
break;
}
}
void readDHT(){
humidity = dht.readHumidity();
temperature = dht.readTemperature();
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read from DHT sensor!");
return;
} else {
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print(" *C, Humidity: ");
Serial.println(humidity);
}
}
void readWaterTemperature(){
byte i;
byte present = 0;
byte type_s;
byte data[12];
byte addr[8];
float celsius, fahrenheit;
if ( !ds.search(addr)) {
Serial.println("No more addresses.");
Serial.println();
ds.reset_search();
delay(500);
return;
}
Serial.print("ROM =");
for( i = 0; i < 8; i++) {
Serial.write(' ');
Serial.print(addr[i], HEX);
}
if (OneWire::crc8(addr, 7) != addr[7]) {
Serial.println("CRC is not valid!");
return;
}
Serial.println();
// the first ROM byte indicates which chip
switch (addr[0]) {
case 0x10:
Serial.println(" Chip = DS18S20"); // or old DS1820
type_s = 1;
break;
case 0x28:
Serial.println(" Chip = DS18B20");
type_s = 0;
break;
case 0x22:
Serial.println(" Chip = DS1822");
type_s = 0;
break;
default:
Serial.println("Device is not a DS18x20 family device.");
return;
}
ds.reset();
ds.select(addr);
ds.write(0x44, 1); // start conversion, with parasite power on at the end
delay(1000); // maybe 750ms is enough, maybe not
// we might do a ds.depower() here, but the reset will take care of it.
present = ds.reset();
ds.select(addr);
ds.write(0xBE); // Read Scratchpad
Serial.print(" Data = ");
Serial.print(present, HEX);
Serial.print(" ");
for ( i = 0; i < 9; i++) { // we need 9 bytes
data[i] = ds.read();
Serial.print(data[i], HEX);
Serial.print(" ");
}
Serial.print(" CRC=");
Serial.print(OneWire::crc8(data, 8), HEX);
Serial.println();
// Convert the data to actual temperature
// because the result is a 16 bit signed integer, it should
// be stored to an "int16_t" type, which is always 16 bits
// even when compiled on a 32 bit processor.
int16_t raw = (data[1] << 8) | data[0];
if (type_s) {
raw = raw << 3; // 9 bit resolution default
if (data[7] == 0x10) {
// "count remain" gives full 12 bit resolution
raw = (raw & 0xFFF0) + 12 – data[6];
}
} else {
byte cfg = (data[4] & 0x60);
if (cfg == 0x00) raw = raw & ~7; // 9 bit resolution, 93.75 ms
else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
//// default is 12 bit resolution, 750 ms conversion time
}
celsius = (float)raw / 16.0;
fahrenheit = celsius * 1.8 + 32.0;
Serial.print(" Temperature = ");
Serial.print(celsius);
Serial.print(" Celsius, ");
Serial.print(fahrenheit);
Serial.println(" Fahrenheit");
}
this is the i want to over write…………….
PLEASE HELP ME < THIS PROJECT IS GOING TO CREATE A LOT OF CHANGE IN MY CAREER
If you didn’t created any PCB for that, then you can use an ESP32 Development Board/ESP32 Chip. It has 18 ADC Channels,BLuetooth and more memory. https://www.factoryforward.com/product/esp32-development-board-wifi-bluetooth/
Is possible to make such program from where the Data can be read from the thingspeak and then that data can be used to control some hardware(like survo motor or led etc.)
Yes you can, We are using Write API in this example. Instead we need to use Read APIs to get the values and using a simple if..else conditions you can control it.
You can use a seperate NodeMCU or the same for both and Read and Write operations. I think an in the File>Examples in Arduino IDE the read example code might be there. You can modify it according to that format.
Sir plz send me ir sensor code for uploading could to things speak
Replace this line
val = analogRead(LDRpin); //Read Analog values and Store in val variable
with
val = digitalReadRead(LDRpin); //Read Analog values and Store in val variable
Initialize the pinmode as input in Setup Loop
pinMode(LDRpin, INPUT); //LDR Pin is just a variable u can keep or change it to IR.
hello sir, iam able to get the sensor data in the serial monitor but nothing is displayed in the thingspeak channel
Check the SSID and password in proper double quotes and Check the Channel ID and API Keys Once.
Hi Sharath
Im trying to use an ADXL335 and upload the 3 fields x,y,z to thingspeak. I’ve added a bit of math conversion for the acceleraometer, but need help.
Any help would be appreciated – Many thanks
Code as follows:
#include
#define RX 10
#define TX 11
String AP = “***********”; // CHANGE ME
String PASS = “***********”; // CHANGE ME
String API = “************”; // CHANGE ME
String HOST = “api.thingspeak.com”;
String PORT = “80”;
String field1 = “field1”;
String field2 = “field2”;
String field3 = “field3”;
int countTrueCommand;
int countTimeCommand;
boolean found = false;
int valSensor_x = A1;
int valSensor_y = A2;
int valSensor_z = A3; /* connect x_out of module to A1 of UNO board */
SoftwareSerial esp8266(RX,TX);
void setup() {
Serial.begin(9600);
esp8266.begin(115200);
sendCommand(“AT”,5,”OK”);
sendCommand(“AT+CWMODE=1″,5,”OK”);
sendCommand(“AT+CWJAP=\””+ AP +”\”,\””+ PASS +”\””,20,”OK”);
}
void loop() {
int x_adc_value, y_adc_value, z_adc_value;
double x_g_value, y_g_value, z_g_value;
x_adc_value = analogRead(A1); /* Digital value of voltage on x_out pin */
y_adc_value = analogRead(A2); /* Digital value of voltage on y_out pin */
z_adc_value = analogRead(A3); /* Digital value of voltage on z_out pin */
x_g_value = ( ( ( (double)(x_adc_value * 5)/1024) – 1.65 ) / 0.330 ); /* Acceleration in x-direction in g units */
y_g_value = ( ( ( (double)(y_adc_value * 5)/1024) – 1.65 ) / 0.330 ); /* Acceleration in y-direction in g units */
z_g_value = ( ( ( (double)(z_adc_value * 5)/1024) – 1.80 ) / 0.330 ); /* Acceleration in z-direction in g units */
String getData = “GET /update?api_key=”+ API +”&field1=” + x_g_value +”&field2=” + y_g_value +”&field3=” + z_g_value;
sendCommand(“AT+CIPMUX=1″,5,”OK”);
sendCommand(“AT+CIPSTART=0,\”TCP\”,\””+ HOST +”\”,”+ PORT,15,”OK”);
sendCommand(“AT+CIPSEND=0,” +String(getData.length()+4),4,”>”);
esp8266.println(getData);delay(1500);countTrueCommand++;
sendCommand(“AT+CIPCLOSE=0″,5,”OK”);
}
int getSensorData(){
return random(1000); // Replace with
}
void sendCommand(String command, int maxTime, char readReplay[]) {
Serial.print(countTrueCommand);
Serial.print(“. at command => “);
Serial.print(command);
Serial.print(” “);
while(countTimeCommand < (maxTime*1))
{
esp8266.println(command);//at+cipsend
if(esp8266.find(readReplay))//ok
{
found = true;
break;
}
countTimeCommand++;
}
if(found == true)
{
Serial.println("OYI");
countTrueCommand++;
countTimeCommand = 0;
}
if(found == false)
{
Serial.println("Fail");
countTrueCommand = 0;
countTimeCommand = 0;
}
found = false;
}
will you please send the pulse sensor code using node mcu and connected to thingspeak
bro i need coding for level indicator using 3-IR sensor in nodemcu and thingspeak server
Hi…..
I am interfacing the flame sensor with reading(CODE) bt i didn’t get the solution
i used this code..
void loop() {
ThingSpeak.setField(1, number1);
ThingSpeak.setField(2, number2);
ThingSpeak.setField(3, number3);
ThingSpeak.setField(4, number4);
if(number1 > number2){
myStatus = String(“field1 is greater than field2”);
}
else if(number1 < number2){ myStatus = String("field1 is less than field2"); }
else{ myStatus = String("field1 equals field2"); }
el int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
if(x == 200){ Serial.println("Channel update successful."); }
else{ Serial.println("Problem updating channel. HTTP error code " + String(x)); }
}
number1=rondom(0,100);
number2 = random(0,100);
number3 = random(0,100);
number4 = random(0,100);
delay(20000);
}
Problems in the code:
– Where is the setup loop in the code?
– The code in the loop just do nothing as it doesn’t have this line
ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey); // or a similar function
– It is just passing random number from 1 to 100 in all fields and quits without updating anywhere.
– It also doesn’t print any compared values either.
Also you didn’t mentioned what output you are trying to achieve.
hello! sir! i have uploaded a code for gas sensor and neode mcu.But in things speak it doesnt show the graph. can you please guide? the code is here
#include
#include
#include “MQ135.h”
#include
String apiKey = “1CUJEV41WNM7WHHP”; // Enter your Write API key from ThingSpeak
const char *ssid = “Harrin”; // replace with your wifi ssid and wpa2 key
const char *pass = “harrin20”;
const char* server = “api.thingspeak.com”;
WiFiClient client;
unsigned long myChannelNumber = 876579;
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
#define VOLTAGE_MAX 5.0
#define VOLTAGE_MAXCOUNTS 1023.0
void setup() {
Serial.begin(9600);
delay(10);
Serial.println(“Connecting to “);
Serial.println(ssid);
WiFi.begin(ssid, pass);
ThingSpeak.begin(client);
}
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// Convert the analog reading
// On Arduino: 0 – 1023 maps to 0 – 5 volts
// On ESP8266: 0 – 1023 maps to 0 – 1 volts
// On Particle: 0 – 4095 maps to 0 – 3.3 volts
float voltage = sensorValue * (VOLTAGE_MAX / VOLTAGE_MAXCOUNTS);
Serial.print(voltage);
Serial.println();
delay(20000); // ThingSpeak will only accept updates every 15 seconds.
}
Thanks
ThingSpeak.writeField(myChannelNumber, 1,voltage, apiKey); //Update in ThingSpeak
This line is missing in your code. It is the important line to update your data to thingspeak.
The myChannelNumber, voltage and apiKey are the variables that holds data.
In your case you are printing the ‘voltage’ variable in serial monitor, so that is the value you are updating in thingspeak. Hence that is mentioned in the ThingSpeak.writeField() function. The other two holds the channel number and keys that you defined before setup loop. The number ‘1’ mentioned in the function is the field that you are going to update.
That is done. Still not getting the graph.serial monitor shows the output but no output in Thingspeak. Above the graph in thingspeak 0 entries….plz help me further.
I done what you said. But no changes..still same situation. Serial monitor shows the values but nothing is displayed on Thingspeak.
Check if the SSID and Password is connected & Make sure it has internet connection
Check the API Keys.There are two API Keys (Read API & Write API Keys). Check the correct type.
Check your channel number.