Dick in Discussions
上次活动时间: 2024-12-7

I am using a micro:bit device with ESP8266 for a IOT project, but cannot connect thingspeak recently. The conncection is unstable, I can hardly connect to thingspeak for days, somehow it works last night for 30 mins and then it fails. The program does not change and I have included a 25 sec delayed between each data sending. Please advice why and how to fix it. Thank you. Unstable data receiving from Micro:bit device Can you share your program? Specifically,the AT commands used to send the data to ThingSpeak? Please do _not_ share your API keys. esp8266 micro:bit
Siddharth Lotia in MATLAB Answers
上次活动时间: 2024-9-25

Hi I am posting/writing some real time data to multiple fields of multiple channels (4)with help of ESP8266 Wifi Module, but after some time thingspeak returns me 301 error. I tried with Office Wifi as well Mobile Hotspot the issue persists. In office we have a static IP based dual band connection. Please let me know, what to do to remove this error. I tried reintialising the connection with ThingSpeak.begin(client); whenever this error comes but no help. Please let me know how to remove the issue , as I am at critical junction of an important project and this is the only roadblock that I have.
Sergio R in MATLAB Answers
上次活动时间: 2024-8-7

Hello, in a ThingSpeak channel, I am reading every one second the information of two current signals (I have the licensed application). I currently have a MATLAB Analysis routine that adds those two signals and writes, on the same channel, the result of that sum. In the routine I can check that effectively if the sum of the two channels is being done. I do that now with a good result but my problem is that the channel is not updated except when I run MATLAB Analysis. How can I make the channel automatically update every second? ------------------------------------------------------------------------------- This is my routine: readChannelID = 123; readAPIKey = 'XXX'; writeChannelID = 123; writeAPIKey = 'YYY'; %%%%%%%%%%%%%%%%%%%%%% CALCULO DE CORRIENTE %%%%%%%%%%%%%%%%%%%%%% [Cte1, timeStamp] = thingSpeakRead(readChannelID,'Fields',1,'numPoints', 2, 'ReadKey', readAPIKey); anyMissingValues = sum(isnan(Cte1)); if sum(anyMissingValues) > 0 missingValueIndex = find(~sum(isnan(Cte1),2)); cleanCte1 = Cte1(missingValueIndex, :); cleanTimeStamps = timeStamp(missingValueIndex); else cleanCte1 = Cte1; cleanTimeStamps = timeStamp; end [Cte2, timeStamp] = thingSpeakRead(readChannelID,'Fields',4,'numPoints', 2, 'ReadKey', readAPIKey); anyMissingValues = sum(isnan(Cte2)); if sum(anyMissingValues) > 0 missingValueIndex = find(~sum(isnan(Cte2),2)); cleanCte2 = Cte2(missingValueIndex, :); cleanTimeStamps = timeStamp(missingValueIndex); else cleanCte2 = Cte2; cleanTimeStamps = timeStamp; end Corriente = round([cleanCte1 + cleanCte2],1); display (Corriente, 'Corriente') %%%%%%%%%%%%%%%%%%%%%% VOLTAJE %%%%%%%%%%%%%%%%%%%%%% [Voltaje, timeStamp] = thingSpeakRead(readChannelID,'Fields',2,'numPoints', 2, 'ReadKey', readAPIKey); anyMissingValues = sum(isnan(Voltaje)); if sum(anyMissingValues) > 0 missingValueIndex = find(~sum(isnan(Voltaje),2)); cleanVoltaje = Voltaje(missingValueIndex, :); cleanTimeStamps = timeStamp(missingValueIndex); else cleanVoltaje = Voltaje; cleanTimeStamps = timeStamp; end display (cleanVoltaje, 'Voltaje') %%%%%%%%%%%%%%%%%%%%%% CALCULO DE POTENCIA %%%%%%%%%%%%%%%%%%%%%% Potencia = round([Corriente * cleanVoltaje],0) %%%%%%%%%%%%%%%%%%%%%% CALCULO DE ENERGIA %%%%%%%%%%%%%%%%%%%%%% [Energia1, timeStamp] = thingSpeakRead(readChannelID,'Fields',3,'numPoints', 2, 'ReadKey', readAPIKey); anyMissingValues = sum(isnan(Energia1)); if sum(anyMissingValues) > 0 missingValueIndex = find(~sum(isnan(Energia1),2)); cleanEnergia1 = Energia1(missingValueIndex, :); cleanTimeStamps = timeStamp(missingValueIndex); else cleanEnergia1 = Energia1; cleanTimeStamps = timeStamp; end [Energia2, timeStamp] = thingSpeakRead(readChannelID,'Fields',5,'numPoints', 2, 'ReadKey', readAPIKey); anyMissingValues = sum(isnan(Energia2)); if sum(anyMissingValues) > 0 missingValueIndex = find(~sum(isnan(Energia2),2)); cleanEnergia2 = Energia2(missingValueIndex, :); cleanTimeStamps = timeStamp(missingValueIndex); else cleanEnergia2 = Energia2; cleanTimeStamps = timeStamp; end Energia = [cleanEnergia1 + cleanEnergia2]; display (Energia, 'Energia') %%%%%%%%%%%%%%%%% Write the results in fields 6, 7 and 8 of the same channel %%%%%%%%%%%%%%%%%%%% thingSpeakWrite(writeChannelID, 'Fields', [6,7,8], 'Values',... [Corriente, Potencia, Energia],'WriteKey',writeAPIKey); OUTPUT: Corriente = 3.4000 Voltaje = 116 Potencia = 394 Energia = 0.0040
Ignacio in Discussions
上次活动时间: 2024-5-28

I have an Arduino Uno R3 with an integrated ESP 8266. With the Arduino Uno, I measure some capacitive humidity sensors and a DHT 22 temperature and humidity sensor. The measurements are sent to the serial port and the ESP 8266 picks them up and uploads them to ThingSpeak. My problem is that it does this randomly and not in the assigned fields. Could someone help me? Thank you very much random ESP 8266 data Are you using the ThingSpeak library? Have you compared your code to that code or to the examples code in the documentation? After you have compared, please share abbreviated parts of your code that are responsible for writing data and connecting to the server. Thank you very much Christopher, the code I have used is: #include <ESP8266WiFi.h> #include <ThingSpeak.h> const char* ssid = "xxxxxx"; const char* password = "xxxxx"; char thingSpeakAddress[] = "api.thingspeak.com"; String APIKey = "xxxxxx"; unsigned long channelNumber = xxxxx; WiFiClient client; void setup() { Serial.begin(115200); WiFi.begin(ssid, password); unsigned long startAttemptTime = millis(); while (WiFi.status() != WL_CONNECTED && millis() - startAttemptTime < 5000) { delay(500); Serial.print("."); } if(WiFi.status() != WL_CONNECTED) { Serial.println("Failed to connect to WiFi"); } ThingSpeak.begin(client); } void loop() { if (Serial.available()) { String data = Serial.readStringUntil('\n'); int commaIndex[6]; commaIndex[0] = data.indexOf(','); for(int i=1; i<6; i++){ commaIndex[i] = data.indexOf(',', commaIndex[i-1] + 1); } if(commaIndex[5] > 0) { String humidity1 = data.substring(0, commaIndex[0]); String humidity2 = data.substring(commaIndex[0] + 1, commaIndex[1]); String humDHT = data.substring(commaIndex[1] + 1, commaIndex[2]); String tempDHT = data.substring(commaIndex[2] + 1, commaIndex[3]); String tempC = data.substring(commaIndex[3] + 1, commaIndex[4]); String relay1Count = data.substring(commaIndex[4] + 1, commaIndex[5]); String relay2Count = data.substring(commaIndex[5] + 1); Serial.println("humidity1: " + humidity1); Serial.println("humidity2: " + humidity2); Serial.println("humDHT: " + humDHT); Serial.println("tempDHT: " + tempDHT); Serial.println("tempC: " + tempC); Serial.println("relay1Count: " + relay1Count); Serial.println("relay2Count: " + relay2Count); ThingSpeak.setField(1, humidity1.toInt()); ThingSpeak.setField(2, humidity2.toInt()); ThingSpeak.setField(3, humDHT.toFloat()); ThingSpeak.setField(4, tempDHT.toFloat()); ThingSpeak.setField(5, tempC.toFloat()); ThingSpeak.setField(6, relay1Count.toInt()); ThingSpeak.setField(7, relay2Count.toInt()); ThingSpeak.writeFields(channelNumber, APIKey.c_str()); } else { Serial.println("Invalid data format"); } } delay(20000); } I show you the graphs where you can see the response, the sensors through the serial port and the LCD give correct readings, but when passing to thingspeak they come out random I've already found the error; we need to remove the serialprint section I am surprised that would make a differece, but Im glad to hear you found an error to fix. Can you post the working code for others who find this topic? I would imagine that the way you are finding commas in your input data is potentially fragile. I would consider printing the input and output data to check that part in case you are still seeing any issues. Also, I have had times where I need to wait longer than 5 seconds to conenct, especially on an esp8266 in a weak WiFi network. You may want to increase the startAttempTime comparison constant. arduino uno r3 with esp 8266
Chris Nas in MATLAB Answers
上次活动时间: 2024-4-19

Hey, I am currently programming something in ArduinoIDE for an ESP8266 to read my sensor data that is already uploaded to TS. For this, I use the function: ThingSpeak.readMultipleFields(CHANNELID,READKEY). Unfortunately, I found that the server no longer returns the correct data. Here some debug Log from the Arduino library right after caling ThingSpeak.readMultipleFields(CHANNELID,READKEY): ts::readRaw (channelNumber: 13xxxxx readAPIKey: H89OOxxYFXxxxxxx suffixURL: "/feeds/last.txt?status=true&location=true") Connect to default ThingSpeak: api.thingspeak.com:80...Success. GET "/channels/13xxxxx/feeds/last.txt?status=true&location=true" Got Status of 200 Content Length: 210 Found end of header Response: "{"created_at":"2021-04-06T20:25:06Z","entry_id":5,"field1":null,"field2":null,"field3":null,"field4":null,"field5":"27.82000","field6":"28.96680","latitude":null,"longitude":null,"elevation":null,"status":null}" Read: "{"created_at":"2021-04-06T20:25:06Z","entry_id":5,"field1":null,"field2":null,"field3":null,"field4":null,"field5":"27.82000","field6":"28.96680","latitude":null,"longitude":null,"elevation":null,"status":null}" disconnected. As you can see, field 4 returns "null". When reading the same Channel and field with the function: ThingSpeak.readFloatField(CHANNELID,FIELD ID,READKEY) I get: ts::readStringField(channelNumber: 13xxxxx readAPIKey: H89OOxxYFXxxxxxx field: 4) ts::readRaw (channelNumber: 13xxxxx readAPIKey: H89OOxxYFXxxxxxx suffixURL: "/fields/4/last") Connect to default ThingSpeak: api.thingspeak.com:80...Success. GET "/channels/13xxxxx/fields/4/last" Got Status of 200 Content Length: 8 Found end of header Response: "29.94141" Read: "29.94141" disconnected. And this is the right value. Im using the latest Version from TS arduino Library. I already opend an issue on Github but there is no reaction on it. https://github.com/mathworks/thingspeak-arduino/issues/80 Does anyone have any ideas? Greetings!
Hans Scharler in Discussions
上次活动时间: 2023-9-21

The ThingSpeak Communication Library for Arduino, ESP8266 and ESP32 enables an Arduino or other compatible hardware to write or read data to or from ThingSpeak, an open data platform for the Internet of Things with MATLAB analytics and visualization. Link: <https://github.com/mathworks/thingspeak-arduino> Installation: In the Arduino IDE, choose Sketch/Include Library/Manage Libraries. Click the ThingSpeak Library from the list, and click the Install button. Compatible Hardware: * Arduino/Genuino or compatible using a WiFi Shield * Arduino/Genuino or compatible using a WiFi Shield 101 (Use the WiFi101 library version 0.13.0 or older.) * Arduino/Genuino or compatible using an Ethernet Shield * Arduino/Genuino or compatible using a MKR ETH Shield * Arduino MKR1000 * Arduino MKR1010 * Arduino VIDOR 4000 * Arduino GSM 14000 * Arduino Uno WiFi Rev2 * Arduino Yún (Rev1 and Rev2) * ESP8266 programming directly (tested with SparkFun ESP8266 Thing - Dev Board and NodeMCU 1.0 module) * ESP8266 via AT commands * ESP32 (tested with SparkFun ESP32 Thing) Tutorial: <https://nothans.com/thingspeak-tutorials/arduino/send-data-to-thingspeak-with-arduino> ThingSpeak Communication Library for Arduino, ESP8266 and ESP32 Along with some performance improvements, the latest version of the library supports reading from multiple fields of a channel to your device with a single command. ThingSpeak.readMultipleFields(ChannelNumber); Mr Chris, How do i read a field value at a specific timestamp The Arduino library doesn't include the ability to read a particular timestamp. We've chosen a reduced number of features to keep the footprint smaller. The best way to achieve the result you are looking for is to use the REST API call for <https://www.mathworks.com/help/thingspeak/readdata.html Read Data> with the start and end parameters to get the date you are interested in. There is an example in the documentation that shows how to send a REST call but its a POST. You need a GET. Instead of these lines in that code: client.println( "POST /update HTTP/1.1" ); client.println( "Host: api.thingspeak.com" ); client.println( "Connection: close" ); client.println( "Content-Type: application/x-www-form-urlencoded" ); client.println( "Content-Length: " + String( postData.length() ) ); client.println(); client.println( postData ); Serial.println( postData ); Use something like this, changing the URL for your needs: url = 'https://api.thingspeak.com/channels/9/feeds.csv?start=2011-11-11%2010:10:10&end=2011-11-11%2011:11:11" client.println(String("GET ") + url); Thank you Chris. you are the best. Hello sir, Where should I move the secrets.h file such as the one for ESP32 https://github.com/mathworks/thingspeak-arduino/tree/master/examples/ESP32/WriteSingleField Already checked the instructions at https://www.arduino.cc/en/Guide/Libraries but I cannot find a method to add a bare .h -file (only .zip files). The secrets file should be located in then same directory as the .ino file. You can create a new file in the Arduino IDE using the plus button by the tabs near the top. hi i was ending data to my channel and then i dont know what happend my channel dosent recive any value plz if u could help me bc my project discussion next week ,if we could speak on e-mail or telegram i apriceat that Start a new question on MATLAB answers pelase. You can see the ask a question button if you scroll past the discussion section. Be sure to include your problem description, your hardware, what youve tried, what you observed, and perhaps even a small snippet of the code you think is causing the problem. I have done some basic testing of the ThingSpeak Communication Arduino library with the Raspberry Pi Pico W board using the Philhower Arduino-Pico implementation for Arduino {Arduino-Pico} and it appears to work correctly. However, there is one complaint generated when building code using the Thingspeak library and that is a warning as follows: WARNING: library ThingSpeak claims to run on avr, esp8266, sam, samd, esp32, samd_beta, megaavr architecture(s) and may be incompatible with your current board which runs on rp2040 architecture(s). To remove this warning, add 'rp2040' to the list of architectures in the "library.properties" file. Hi, I have Arduino UNO SMD, how could I connect it to THingSpeak ? which example should i use ?? Thank you You will need some way to connect the device to a network. Wi-Fi is probably the easiest and most versatile. There is a Wi-Fi adapter board for UNO or you can use an esp32 to connect the UNO to Wi-Fi. In this configuration, you use serial communication to send data from the UNO to the ESP. Since the ESP32 is about as powerful (or more) than the UNO, my preference is just to use the ESP32 directly and skip the UNO. arduino esp32 esp8266
Muhammad in MATLAB Answers
上次活动时间: 2023-6-8

esp8266 keeps displaying 0 even though the field is 1, and it's not writing to it. it was working fine for months. and today out of the blue it's not working. checked the esp and it's working fine. tried writing and reading from the channel using an app and it's working fine. what could be the problem? void loop() { int A = ThingSpeak.readLongField(ChannelNumber, FieldNumber1, ReadAPIKey); Serial.println(A); if (A == 1 && !relayTriggered) { // only trigger the relay if it hasn't been triggered before digitalWrite(relay, LOW); delay(200); digitalWrite(relay, HIGH); ThingSpeak.writeField(ChannelNumber, FieldNumber1, 1, WriteAPIKey); // Write 0 back to FieldNumber1 using ThingSpeak API relayTriggered = true; // set the flag to true after the relay has been triggered } else if (A == 0) { relayTriggered = false; // reset the flag when the field value changes to 0 } ThingSpeak.writeField(ChannelNumber, FieldNumber1, 1, WriteAPIKey); }
Tom BS in Discussions
上次活动时间: 2022-11-15

Hello, Can someone please give me a hint how the settings at Tasmoto have to be made in order to send data via MQTT to ThingSpeak. Halil Kemal has an open channel tag: tasmota where this seems to work. Thank you in advance for your support. TOM How to config tasmota? The MQTT publish page shows you most of the relevant settings. The desktop client example is also a good wat to troubleshoot and learn the settings. tasmota esp8266 own thing
Jakub R in MATLAB Answers
上次活动时间: 2022-9-18

Hello, I have a problem to write a bulk-update using csv format. I have some experience with thingspeak using JSON update method, but I need to change it because *csv format would be more RAM-saving method in case of bulk update (less characters = less memory needed). I was trying to change my code written for JSON method to csv according to instructions: https://www.mathworks.com/help/thingspeak/bulkwritecsvdata.html but my example-string csv_feed is not accepted by Thingspeak server. I don't have ideas where is the problem, I tried to comment "//" some non-necessery lines, because in API's example, those lines doesn't appears in code. Thingspeak response code is always the same: 401, meaning "authorization required". But I wrote in code "write_api_key" properly I think (I'm sure that API key and channel number is the same as it is in channel settings on Thingspeak page). The key is authentic, I don't have important data on this channel and I'll change the key after getting rid problems with that code. Without success, I've been changing csv_feed content with diffrent time format (I'd like to use EPOCH time), diffrent number of commas representing field values and I'm still stuck with that code. Could anybody show my mistake? Thank you in advance, Jakub char csv_feed[] = "write_api_key%3DxxxxxxxxxxxxxxxxC%26time_format%3Dabsolute%26updates%3D1662883022%2C20%2C%2C%2C%2C%2C%2C%2C%2C%2C%2C%2C"; String csv_lenght = String(strlen(csv_feed)+1); if(client.connect(server, 80)){ client.println("POST /channels/647137/bulk_update.csv HTTP/1.1"); client.println("Host: api.thingspeak.com"); //client.println("User-Agent: mw.doc.bulk-update (Arduino ESP8266)"); //client.println("Connection: close"); client.println("Content-Type: application/x-www-form-urlencoded"); client.println("time_format: absolute"); //client.println("write_api_key: xxxxxxxxxxxxxxxx"); client.println("Content-Length: "+csv_lenght); client.println(); client.println(csv_feed);
Fariha Islam in MATLAB Answers
上次活动时间: 2022-5-26

I have created 3 fields for 3 of my sensor datas (gsr sensor, dht22 temperature and humidity sensor) . But the values are not updated into their respective fields simultaneously. I have written the code as follows, it would be very kind if someone could help me out. Thank you. #include <dht.h> #include <SoftwareSerial.h> dht DHT; #define DHT11_PIN 12 #define RX 2 #define TX 3 const int GSR=A2; int sensorValue=0; int gsr_average=0; String AP = "XXXXXXXXXXX"; // AP NAME String PASS = "XXXXXXXXXXXXX"; // AP PASSWORD String API = "YYYYYYYYYYYY"; // Write API KEY String HOST = "api.thingspeak.com"; String PORT = "80"; //String field = "field1"; int countTrueCommand; int countTimeCommand; boolean found = false; //int valSensor=1; 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() { //valSensor = getSensorData(); sendtoServer(); } String getTemperatureValue(){ int chk = DHT.read22(DHT11_PIN); float t= DHT.temperature; Serial.print(" Temperature(C)= "); Serial.println(DHT.temperature); delay(50); return String (t); } String getHumidityValue(){ // int chk = DHT.read22(DHT11_PIN); float h= DHT.humidity; Serial.print(" Humidity in %= "); Serial.println(DHT.humidity); delay(50); return String (h); } String getGSRValue(){ long sum=0; for(int i=0;i<10;i++) //Average the 10 measurements to remove the glitch { sensorValue=analogRead(GSR); sum += sensorValue; delay(5); } gsr_average = sum/10; Serial.println(gsr_average); return String(gsr_average); } void sendtoServer(){ String getData = "GET /update?api_key="+ API +"&field1="+ getGSRValue(); 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(1000);countTrueCommand++; sendCommand("AT+CIPCLOSE=0",5,"OK"); String getData2 = "GET /update?api_key="+ API +"&field2="+ getTemperatureValue(); sendCommand("AT+CIPMUX=1",5,"OK"); sendCommand("AT+CIPSTART=0,\"TCP\",\""+ HOST +"\","+ PORT,15,"OK"); sendCommand("AT+CIPSEND=0," +String(getData2.length()+4),4,">"); esp8266.println(getData2);delay(500);countTrueCommand++; sendCommand("AT+CIPCLOSE=0",5,"OK"); String getData3 = "GET /update?api_key="+ API +"&field3="+ getHumidityValue(); sendCommand("AT+CIPMUX=1",5,"OK"); sendCommand("AT+CIPSTART=0,\"TCP\",\""+ HOST +"\","+ PORT,15,"OK"); sendCommand("AT+CIPSEND=0," +String(getData3.length()+4),4,">"); esp8266.println(getData3);delay(250);countTrueCommand++; sendCommand("AT+CIPCLOSE=0",5,"OK"); } 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; }
Sarfaraz Khan in MATLAB Answers
上次活动时间: 2022-5-19

My code is working properly but i am not recevind the data at thingspeak if i can get any help ?? here is the code #include <SoftwareSerial.h> #include <SimpleDHT.h> #include <Wire.h> #include "ThingSpeak.h" #include <LiquidCrystal_I2C.h> #include <dht11.h> #define RX 3 #define TX 2 #define dht_apin 11 // Analog Pin sensor is connected to dht11 dhtObject; String AP = "Khan"; // AP NAME String PASS = "Pakistan2"; // AP PASSWORD String API = "xxxxxxxxx"; // Write API KEY String HOST = "api.thingspeak.com"; //String HOST = "184.106.153.149"; String PORT = "80"; String field = "field1"; int countTrueCommand; int countTimeCommand; boolean found = false; int valSensor = 1; int pinDHT11 = 11; SimpleDHT11 dht11(pinDHT11); LiquidCrystal_I2C lcd(0x27, 16, 2); 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() { String getData = "GET /update?api_key="+ API +"&field1="+getTemperatureValue()+"&field2="+getHumidityValue(); 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(2000);countTrueCommand++; sendCommand("AT+CIPCLOSE=0",5,"OK"); } String getTemperatureValue(){ dhtObject.read(dht_apin); Serial.print(" Temperature(C)= "); int temp = dhtObject.temperature; Serial.println(temp); delay(50); return String(temp); } String getHumidityValue(){ dhtObject.read(dht_apin); Serial.print(" Humidity in %= "); int humidity = dhtObject.humidity; Serial.println(humidity); delay(50); return String(humidity); } void sendCommand(String command, int maxTime, char readReplay[]) { Serial.print(countTrueCommand); Serial.print(". at command => "); Serial.print(command); Serial.print(" "); lcd.begin(); // Turn on the blacklight and print a message. lcd.backlight(); lcd.print("Tempature "); lcd.print((String)getTemperatureValue()); lcd.print("C"); lcd.setCursor(0, 1); lcd.print("Humidity "); lcd.print((String)getHumidityValue()); lcd.print("%"); delay(1000); 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; }
Halis Safa Turan in MATLAB Answers
上次活动时间: 2022-4-2

Hello everyone I want to control my led which is connected to arduino. I have esp8266 module I can send data to thingspeak with this module but I couldn't retrieve data from thingspeak. What is the easiest way for this application?
Matt Hosini in MATLAB Answers
上次活动时间: 2022-2-18

Hi guys, One way of posting multiple data at once is bulk-write JSON Data. There is an example re this here, which shows how to update the data on ESP8266 frequently. I can't work out step 8, which expalins how to update the JSON file. Could you please provide me a reference/tutorial/manual so that I can upskill myself to work this out? Also, I need to send the temperature readings (variables). Do I need to define the temp data as object or array on JSON? Below provides the code for step 8. // Updates the josnBuffer with data void updatesJson(char* jsonBuffer){ /* JSON format for updates paramter in the API * This examples uses the relative timestamp as it uses the "delta_t". You can also provide the absolute timestamp using the "created_at" parameter * instead of "delta_t". * "[{\"delta_t\":0,\"field1\":-70},{\"delta_t\":3,\"field1\":-66}]" */ // Format the jsonBuffer as noted above strcat(jsonBuffer,"{\"delta_t\":"); unsigned long deltaT = (millis() - lastUpdateTime)/1000; size_t lengthT = String(deltaT).length(); char temp[4]; String(deltaT).toCharArray(temp,lengthT+1); strcat(jsonBuffer,temp); strcat(jsonBuffer,","); long rssi = WiFi.RSSI(); strcat(jsonBuffer, "\"field1\":"); lengthT = String(rssi).length(); String(rssi).toCharArray(temp,lengthT+1); strcat(jsonBuffer,temp); strcat(jsonBuffer,"},"); // If posting interval time has reached 2 minutes, update the ThingSpeak channel with your data if (millis() - lastConnectionTime >= postingInterval) { size_t len = strlen(jsonBuffer); jsonBuffer[len-1] = ']'; httpRequest(jsonBuffer); } lastUpdateTime = millis(); // Update the last update time }
Matthias Borremans in MATLAB Answers
上次活动时间: 2022-2-9

Hi all, I have a ds18b20 and esp8266 with espeasy which posts a temperature reading to thingspeak every 5 minutes, works without any issue. I want to have multiple fields to be able to show a daily average. I think this is not possible with espeasy directly so i have to get some workaround with the visualizations. I have the code below to show an average, it outputs a number, but nothing is plotted. % Read temperature over the past hour from a ThingSpeak channel readChannelID = 1462749; TemperatureFieldID = 1; readAPIKey = '__REDACTED__'; % Get temperature data for the last 60 minutes [data, timeStamps ] = thingSpeakRead(readChannelID,'Fields',[TemperatureFieldID], 'NumPoints',30,'ReadKey',readAPIKey); % Calculate the average temperature avgTemperature = mean(data); display(avgTemperature,'Average Temperature'); % Plot temperature and timestamp plot(timeStamps,avgTemperature) ylabel('temperature (°C)');
boonchin ong in Discussions
上次活动时间: 2021-12-24

I am using TX and RX pin of arduino connect to RX and TX pin of NodeMCU. The data does not received, the data upload to thingspeak is zero. How to send data from arduino to NodeMCU? I ady using the software serial (D2,D3) for other device. Can I straight away use TX and RX pin? This is my arduino coding: { #include <SoftwareSerial.h> #include <Wire.h> #include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h> //#include <AltSoftSerial.h> // For the i2c supported Oled display module which is 128x64 #define SCREEN_WIDTH 128 // OLED display width, in pixels #define SCREEN_HEIGHT 64 // OLED display height, in pixels #define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin) Adafruit_SSD1306 display(128, SCREEN_HEIGHT, &Wire, OLED_RESET); //declare the digital to control the operation of RS-485 modbus #define RE 8 // The following are the Inquiry frames which are send to the NPK sensor //for reading the Nitrogen, Phosphorus, and Potassium values // We defined three arrays with names nitro_inquiry_frame, phos_inquiry_frame, and pota_inquiry_frame // Each inquiry frame have 8 values const byte nitro_inquiry_frame[] = {0x01,0x03, 0x00, 0x1e, 0x00, 0x01, 0xe4, 0x0c}; const byte phos_inquiry_frame[] = {0x01,0x03, 0x00, 0x1f, 0x00, 0x01, 0xb5, 0xcc}; const byte pota_inquiry_frame[] = {0x01,0x03, 0x00, 0x20, 0x00, 0x01, 0x85, 0xc0}; char buffer[40]; byte values[11]; SoftwareSerial modbus(2,3); //AltSoftSerial espSerial; // we will need three variables of the type byte to store the values of // Nitrogen, phosphorus, and Potassium. byte nitrogen_val,phosphorus_val,potassium_val; void setup() { Serial.begin(115200); modbus.begin(4800); //espSerial.begin(1200); pinMode(RE, OUTPUT); display.begin(SSD1306_SWITCHCAPVCC, 0x3C); //initialize with the I2C addr 0x3C (128x64) delay(500); display.clearDisplay(); display.setCursor(25, 15); display.setTextSize(1); display.setTextColor(WHITE); display.println(" NPK Sensor"); display.setCursor(25, 35); display.setTextSize(1); display.print("Initializing"); display.display(); } void loop() { nitrogen_val = nitrogen(); delay(100); phosphorus_val = phosphorous(); delay(100); potassium_val = potassium(); delay(100); //------Sending Data to ESP8266--------// sprintf(buffer,"*%03d%03d%03d#",nitrogen_val,phosphorus_val,potassium_val);//Sending *xxxxxxxxx# to esp8266 Serial.println(buffer); delay(2000); //------------------------------------// // The following code is used to display the data on the Oled display display.clearDisplay(); display.setTextSize(2); display.setCursor(0, 5); display.print("N: "); display.print(nitrogen_val); display.setTextSize(1); display.print(" mg/kg"); display.setTextSize(2); display.setCursor(0, 25); display.print("P: "); display.print(phosphorus_val); display.setTextSize(1); display.print(" mg/kg"); display.setTextSize(2); display.setCursor(0, 45); display.print("K: "); display.print(potassium_val); display.setTextSize(1); display.print(" mg/kg"); display.display(); } byte nitrogen(){ digitalWrite(RE,HIGH); delay(10); if(modbus.write(nitro_inquiry_frame,sizeof(nitro_inquiry_frame))==8){ digitalWrite(RE,LOW); // When we send the inquiry frame to the NPK sensor, then it replies with the response frame // now we will read the response frame, and store the values in the values[] arrary, we will be using a for loop. for(byte i=0;i<7;i++){ //Serial.print(modbus.read(),HEX); values[i] = modbus.read(); // Serial.print(values[i],HEX); } Serial.println(); } return values[5]; // returns the Nigtrogen value only, which is stored at location 4 in the array } byte phosphorous(){ digitalWrite(RE,HIGH); delay(10); if(modbus.write(phos_inquiry_frame,sizeof(phos_inquiry_frame))==8){ digitalWrite(RE,LOW); for(byte i=0;i<7;i++){ //Serial.print(modbus.read(),HEX); values[i] = modbus.read(); // Serial.print(values[i],HEX); } Serial.println(); } return values[5]; } byte potassium(){ digitalWrite(RE,HIGH); delay(10); if(modbus.write(pota_inquiry_frame,sizeof(pota_inquiry_frame))==8){ digitalWrite(RE,LOW); for(byte i=0;i<7;i++){ //Serial.print(modbus.read(),HEX); values[i] = modbus.read(); //Serial.print(values[i],HEX); } Serial.println(); } return values[5]; } } if true #include <SoftwareSerial.h> #include <Wire.h> #include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h> //#include <AltSoftSerial.h> // For the i2c supported Oled display module which is 128x64 #define SCREEN_WIDTH 128 // OLED display width, in pixels #define SCREEN_HEIGHT 64 // OLED display height, in pixels #define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin) Adafruit_SSD1306 display(128, SCREEN_HEIGHT, &Wire, OLED_RESET); //declare the digital to control the operation of RS-485 modbus #define RE 8 // The following are the Inquiry frames which are send to the NPK sensor //for reading the Nitrogen, Phosphorus, and Potassium values // We defined three arrays with names nitro_inquiry_frame, phos_inquiry_frame, and pota_inquiry_frame // Each inquiry frame have 8 values const byte nitro_inquiry_frame[] = {0x01,0x03, 0x00, 0x1e, 0x00, 0x01, 0xe4, 0x0c}; const byte phos_inquiry_frame[] = {0x01,0x03, 0x00, 0x1f, 0x00, 0x01, 0xb5, 0xcc}; const byte pota_inquiry_frame[] = {0x01,0x03, 0x00, 0x20, 0x00, 0x01, 0x85, 0xc0}; char buffer[40]; byte values[11]; SoftwareSerial modbus(2,3); //AltSoftSerial espSerial; // we will need three variables of the type byte to store the values of // Nitrogen, phosphorus, and Potassium. byte nitrogen_val,phosphorus_val,potassium_val; void setup() { Serial.begin(115200); modbus.begin(4800); //espSerial.begin(1200); pinMode(RE, OUTPUT); display.begin(SSD1306_SWITCHCAPVCC, 0x3C); //initialize with the I2C addr 0x3C (128x64) delay(500); display.clearDisplay(); display.setCursor(25, 15); display.setTextSize(1); display.setTextColor(WHITE); display.println(" NPK Sensor"); display.setCursor(25, 35); display.setTextSize(1); display.print("Initializing"); display.display(); } void loop() { nitrogen_val = nitrogen(); delay(100); phosphorus_val = phosphorous(); delay(100); potassium_val = potassium(); delay(100); //------Sending Data to ESP8266--------// sprintf(buffer,"*%03d%03d%03d#",nitrogen_val,phosphorus_val,potassium_val);//Sending *xxxxxxxxx# to esp8266 Serial.println(buffer); delay(2000); //------------------------------------// // The following code is used to display the data on the Oled display display.clearDisplay(); display.setTextSize(2); display.setCursor(0, 5); display.print("N: "); display.print(nitrogen_val); display.setTextSize(1); display.print(" mg/kg"); display.setTextSize(2); display.setCursor(0, 25); display.print("P: "); display.print(phosphorus_val); display.setTextSize(1); display.print(" mg/kg"); display.setTextSize(2); display.setCursor(0, 45); display.print("K: "); display.print(potassium_val); display.setTextSize(1); display.print(" mg/kg"); display.display(); } byte nitrogen(){ digitalWrite(RE,HIGH); delay(10); if(modbus.write(nitro_inquiry_frame,sizeof(nitro_inquiry_frame))==8){ digitalWrite(RE,LOW); // When we send the inquiry frame to the NPK sensor, then it replies with the response frame // now we will read the response frame, and store the values in the values[] arrary, we will be using a for loop. for(byte i=0;i<7;i++){ //Serial.print(modbus.read(),HEX); values[i] = modbus.read(); // Serial.print(values[i],HEX); } Serial.println(); } return values[5]; // returns the Nigtrogen value only, which is stored at location 4 in the array } byte phosphorous(){ digitalWrite(RE,HIGH); delay(10); if(modbus.write(phos_inquiry_frame,sizeof(phos_inquiry_frame))==8){ digitalWrite(RE,LOW); for(byte i=0;i<7;i++){ //Serial.print(modbus.read(),HEX); values[i] = modbus.read(); // Serial.print(values[i],HEX); } Serial.println(); } return values[5]; } byte potassium(){ digitalWrite(RE,HIGH); delay(10); if(modbus.write(pota_inquiry_frame,sizeof(pota_inquiry_frame))==8){ digitalWrite(RE,LOW); for(byte i=0;i<7;i++){ //Serial.print(modbus.read(),HEX); values[i] = modbus.read(); //Serial.print(values[i],HEX); } Serial.println(); } return values[5]; } end Have you taken a look at the library <https://github.com/mathworks/thingspeak-arduino here.> There are numerous examples in that git repository that can help you get started. arduino nodemcu eps 8266 iot project
Colin kerr in Discussions
上次活动时间: 2021-9-8

I'd appreciate comment on whether I understand the limitations with MQTT and low power. Using deep sleep the ESP12 consumes microamps and my sensor is insignificant. The big drain on the battery is WiFi. Sending an MQTT message is taking around 10ms which seems at first sight promising. Unfortunately it looks to me like deep sleep ends the connection, and reconnection takes 4 or more seconds. I'd thought that deep sleep, static IP, and MQTT were the way to get very low power consumption but it looks to me like they don't solve the problem. MQTT on ESP12 with battery power and static IP How often are you planning to make a connection and send data? That depends on the power consumption of each connection. Ideally 16s but I know that's not feasible unless time to connect is way less than I'm seeing. I calculate I can get 60 connections in 24 hours if I run off 2xAA Lithium and want them to last over 6 months. I discovered the ESP32-S2 a couple of days ago and it seems to be have a sleep mode that sends a beacon and averages 24uA. So that looks my best hope unless I can get the start up and MQTT connect well below 4 seconds. mqtt deep sleep static ip esp8266
BRIAN MINOR in MATLAB Answers
上次活动时间: 2021-9-7

I'm using the ThingSpeak library that I had downloaded from github on 10/27/20. I'm sending data to ThingSpeak just over every 15 seconds. The data will send without issue a couple of times and will return a value of 200, and then the next time will return a value of -301. I've incorporated a while loop to immediately send the data again when encountering this, and it always goes through successfully the second time. The only issue is that when I'm getting the -301 error it's pausing the program for about 10 seconds. When researching this issue, I was finding examples where the user was unable to send data at all, I wasn't really seeing examples of intermittent issues like mine. Any thoughts on what the issue could be? #include "ThingSpeak.h" #include <ESP8266WiFi.h> //------- WI-FI details ----------// char ssid[] = "xxxxxxxxx"; //SSID here char pass[] = "xxxxxxxxx"; // Passowrd here //-----------------------------// //----------- Channel details ----------------// unsigned long Channel_ID = xxxxxxxxx; // Your Channel ID const char * myWriteAPIKey = "xxxxxxxxxx"; //Your write API key //-------------------------------------------// #define SENSOR 2 const int Field_Number_1 = 1; int sensorVal = 0; unsigned long timeNow = 0; unsigned long timerStart = 0; unsigned long timerStart2 = 0; unsigned long instance = 0; int writeSuccess = 0; WiFiClient client; void setup() { // put your setup code here, to run once: Serial.begin(115200); WiFi.mode(WIFI_STA); ThingSpeak.begin(client); pinMode(SENSOR, INPUT); internet(); } void loop() { // put your main code here, to run repeatedly: timeNow = millis(); internet(); if (timeNow - timerStart > 2000) {} sensorVal = digitalRead(SENSOR); Serial.println(sensorVal); timerStart = millis(); } upload(); } void internet() { if (WiFi.status() != WL_CONNECTED) { while (WiFi.status() != WL_CONNECTED) { WiFi.begin(ssid, pass); delay(5000); } } } void upload() { if (timeNow - timerStart2 > 15100) { ThingSpeak.setField(1,(String)sensorVal); ThingSpeak.setField(2,(String)instance); writeSuccess = ThingSpeak.writeFields(Channel_ID, myWriteAPIKey); Serial.print("Write success: "); Serial.println(writeSuccess); while (writeSuccess == -301) { writeSuccess = ThingSpeak.writeFields(Channel_ID, myWriteAPIKey); Serial.print("Write success: "); Serial.println(writeSuccess); } timerStart2 = millis(); instance++; } }
Cristin Manora in MATLAB Answers
上次活动时间: 2021-8-20

I made a project with a soil moisture sensor but thingspeak can't receive the measurement data. i am using esp8266 nodemcu. I've also tried via https://api.thingspeak.com/update?api_key=xxxxxxxxxxxxxxxx&field1=0 manually..the result is incoming data. But not logging in by using esp866. this is my code : th#include <ESP8266WiFi.h> char ssid [] = "Manorangi"; char pw [] = "carpediem"; String apiKey = "xxxxxxxxxxxxxxxx"; char server [] = "api.thingspeak.com"; int soil_sensor = A0; WiFiClient client; void setup() { Serial.begin (115200); delay (10); WiFi.begin (ssid, pw); while (WiFi.status () != WL_CONNECTED) { delay (100); Serial.print ("..."); } Serial.print ("\n Connect to... "); Serial.println (ssid); Serial.print (" IP Address : "); Serial.print (WiFi.localIP ()); Serial.print ("\n"); } void loop () { int persenhumid = map (analogRead (soil_sensor),0,1023,100,0); if (client.connect (server,80)) { String postStr = apiKey+"&field1="+String(persenhumid)+"\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.print ("Kelembaban: "); Serial.print (persenhumid); Serial.println ("%"); Serial.print ("Mengirim data ke Thingpeak"); Serial.print ("\n"); } client.stop (); Serial.println ("Waiting..."); for (unsigned int i = 0; i< 20 ; i++) { delay (1000); } }
Craig Larson in MATLAB Answers
上次活动时间: 2021-8-9

This link showed me how to successfully do a JSON bulk upload from an ESP8266 to ThingSpeak. I would like to post 60 values in one bulk upload to save on batteries. I know that it is possible to do a CSV bulk upload of data that does not include the "delta_t" or "field1" ascii text for every datapoint as with JSON. This repeated JSON text really bloats the data transfer (about 2000 characters for 60 values). I did successfully complete the Postman example provided in this link but I am unable to mimic this action in the code on my ESP8266. Does anybody know where example code exists - I've been looking for days? Sorry so cryptic but I'm trying to keep my query trim.
Rey Mat in MATLAB Answers
上次活动时间: 2021-5-27

Hello I used the example program to write data to ThingSpeak and I have the following compilation error c:/users/name/.platformio/packages/toolchain-xtensa/bin/../lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld.exe: .pio\build\nodemcuv2\src\main.cpp.o:(.text.setup+0xc): undefined reference to `ThingSpeak' collect2.exe: error: ld returned 1 exit status *** [.pio\build\nodemcuv2\firmware.elf] Error 1 Here my include files #include <Arduino.h> #include <ESP8266WiFi.h> #include <secrets.h> #include <ThingSpeak.h> // always include thingspeak header file after other header files and custom macros I've searched on the web but I can't find a solution. If anyone can help me. Thank you in advance.
Md. Najmul Hasan in MATLAB Answers
上次活动时间: 2021-5-25

i am using arduino mega and esp 01.i am getting reading on serial monitor.but thingspeak shows 0 for 5 sensors data fields.where is the problem in this code please help me. Esp 01 code- #include "ThingSpeak.h" #include <ESP8266WiFi.h> char ssid[] = "xxxxxxx"; // SSID here char pass[] = "xxxxxxxx"; // Passowrd here unsigned long Channel_ID = xxxxxx; // Channel ID const char * myWriteAPIKey = "xxxxxxxx"; // Write API key const int Field_Number_1 = 1; const int Field_Number_2 = 2; const int Field_Number_3 = 3; const int Field_Number_4 = 4; const int Field_Number_5 = 5; String value = ""; int value_1 = 0, value_2 = 0, value_3 = 0, value_4 = 0, value_5 = 0; WiFiClient client; void setup() { Serial.begin(115200); WiFi.mode(WIFI_STA); ThingSpeak.begin(client); internet(); } void loop() { internet(); if (Serial.available() > 0) { delay(100); while (Serial.available() > 0) { value = Serial.readString(); if (value[0] == '*') { if (value[11] == '#') { value_1 = ((value[1] - 0x30) * 10 + (value[2] - 0x30)); value_2 = ((value[3] - 0x30) * 10 + (value[4] - 0x30)); value_3 = ((value[5] - 0x30) * 10 + (value[6] - 0x30)); value_4 = ((value[7] - 0x30) * 10 + (value[8] - 0x30)); value_5 = ((value[9] - 0x30) * 10 + (value[10] - 0x30)); } } } } upload(); } void internet() { if (WiFi.status() != WL_CONNECTED) { while (WiFi.status() != WL_CONNECTED) { WiFi.begin(ssid, pass); delay(5000); } } } void upload() { ThingSpeak.writeField(Channel_ID, Field_Number_1, value_1, myWriteAPIKey); delay(15000); ThingSpeak.writeField(Channel_ID, Field_Number_2, value_2, myWriteAPIKey); delay(15000); ThingSpeak.writeField(Channel_ID, Field_Number_3, value_3, myWriteAPIKey); delay(15000); ThingSpeak.writeField(Channel_ID, Field_Number_4, value_4, myWriteAPIKey); delay(15000); ThingSpeak.writeField(Channel_ID, Field_Number_5, value_5, myWriteAPIKey); delay(15000); value = ""; } arduino code- #include <dht.h> #define soilWet 56 #define soilDry 50 const int LM35 = A0; // Soil Temperature pin // lowest and highest sensor readings (Rain Detection) const int sensorMin = 0; // sensor minimum const int sensorMax = 1024; // sensor maximum #define sensorPower 5 // Motor pin int obstaclePin = 10; // IR sensor pin 7 int hasObstacle = HIGH; // High means no obstacle const int trigger = 34; const int echo = 35; long T; float distanceCM; dht DHT; #define DHT11_PIN 30 int humi,temp; void setup(){ pinMode(sensorPower, OUTPUT); // Initially keep the Motor OFF digitalWrite(sensorPower, HIGH); pinMode(obstaclePin, INPUT); pinMode(trigger, OUTPUT); pinMode(echo, INPUT); Serial.begin(9600); } void loop() { int moisture = (100 - ((analogRead(A1)/1023.00)*100)); digitalWrite(trigger, LOW); delay(10); digitalWrite(trigger, HIGH); delayMicroseconds(10); digitalWrite(trigger, LOW); T = pulseIn(echo, HIGH); distanceCM = T * 0.034; distanceCM = distanceCM / 2; int ADC; float tempS; ADC = analogRead(LM35); tempS = (ADC * 4.88); tempS = (tempS / 10); int sensorReading = analogRead(A2); // Rain detection pin A2 int range = map(sensorReading, sensorMin, sensorMax, 0, 3); // Rain detection switch (range) { case 0: // Sensor getting wet Serial.println("Rain Status : ***Raining***"); break; case 1: // Sensor getting wet Serial.println("Rain Status : **Rain Warning**"); break; case 2: // Sensor dry - To shut this up delete the " Serial.println("Not Raining"); " below. Serial.println("Rain Status : *Not Raining*"); break; } DHT.read11(DHT11_PIN); humi=DHT.humidity; temp=DHT.temperature; Serial.print("Air Temperature = "); Serial.print(temp); Serial.println("°C "); Serial.print("Air Humidity = "); Serial.print(humi); Serial.println(" %"); Serial.print("Distance = "); Serial.print(distanceCM); Serial.println("cm"); Serial.print("Soil Temperature = "); Serial.print(tempS); Serial.println("°C"); Serial.print("Soil Moisture = "); Serial.print(moisture); Serial.println(" %"); if (moisture < soilWet) { Serial.println("Status: Soil is too wet"); } else if (moisture >= soilWet && moisture < soilDry) { Serial.println("Status: Soil moisture is perfect"); } else { Serial.println("Status: Soil is too dry - time to water!"); } if (moisture < 35) { digitalWrite(sensorPower, HIGH); // turn ON motor Serial.println("Motor is ON"); } if (moisture > 35 && moisture < 37) { digitalWrite(sensorPower, HIGH); //turn ON motor Serial.println("Motor is ON"); } if (moisture > 38) { digitalWrite(sensorPower, LOW); // turn OFF motor Serial.println("Motor is OFF"); } hasObstacle = digitalRead(obstaclePin); //Reads the output of the obstacle sensor from the 7th PIN of the Digital section of the arduino if (hasObstacle == LOW) //LOW means something is ahead { Serial.println("Something is ahead !!!"); } else { Serial.println("Path is clear"); } Serial.println("--------------------------------------------------------------------------"); Serial.println(""); delay(3000); }
Chamath Vithanawasam in MATLAB Answers
上次活动时间: 2021-4-30

I've been uploading data from a set of moisture sensors to 6 channels on thingspeak (4 in one account and 2 in another). I am using free versions. I will be uploading less that 1000 messages a day, and there are large intervals inbetween the channels. This system worked fine for the past three weeks or so, but on the 24th of April, the data simply stopped uploading. I first tried to change the API key, then I tried to delete a channel and try again. I even tried sending sample data with no real values using a simplified code. Nothing seems to work. Any idea what may have happened? I am sending the code I've used for reference. //****************************Connections*****************************// //D0 ----------> EN (Mux) //D1 ----------> SCL (Screen) //D2 ----------> SDA (Screen) //D3 ----------> Temp Data (DS18B20) //D4 ----------> S0 (Mux) //D5 ----------> S1 (Mux) //D6 ----------> S2 (Mux) //D7 ----------> S3 (Mux) //D8 ----------> Relay //A0 ----------> Z (Mux) //********************************************************************// //******************************DS18B20******************************// #include <OneWire.h> #include <DallasTemperature.h> #define ONE_WIRE_BUS 0 OneWire oneWire(ONE_WIRE_BUS); DallasTemperature sensors(&oneWire); DeviceAddress sensor1 = {0x28, 0x90, 0x7F, 0xC7, 0x1F, 0x13, 0x1, 0xE0 }; //34 DeviceAddress sensor2 = { 0x28, 0xAA, 0x5E, 0x50, 0x19, 0x13, 0x2, 0xA3 }; //04 DeviceAddress sensor3 = { 0x28, 0x60, 0xF4, 0xB8, 0x1F, 0x13, 0x1, 0x1B }; //05 DeviceAddress sensor4 = { 0x28, 0xAA, 0xA2, 0xC, 0x19, 0x13, 0x2, 0xEE }; //03 DeviceAddress sensor5 = { 0x28, 0xAA, 0x9B, 0xF, 0x19, 0x13, 0x2, 0x11 }; //01 DeviceAddress sensor6 = { 0x28, 0xAA, 0x89, 0xF, 0x19, 0x13, 0x2, 0xEE }; //30 DeviceAddress sensor7 = { 0x28, 0xAA, 0xA8, 0xBB, 0x18, 0x13, 0x2, 0xEF }; //02 DeviceAddress sensor8 = { 0x28, 0xAA, 0xC5, 0x5D, 0x19, 0x13, 0x2, 0xF9 }; //32 DeviceAddress sensor9 = { 0x28, 0x36, 0x74, 0x45, 0x92, 0x18, 0x2, 0x13 }; //22 DeviceAddress sensor10 = { 0x28, 0x4F, 0xD2, 0x3C, 0x2F, 0x14, 0x1, 0x8A }; //31 DeviceAddress sensor11 = { 0x28, 0x2, 0x92, 0x45, 0x92, 0x18, 0x2, 0x64 }; //21 DeviceAddress sensor12 = { 0x28, 0xAA, 0x1D, 0x0, 0x19, 0x13, 0x2, 0xDC }; //33 DeviceAddress sensor13 = { 0x28, 0x7B, 0x1B, 0x45, 0x92, 0x5, 0x2, 0x37 }; //28 DeviceAddress sensor14 = { 0x28, 0xB6, 0x0, 0x45, 0x92, 0x11, 0x2, 0x39 }; //14 //********************************************************************// //******************************74HC4067******************************// #include "MUX74HC4067.h" //********************************************************************// //*******************************SCREEN*******************************// //SCL ----------> D1 //SDA ----------> D2 #include <SPI.h> #include <Wire.h> #include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h> #define SCREEN_WIDTH 128 // OLED display width, in pixels #define SCREEN_HEIGHT 64 // OLED display height, in pixels // Declaration for an SSD1306 display connected to I2C (SDA, SCL pins) #define OLED_RESET LED_BUILTIN //4 // Reset pin # (or -1 if sharing Arduino reset pin) Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET); //********************************************************************// //******************************74HC4067******************************// // Creates a MUX74HC4067 instance // 1st argument is the Arduino PIN to which the EN pin connects // 2nd-5th arguments are the Arduino PINs to which the S0-S3 pins connect //MUX74HC4067 mux(7, 8, 9, 10, 11); //Arduino MUX74HC4067 mux(16, 2, 14, 12, 13); //NodeMCU //********************************************************************// //******************************Internet******************************// #include <ESP8266WiFi.h> #include <WiFiClient.h> #include <ThingSpeak.h> const char* ssid = "SSID"; const char* password = "PASSWORD"; WiFiClient client; unsigned long Channel1 = censored; //2021 Moisture Set 1 const char * myWriteAPIKey1 = "censored"; unsigned long Channel2 = censored; //2021 Moisture Set 2 const char * myWriteAPIKey2 = "censored"; unsigned long Channel3 = censored; //2021 Moisture Set 3 const char * myWriteAPIKey3 = "censored"; unsigned long Channel4 = censored; //2021 Temperature Set 1 const char * myWriteAPIKey4 = "censored"; unsigned long Channel5 = censored; //2021 Temperature Set 2 const char * myWriteAPIKey5 = "censored"; //********************************************************************// //*****************************Constants******************************// int timeBetweenReadings = 60000; //1 minute //int delayForNewReadingCycle = 900000; //15 minutes //int delayForNewReadingCycle = 1800000; //30 minutes int delayForNewReadingCycle = 2400000; //40 minutes int MuxValues[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; //********************************************************************// //**************************Important pins****************************// #define relayPin 15 //********************************************************************// void startup() { Serial.println("."); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); // Print the IP address Serial.println(WiFi.localIP()); ThingSpeak.begin(client); delay(3000); } //********************************************************************// void readMuxVal(int x) { int data = 0; int mPerc = 0; data = mux.read(x); // Reads from channel i. Returns a value from 0 to 1023 mPerc=(-0.000000001219500040736946*(pow(data,4)))+(0.000002433251912455929*(pow(data,3)))+(-0.001531281295811*(pow(data,2)))+(0.227285203001156*(data))+(102.9068673556674); Serial.print("Potentiometer at channel "); Serial.print(x); Serial.print(" is at "); Serial.print(data); Serial.print(" ("); Serial.print((double)(data) * 100 / 1023); Serial.print("%%"); Serial.println(")"); display.setTextSize(1); // Normal 1:1 pixel scale display.setTextColor(WHITE); // Draw white text if (x >= 0 && x <= 4) display.setCursor(10, ((8 * x) + 17)); if (x >= 5 && x <= 7) display.setCursor(70, ((8 * x) - 23)); if (x >= 8 && x <= 11) display.setCursor(10, ((8 * x) - 47)); if (x >= 12 && x <= 15) display.setCursor(70, ((8 * x) - 79)); display.print("Y"); display.print(x); display.print(":"); display.print(mPerc); display.print("%"); if (x >= 0 && x <= 3) { ThingSpeak.writeField(Channel1, (x+1), mPerc, myWriteAPIKey1); delay (40000); ThingSpeak.writeField(Channel1, (x+5), data, myWriteAPIKey1); } if (x >= 4 && x <= 7) { ThingSpeak.writeField(Channel2, (x-3), mPerc, myWriteAPIKey2); delay (40000); ThingSpeak.writeField(Channel2, (x+1), data, myWriteAPIKey2); } if (x >= 8 && x <= 11) { ThingSpeak.writeField(Channel3, (x-7), mPerc, myWriteAPIKey3); delay (40000); ThingSpeak.writeField(Channel3, (x-3), data, myWriteAPIKey3); } display.display(); MuxValues[x] = mPerc; delay (timeBetweenReadings); } void setup() { //******************************74HC4067******************************// Serial.begin(9600); // Initializes serial port // Waits for serial port to connect. Needed for Leonardo only while ( !Serial ) ; // Configures how the SIG pin will be interfaced // e.g. The SIG pin connects to PIN A0 on the Arduino, // and PIN A0 is a analog input mux.signalPin(A0, INPUT, ANALOG); //********************************************************************// //*******************************SCREEN*******************************// // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3D for 128x64 Serial.println("SSD1306 allocation failed"); for (;;); // Don't proceed, loop forever } //********************************************************************// //*******************************RELAY********************************// pinMode(relayPin, OUTPUT); //********************************************************************// //******************************DS18B20******************************// sensors.begin(); //********************************************************************// } // Reads the 16 channels and reports on the serial monitor // the corresponding value read by the A/D converter void loop() { digitalWrite(relayPin, LOW); display.clearDisplay(); display.setTextSize(2); // Normal 1:1 pixel scale display.setTextColor(WHITE); // Draw white text display.setCursor(0,20); // Start at top-left corner display.print("Connecting..."); display.print(ssid); display.display(); startup(); if (WiFi.status() != WL_CONNECTED) { Serial.println("WiFi disconnected, reconnecting now."); startup(); } float data = 0; display.clearDisplay(); display.setTextSize(1); // Normal 1:1 pixel scale display.setTextColor(WHITE); // Draw white text display.setCursor(0, 0); // Start at top-left corner display.println("Connected to"); display.print(ssid); digitalWrite(relayPin, HIGH); readMuxVal(0); readMuxVal(1); readMuxVal(2); readMuxVal(3); readMuxVal(4); readMuxVal(5); readMuxVal(6); readMuxVal(7); display.clearDisplay(); display.setTextSize(1); // Normal 1:1 pixel scale display.setTextColor(WHITE); // Draw white text display.setCursor(0, 0); // Start at top-left corner display.println("Connected to"); display.print(ssid); readMuxVal(8); readMuxVal(9); readMuxVal(10); readMuxVal(11); display.clearDisplay(); display.setTextSize(1); // Normal 1:1 pixel scale display.setTextColor(WHITE); // Draw white text display.setCursor(0, 0); // Start at top-left corner display.println("Connected to"); display.print(ssid); Serial.print("Requesting temperatures..."); sensors.requestTemperatures(); // Send the command to get temperatures Serial.println("DONE"); Serial.print("Sensor 1(*C): "); data = sensors.getTempC(sensor1); Serial.println(data); if (data != 85 || data != -127) { ThingSpeak.writeField(Channel4, (1), data, myWriteAPIKey4); } display.setCursor(10, 24); display.print("T1: ");// Start at top-left corner display.print(data); display.display(); delay (timeBetweenReadings); Serial.print("Sensor 2(*C): "); data = sensors.getTempC(sensor2); Serial.println(data); if (data != 85 || data != -127) { ThingSpeak.writeField(Channel4, (2), data, myWriteAPIKey4); } display.setCursor(10, 32); display.print("T2: ");// Start at top-left corner display.print(data); display.display(); delay (timeBetweenReadings); digitalWrite(relayPin, LOW); //RELAY PIN SWITCHES OFF HERE Serial.print("Sensor 3(*C): "); data = sensors.getTempC(sensor3); Serial.println(data); if (data != 85 || data != -127) { ThingSpeak.writeField(Channel4, (3), data, myWriteAPIKey4); } display.setCursor(10, 40); display.print("T3: ");// Start at top-left corner display.print(data); display.display(); delay (timeBetweenReadings); Serial.print("Sensor 4(*C): "); data = sensors.getTempC(sensor4); Serial.println(data); if (data != 85 || data != -127) { ThingSpeak.writeField(Channel4, (4), data, myWriteAPIKey4); } display.setCursor(10, 48); display.print("T4: ");// Start at top-left corner display.print(data); display.display(); delay (timeBetweenReadings); Serial.print("Sensor 5(*C): "); data = sensors.getTempC(sensor5); Serial.println(data); if (data != 85 || data != -127) { ThingSpeak.writeField(Channel4, (5), data, myWriteAPIKey4); } display.setCursor(10, 56); display.print("T5: ");// Start at top-left corner display.print(data); display.display(); delay (timeBetweenReadings); Serial.print("Sensor 6(*C): "); data = sensors.getTempC(sensor6); Serial.println(data); if (data != 85 || data != -127) { ThingSpeak.writeField(Channel4, (6), data, myWriteAPIKey4); } display.setCursor(70, 24); display.print("T6: ");// Start at top-left corner display.print(data); display.display(); delay (timeBetweenReadings); Serial.print("Sensor 7(*C): "); data = sensors.getTempC(sensor7); Serial.println(data); if (data != 85 || data != -127) { ThingSpeak.writeField(Channel4, (7), data, myWriteAPIKey4); } display.setCursor(70, 32); display.print("T7: ");// Start at top-left corner display.print(data); display.display(); delay (timeBetweenReadings); Serial.print("Sensor 8(*C): "); data = sensors.getTempC(sensor8); Serial.println(data); if (data != 85 || data != -127) { ThingSpeak.writeField(Channel4, (8), data, myWriteAPIKey4); } display.setCursor(70, 40); display.print("T8: ");// Start at top-left corner display.print(data); display.display(); delay (timeBetweenReadings); Serial.print("Sensor 9(*C): "); data = sensors.getTempC(sensor9); Serial.println(data); if (data != 85 || data != -127) { ThingSpeak.writeField(Channel5, (1), data, myWriteAPIKey5); } display.setCursor(70, 48); display.print("T9: ");// Start at top-left corner display.print(data); display.display(); delay (timeBetweenReadings); Serial.print("Sensor 10(*C): "); data = sensors.getTempC(sensor10); Serial.println(data); if (data != 85 || data != -127) { ThingSpeak.writeField(Channel5, (2), data, myWriteAPIKey5); } display.setCursor(70, 56); display.print("T10: ");// Start at top-left corner display.print(data); display.display(); delay (timeBetweenReadings); display.clearDisplay(); display.setTextSize(1); // Normal 1:1 pixel scale display.setTextColor(WHITE); // Draw white text display.setCursor(0, 0); // Start at top-left corner //display.print("Readings"); display.println("Connected to"); display.print(ssid); Serial.print("Sensor 11(*C): "); data = sensors.getTempC(sensor11); Serial.println(data); if (data != 85 || data != -127) { ThingSpeak.writeField(Channel5, (3), data, myWriteAPIKey5); } display.setCursor(10, 24); display.print("T11: ");// Start at top-left corner display.print(data); display.display(); delay (timeBetweenReadings); Serial.print("Sensor 12(*C): "); data = sensors.getTempC(sensor12); Serial.println(data); if (data != 85 || data != -127) { ThingSpeak.writeField(Channel5, (4), data, myWriteAPIKey5); } display.setCursor(10, 32); display.print("T12: ");// Start at top-left corner display.print(data); display.display(); delay (timeBetweenReadings); Serial.print("Sensor 13(*C): "); data = sensors.getTempC(sensor13); Serial.println(data); if (data != 85 || data != -127) { ThingSpeak.writeField(Channel5, (5), data, myWriteAPIKey5); } display.setCursor(10, 40); display.print("T13: ");// Start at top-left corner display.print(data); display.display(); delay (timeBetweenReadings); Serial.print("Sensor 14(*C): "); data = sensors.getTempC(sensor14); Serial.println(data); if (data != 85 || data != -127) { ThingSpeak.writeField(Channel5, (6), data, myWriteAPIKey5); } display.setCursor(10, 48); display.print("T14: ");// Start at top-left corner display.print(data); display.display(); delay (delayForNewReadingCycle); }
Jeffrey Marchal in MATLAB Answers
上次活动时间: 2021-4-6

I have been working for tens of hours trying to understand the basics of Thingspeak. I am completely flummoxed... I am using a PIC and ESP8266 and trying to write to my Thingspeak Channel using a variety of ways that so far have proved useless... I really have tried to work through this without help. And this Community is only the second time I have been so confused that I am asking for help. I successfully connect to my local wireless network with the appropriate ESP8266 command: AT+CWJAP_CUR="MY_NETWORK_SSID","MY_PASSWORD" I can also get an "OK" response from this (I am leaving out the ESP8266 AT+CIPSEND=##, that just tells the ESP8266 how many bytes to send): AT+CIPSTART="TCP","API.THINGSPEAK.COM",80 (I sometimes used AT+CIPSTART="TCP","API.THINGSPEAK.COM",80, 50 to use keepalive?) From this starting point I have tried: POST /update HTTP/1.1 Host: api.thingspeak.com <- Error +IPD,272:HTTP/1.1 400 Bad Request and: POST https://api.thingspeak.com/update api_key=MY_WRITE_API_KEY<- Error +IPD,272:HTTP/1.1 400 Bad Request and: POST https://api.thingspeak.com/update X-THINGSPEAKAPIKEY=MY_WRITE_API_KEY<- Error +IPD,272:HTTP/1.1 400 Bad Request and literally hundreds of other permutations of things I have found on the web. I have tried to use the Arduino IDE and tried to build many examples of various projects with no success... I am pretty familiar with MPLABX, but the Arduino IDE has so far failed to build ANYTHING... I have looked through the various Arduino headers trying to write the simplest versions I can for the PIC I am using - all with no success.. I am desperate for something, anything to help me get something working. I have manually input commands to the ESP8266 unsing the AT command set, again without success in getting Thingspeak to LET ME IN. I really just need an example of the commands to send... Thanks In Advance For Anyone Willing To Help. I will not be a bother once I get this going a little better as I try to learn the rest on my own... I REALLY tried.
Durgesh Chaubey in Discussions
上次活动时间: 2021-4-4

Hey guys! i recentlly written a code for patient health monitoring system using arduino and configured with that thingspeak api so that i could collect the data gathered by my pulse rate sensor and temparature sensor to thingspeak cloud and things went very fine my programe is executing fine but the data is not coming on thingspeak cloud..please guys it's so urgent for me cause i have to show this project as mu finao year demonstration project please help me or call me my email is durgeshc1402@gmail.com and call me on 7355104033.. it's so urgent for me to get this project working . below is the code #include <LiquidCrystal.h> LiquidCrystal lcd(12, 11, 5, 4, 3, 2); #include <SoftwareSerial.h> #include <ThingSpeak.h> float pulse = 0; float temp= 0; SoftwareSerial ser(9,10); String apiKey = "KT8O9XXE4K5WMVWA"; // Variables int pulsePin = A0; // Pulse Sensor purple wire connected to analog pin 0 int blinkPin = 7 ; // pin to blink led at each beat int fadePin = 13; // pin to do fancy classy fading blink at each beat int fadeRate = 0; // used to fade LED on with PWM on fadePin // Volatile Variables, used in the interrupt service routine! volatile int BPM; // int that holds raw Analog in 0. updated every 2mS volatile int Signal; // holds the incoming raw data volatile int IBI = 600; // int that holds the time interval between beats! Must be seeded! volatile boolean Pulse = false; // "True" when User's live heartbeat is detected. "False" when nota "live beat". volatile boolean QS = false; // becomes true when Arduoino finds a beat. // Regards Serial OutPut -- Set This Up to your needs static boolean serialVisual = true; // Set to 'false' by Default. Re-set to 'true' to see Arduino Serial Monitor ASCII Visual Pulse volatile int rate[10]; // array to hold last ten IBI values volatile unsigned long sampleCounter = 0; // used to determine pulse timing volatile unsigned long lastBeatTime = 0; // used to find IBI volatile int P = 512; // used to find peak in pulse wave, seeded volatile int T = 512; // used to find trough in pulse wave, seeded volatile int thresh = 525; // used to find instant moment of heart beat, seeded volatile int amp = 100; // used to hold amplitude of pulse waveform, seeded volatile boolean firstBeat = true; // used to seed rate array so we startup with reasonable BPM volatile boolean secondBeat = false; // used to seed rate array so we startup with reasonable BPM void setup() { lcd.begin(16, 2); pinMode(blinkPin,OUTPUT); // pin that will blink to your heartbeat! pinMode(fadePin,OUTPUT); // pin that will fade to your heartbeat! Serial.begin(115200); // we agree to talk fast! interruptSetup(); // sets up to read Pulse Sensor signal every 2mS // IF YOU ARE POWERING The Pulse Sensor AT VOLTAGE LESS THAN THE BOARD VOLTAGE, // UN-COMMENT THE NEXT LINE AND APPLY THAT VOLTAGE TO THE A-REF PIN // analogReference(EXTERNAL); lcd.clear(); lcd.setCursor(0,0); lcd.print(" Patient Health"); lcd.setCursor(0,1); lcd.print(" Monitoring "); delay(4000); lcd.clear(); lcd.setCursor(0,0); lcd.print("Initializing...."); delay(5000); lcd.clear(); lcd.setCursor(0,0); lcd.print("Getting Data...."); ser.begin(9600); ser.println("AT"); delay(1000); ser.println("AT+GMR"); delay(1000); ser.println("AT+CWMODE=3"); delay(1000); ser.println("AT+RST"); delay(5000); ser.println("AT+CIPMUX=1"); delay(1000); String cmd="AT+CWJAP=\"durgesh\",\"eeeeeeee\""; ser.println(cmd); delay(1000); ser.println("AT+CIFSR"); delay(1000); } // Where the Magic Happens void loop() { serialOutput(); if (QS == true) // A Heartbeat Was Found { // BPM and IBI have been Determined // Quantified Self "QS" true when arduino finds a heartbeat fadeRate = 255; // Makes the LED Fade Effect Happen, Set 'fadeRate' Variable to 255 to fade LED with pulse serialOutputWhenBeatHappens(); // A Beat Happened, Output that to serial. QS = false; // reset the Quantified Self flag for next time } ledFadeToBeat(); // Makes the LED Fade Effect Happen delay(20); // take a break read_temp(); esp_8266(); } void ledFadeToBeat() { fadeRate -= 15; // set LED fade value fadeRate = constrain(fadeRate,0,255); // keep LED fade value from going into negative numbers! analogWrite(fadePin,fadeRate); // fade LED } void interruptSetup() { // Initializes Timer2 to throw an interrupt every 2mS. TCCR2A = 0x02; // DISABLE PWM ON DIGITAL PINS 3 AND 11, AND GO INTO CTC MODE TCCR2B = 0x06; // DON'T FORCE COMPARE, 256 PRESCALER OCR2A = 0X7C; // SET THE TOP OF THE COUNT TO 124 FOR 500Hz SAMPLE RATE TIMSK2 = 0x02; // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A sei(); // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED } void serialOutput() { // Decide How To Output Serial. if (serialVisual == true) { arduinoSerialMonitorVisual('-', Signal); // goes to function that makes Serial Monitor Visualizer } else { sendDataToSerial('S', Signal); // goes to sendDataToSerial function } } void serialOutputWhenBeatHappens() { if (serialVisual == true) // Code to Make the Serial Monitor Visualizer Work { Serial.print("*** Heart-Beat Happened *** "); //ASCII Art Madness Serial.print("BPM: "); Serial.println(BPM); } else { sendDataToSerial('B',BPM); // send heart rate with a 'B' prefix sendDataToSerial('Q',IBI); // send time between beats with a 'Q' prefix } } void arduinoSerialMonitorVisual(char symbol, int data ) { const int sensorMin = 0; // sensor minimum, discovered through experiment const int sensorMax = 1024; // sensor maximum, discovered through experiment int sensorReading = data; // map the sensor range to a range of 12 options: int range = map(sensorReading, sensorMin, sensorMax, 0, 11); // do something different depending on the // range value: switch (range) { case 0: Serial.println(""); /////ASCII Art Madness break; case 1: Serial.println("---"); break; case 2: Serial.println("------"); break; case 3: Serial.println("---------"); break; case 4: Serial.println("------------"); break; case 5: Serial.println("--------------|-"); break; case 6: Serial.println("--------------|---"); break; case 7: Serial.println("--------------|-------"); break; case 8: Serial.println("--------------|----------"); break; case 9: Serial.println("--------------|----------------"); break; case 10: Serial.println("--------------|-------------------"); break; case 11: Serial.println("--------------|-----------------------"); break; } } void sendDataToSerial(char symbol, int data ) { Serial.print(symbol); Serial.println(data); } ISR(TIMER2_COMPA_vect) //triggered when Timer2 counts to 124 { cli(); // disable interrupts while we do this Signal = analogRead(pulsePin); // read the Pulse Sensor sampleCounter += 2; // keep track of the time in mS with this variable int N = sampleCounter - lastBeatTime; // monitor the time since the last beat to avoid noise // find the peak and trough of the pulse wave if(Signal < thresh && N > (IBI/5)*3) // avoid dichrotic noise by waiting 3/5 of last IBI { if (Signal < T) // T is the trough { T = Signal; // keep track of lowest point in pulse wave } } if(Signal > thresh && Signal > P) { // thresh condition helps avoid noise P = Signal; // P is the peak } // keep track of highest point in pulse wave // NOW IT'S TIME TO LOOK FOR THE HEART BEAT // signal surges up in value every time there is a pulse if (N > 250) { // avoid high frequency noise if ( (Signal > thresh) && (Pulse == false) && (N > (IBI/5)*3) ) { Pulse = true; // set the Pulse flag when we think there is a pulse digitalWrite(blinkPin,HIGH); // turn on pin 13 LED IBI = sampleCounter - lastBeatTime; // measure time between beats in mS lastBeatTime = sampleCounter; // keep track of time for next pulse if(secondBeat) { // if this is the second beat, if secondBeat == TRUE secondBeat = false; // clear secondBeat flag for(int i=0; i<=9; i++) // seed the running total to get a realisitic BPM at startup { rate[i] = IBI; } } if(firstBeat) // if it's the first time we found a beat, if firstBeat == TRUE { firstBeat = false; // clear firstBeat flag secondBeat = true; // set the second beat flag sei(); // enable interrupts again return; // IBI value is unreliable so discard it } // keep a running total of the last 10 IBI values word runningTotal = 0; // clear the runningTotal variable for(int i=0; i<=8; i++) { // shift data in the rate array rate[i] = rate[i+1]; // and drop the oldest IBI value runningTotal += rate[i]; // add up the 9 oldest IBI values } rate[9] = IBI; // add the latest IBI to the rate array runningTotal += rate[9]; // add the latest IBI to runningTotal runningTotal /= 10; // average the last 10 IBI values BPM = 60000/runningTotal; // how many beats can fit into a minute? that's BPM! QS = true; // set Quantified Self flag // QS FLAG IS NOT CLEARED INSIDE THIS ISR pulse = BPM; } } if (Signal < thresh && Pulse == true) { // when the values are going down, the beat is over digitalWrite(blinkPin,LOW); // turn off pin 13 LED Pulse = false; // reset the Pulse flag so we can do it again amp = P - T; // get amplitude of the pulse wave thresh = amp/2 + T; // set thresh at 50% of the amplitude P = thresh; // reset these for next time T = thresh; } if (N > 2500) { // if 2.5 seconds go by without a beat thresh = 512; // set thresh default P = 512; // set P default T = 512; // set T default lastBeatTime = sampleCounter; // bring the lastBeatTime up to date firstBeat = true; // set these to avoid noise secondBeat = false; // when we get the heartbeat back } sei(); // enable interrupts when youre done! }// end isr void esp_8266() { // TCP connection AT+CIPSTART=4,"TCP","184.106.153.149",80 String cmd = "AT+CIPSTART=4,\"TCP\",\""; cmd += "184.106.153.149"; // api.thingspeak.com cmd += "\",80"; ser.println(cmd); Serial.println(cmd); if(ser.find("Error")) { Serial.println("AT+CIPSTART error"); return; } String getStr = "GET /update?api_key="; getStr += apiKey; getStr +="&field1="; getStr +=String(temp); getStr +="&field2="; getStr +=String(pulse); getStr += "\r\n\r\n"; // send data length cmd = "AT+CIPSEND=4,"; cmd += String(getStr.length()); ser.println(cmd); Serial.println(cmd); delay(1000); ser.print(getStr); Serial.println(getStr); //thingspeak needs 15 sec delay between updates delay(3000); } void read_temp() { int temp_val = analogRead(A1); float mv = (temp_val/1024.0)*5000; float cel = mv/10; temp = (cel*9)/5 + 32; Serial.print("Temperature:"); Serial.println(temp); lcd.clear(); lcd.setCursor(0,0); lcd.print("BPM :"); lcd.setCursor(7,0); lcd.print(BPM); lcd.setCursor(0,1); lcd.print("Temp.:"); lcd.setCursor(7,1); lcd.print(temp); lcd.setCursor(13,1); lcd.print("F"); } Data is not being tramsformed to thingspeak from arduino arduino thingspeak esp8266
Ulrich Engel in Discussions
上次活动时间: 2021-3-24

Hallo,ich bin Anfänger und nutze ThingSpeak um meine Wetterdaten (ESP8266 mit BME280 Sensor) und meine Feinstaubdaten (ESP8266 und PMS5003) anzuzeigen. Der erste ESP überträgt Temperatur, Luftfeuchte und Luftdruck in die Felder 1-3 bei ThingSpeak und der zweite ESP die Feinstaubwerte in die Felder 5-7 bei ThingSpeak. Alle 30 Sekunden werden jeweils Daten geschickt. Im Serial Monitor erfolgt die Übertragung wie geplant im Programm. Mein Problem: Die Ausgabe in ThingSpeak enthält viele Aussetzer. Es gehen Daten verloren und werden nicht angezeigt. Freue mich über Rückmeldungen. Ulli ThingSpeak Wetterdaten und Luftqualität Are you using the <https://github.com/mathworks/thingspeak-arduino ThingSpeak Library> ? What are you seeing on the serial monitor? Are both devices posting to the same channel? If two devices post to the same channel on a free account, there may be collisions that cause your data to be lost. We recommend one channel per device. esp8266 bme280 pms5003

关于 ThingSpeak

The community for students, researchers, and engineers looking to use MATLAB, Simulink, and ThingSpeak for Internet of Things applications. You can find the latest ThingSpeak news, tutorials to jump-start your next IoT project, and a forum to engage in a discussion on your latest cloud-based project. You can see answers to problems other users have solved and share how you solved a problem.