Contenido principal

Resultados de

Simple app created using Simulink support package for Android device. App created but data is not getting logged on thingspeak channel the error msg on app log is as attached.
I'm trying to access the ThingSpeak channel from Unity using MQTTnet.
I tried the following, but the access failed.
options = new MqttClientOptionsBuilder()
.WithClientId(clientId)
.WithTcpServer("mqtt3.thingspeak.com", 1833)
.WithCredentials(username, password)
.WithTls()
.Build();
try
{
await mqttClient.ConnectAsync(options);
}
How do I access the channel to send and receive values?
Hi, there ! Need some serious help.... I have trouble trying to upload my data to my Channel. Any ideas to fix it?
Below you can see my code:
#include <ThingSpeak.h>// Η βιβλιοθήκη του ThingSpeak.
#include <SPI.h>
#include <Ethernet.h>
#include <SoftwareSerial.h>
#include <Servo.h> // Η βιβλιοθήκη του σερβοκινητήρα.
#include "DHT.h"
#include "MQ7.h"
//Για τον αισθητήρα DHT11.
#define DHTPIN 7
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
//Για τον φωτισμό.
#define DELAY 5000 // Καθυστέρηση μεταξύ μετρήσεων σε ms για τον φωτισμό.
#define VIN 5 // Τάση 5V.
#define R 10000 //Αντίσταση 10.000 Ω.
//Για τον αισθητήρα MQ7.
int MQ7pin = A0;
int MQ7Reading;
int MQ7led = 3;
//Για τον αισθητήρα Soil.
int val;
int soil_dig= 8;
int soil_analog = A1;
//Μεταβλητές για τον φωτισμό και για τον υπολογισμό lux.
const int sensorPin = A3; // Το pin στο οποίο συνδέεται ο αισθητήρας.
const int led = 12;
const int greenled = 10;
const int redled = 4;
const long onduration = 10000;
const long offduration = 30000;
int ledstate = HIGH;
long remembertime = 0;
int sensorVal; // Αναλογική τιμή από τον αισθητήρα.
int lux; //Τιμές για τα lux
int valvePin = 13; // Το pin στο οποίο συνδέεται το ρελέ, ώστε να ενεργοποιεί την ηλεκτροβάνα.
//Για τον αισθητήρα Ultrasonic.
#define echoPin 5 // Το echoPin.
#define trigPin 6 // To trigPin.
long duration; // Η διάρκεια που κάνει το ηχητικό κύμα να ταξιδέψει.
int distance; // Ο υπολογισμός της ταχύτητας του ηχητικού κύματος.
//Για τον αισθητήρα Rain.
const int rain_D = 2;//Ψηφιακή τιμή αισθητήρα βροχής.
const int rain_A = A2;//Αναλογική τιμή αισθητήρα βροχής.
int rain_val;// Μεταβλητή για την αποθήκευση της τιμής του αισθητήρα βροχής.
int r;// Μεταβλητή για την αποθήκευση της τιμής του αισθητήρα βροχής.
Servo servo; // Το όνομα του σερβοκινητήρα.
int servoPin = 11; // Το pin στο οποίο συνδέεται ο σερβοκινητήρας.
#define pwm 9 // Το pin στο οποίο συνδέεται ο ανεμιστήρας.
//Σύνδεση
String readString;
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //H mac address.
byte ip[] = {192,168,2,123};
EthernetClient client;
unsigned long myChannelNumber = 1*******; //Ο αριθμός του καναλιού.
const char * myWriteAPIKey = "****************"; //Το ΑΡΙ Κey του καναλιού.
const int updateInterval = 10000;
void setup() {
Serial.begin(9600);
ThingSpeak.begin(client);// Σύνδεση στο cloud του ThingSpeak.
dht.begin();
pinMode(MQ7led, OUTPUT);// Θέτει το led του MQ7 ως OUTPUT.
pinMode(trigPin, OUTPUT); // Θέτει το trigPin ως OUTPUT.
pinMode(echoPin, INPUT); // Θέτει το echoPin ως INPUT.
pinMode(rain_D, INPUT); // Θέτει το rain_D ως INPUT.
pinMode(rain_A, INPUT); // Θέτει το rain_A ως INPUT.
pinMode(servoPin, OUTPUT);// Θέτει το servoPin ως OUTPUT.
servo.attach(servoPin);// Σύνδεση σε pin της μεταβλητής του σερβοκινητήρα.
analogWrite(pwm, 255);// Γράφει μία αναλογική τιμή (PWM pin) σε ένα pin.
pinMode(soil_analog, INPUT); // Θέτει το soil_analog ως INPUT.
pinMode(soil_dig, INPUT);// Θέτει το soil_dig ως INPUT.
pinMode(valvePin, OUTPUT); //Θέτει το 13 ως OUTPUT pin, ώστε να στέλνει σήμα στο relay.
pinMode(led, OUTPUT); // Θέτει το ledPin ως output.
digitalWrite(led,ledstate);
pinMode(sensorPin, INPUT);// Θέτει το sensorPin ως INPUT.
pinMode(greenled, OUTPUT);// Θέτει το greenled ως OUTPUT.
pinMode(redled, OUTPUT);// Θέτει το redled ως OUTPUT.
}
void loop() {
Serial.println(F("======================================"));
Serial.println(F("Συνθήκες στο Θερμοκήπιο :"));
//DHT11
float t = dht.readTemperature();// Η θερμοκρασία σε °C.
float h = dht.readHumidity(); // Η υγρασία του χώρου.
float f = dht.readTemperature(true); //Η θερμοκρασία σε °F.
// Υπολογισμός του heat index, ο οποίος πρέπει να μετατραπεί σε Fahrenheit.
float hi = dht.computeHeatIndex(f, h);
Serial.print(F("Temperature: "));
Serial.print(t);
Serial.print(F("°C "));
Serial.print(F(" and "));
Serial.print(f);
Serial.print(F("°F\t"));
Serial.print(F("Humidity: "));
Serial.print(h);
Serial.print(F(" %\t"));
Serial.print(F("Heat index: "));
Serial.print(hi);
Serial.println(F(" °F"));
// Έλεγχος της θερμοκρασίας , ώστε να ενεργοποιείται ο ανεμιστήρας όποτε χρειάζεται.
if (t == 26)
{
analogWrite(pwm, 51);
Serial.print(F("Ταχύτητα ανεμιστήρα: 20% "));
delay(1000);
}
else if (t == 30)
{
analogWrite(pwm, 204);
Serial.print(F("Ταχύτητα ανεμιστήρα: 80% "));
delay(1000);
}
else if (t > 40 )
{
analogWrite(pwm, 255);
Serial.print(F("Ταχύτητα ανεμιστήρα: 100% "));
delay(1000);
Serial.print(F("\t"));
}
//MQ7
float g = analogRead(MQ7pin);
Serial.print(F("MQ7: "));
Serial.println(g);
// Έλεγχος της τιμής του MQ7, ώστε να ανάβει το led που αναπαριστά ανεμιστήρα.
if ( g < 200)
{
Serial.println(F("O ανεμιστήρας κλειστός - Φυσιολογική ποσότητα CO στον χώρο εργασίας."));
digitalWrite(MQ7led, LOW);
}
else if (201 < g && g < 220)
{
Serial.println(F("Η μέγιστη φυσιολογική ποσότητα CO για χώρους εργασίας ξεπεράστηκε!!!- Λειτουργία εξαερισμού στο 50%."));
digitalWrite(MQ7led,HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(MQ7led, LOW); // turn the LED off by making the voltage LOW
delay(1000);
}
if (g > 220)
{
Serial.println(F("Eπικίνδυνα αέρια CO !!!- Λειτουργία εξαερισμού στο 100%."));
digitalWrite(MQ7led, HIGH); // turn the LED on (HIGH is the voltage level)
delay(5000);
}
//Soil Humidity
int soil_analog_value = analogRead(soil_analog);
soil_analog_value = map(soil_analog_value, 0, 1023, 230, 0);//Συνάρτηση map για μετρατροπή τιμής σε %.
val = digitalRead(soil_dig);
Serial.print(F("Soil moisture (Αναλογική τιμή) : "));
Serial.print(soil_analog_value);
Serial.print(F("\t"));
//Έλεγχος υγρασίας εδάφους για αυτόματο πότισμα.
if (soil_analog_value < 50)
{
digitalWrite(valvePin, LOW); //Όταν η τιμή γίνει LOW,τότε και το relay πρέπει να λάβει τιμή LOW.
Serial.println(F("relay on"));
}
else
{
digitalWrite(valvePin, HIGH); //Όταν η τιμή γίνει HIGH, τότε και το relay πρέπει να λάβει τιμή HIGH.
Serial.println(F("relay off"));
}
//Ultrasonic Sensor
// Αρχικοποίηση του trigPin.
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Το trigPin σε HIGH (ACTIVE) για 10 μs.
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
//Διαβάζει το echoPin, επιστρέφει το χρόνο του ηχητικού κύματος σε μs.
duration = pulseIn(echoPin, HIGH);
// Υπολογισμός απόστασης.
distance = (duration - 10) * 0.034 / 2;
Serial.println("");
Serial.print(F("Distance: "));
Serial.print(distance);
Serial.print(F(" cm"));
//Rain Sensor
rain_val = digitalRead(rain_D);
r = analogRead (rain_A);
r = abs ((100*r-40000)/623);
Serial.println(F(""));
Serial.print(F("Rain (Αναλογική τιμή) :"));
Serial.print(r);
Serial.print(F("\t"));
Serial.print(F("Rain (Ψηφιακή τιμή) :"));
Serial.print(rain_val);
//Έλεγχος για λειτουργία του σερβοκινητήρα.
if ((rain_val != HIGH) && (distance < 9)) {
servo.write(0);
}
if ((rain_val != HIGH) && (distance > 9)) {
servo.write(90);
}
else {
servo.write(0);
}
//Μέτρηση τιμής της φωτοαντίστασης και μετατροπή σε lux.
sensorVal = analogRead(sensorPin);
lux=sensorRawToPhys(sensorVal);
Serial.print("Raw value from sensor= ");
Serial.println(sensorVal); //Τύπωση αναλογικής τιμής.
Serial.print("Physical value from sensor = ");
Serial.print(lux); //Τύπωση αναλογικής τιμής.
Serial.println(" lumen");
//Συνθήκες για το άνοιγμα των led και των κουρτινών σκίασης σε διάφορες γωνίες.
if (ledstate == HIGH){
if((millis() - remembertime) >= onduration){
ledstate = LOW;
remembertime = millis();
}
}
if (ledstate == LOW){
if((millis() - remembertime) >= offduration){
ledstate = HIGH;
remembertime = millis();
}
}
//Lux.
if (lux < 100){
digitalWrite(led, HIGH);
if (lux < 200){
digitalWrite(greenled, ledstate);
if (lux < 300){
digitalWrite(redled, ledstate);
}}}
if(lux > 350){
digitalWrite(redled, LOW);
if(lux > 450){
digitalWrite(greenled, LOW);
if (lux>600){
digitalWrite(led, LOW);
}}}
else
digitalWrite(led,ledstate);
//Τα δεδομένα για το ThingSpeak, τα οποία στέλνονται στα αριθμημένα fields.
ThingSpeak.writeField(myChannelNumber,1,t, myWriteAPIKey);
ThingSpeak.writeField(myChannelNumber,2,h ,myWriteAPIKey);
ThingSpeak.writeField(myChannelNumber,3,g ,myWriteAPIKey);
ThingSpeak.writeField(myChannelNumber,4,soil_analog_value, myWriteAPIKey);
ThingSpeak.writeField(myChannelNumber,5,distance, myWriteAPIKey);
ThingSpeak.writeField(myChannelNumber,6,r, myWriteAPIKey);
delay(15000);
}
int sensorRawToPhys(int raw){
// Conversion rule
float Vout = float(raw) * (VIN / float(1023));// Conversion analog to voltage
float RLDR = (R * (VIN - Vout))/Vout; // Conversion voltage to resistance
int phys=500/(RLDR/1000); // Conversion resitance to lumen
return phys;
}
i want to send temperature read to field1 and ecg read to field2
how can i write the code
and i have another problem that i don't have ecg code to thingspeak

I wanted to ask of 3M messages of thingspeak free account will renew every year? Thank You

Hello, I am currently working on a simple android app for a smart irrigation system. Basically the app lets the user enter the name of the plant and then lists all the plants of the garden. Then, I have divided plants into three categories depending on their watering needs and I have created three int values for the amount of plants per group. Essentially I want to send these three values to a thingspeak channel I created, to 3 separated fields. I am not familiar at all with server programming in Java so I would really appreciate any kind of help in how to do this.

Dears Good day. I am new in IoT and I need help I am looking for a code that I can run to transmit real-time data from Revolution Pi based on Raspberry Pi to Thingspeak. I have code I used before to transmit data from Revolution Pi based on Raspberry Pi to Wolkabout ( cloud platform). Nevertheless, due to license issues. I had to change to Thingspeak. Can you please help me to adjust the code so that I can use it with Thingspeak instead of Wolkabout. Here is the code .............Code start...............

import os
import random
import sys
import time
from urllib.request import urlopen
import wolk 
import revpimodio2
from pymodbus.client.sync import ModbusSerialClient as ModbusClient
from pymodbus.register_read_message import ReadInputRegistersResponse
  1. Sensors Keys device = wolk.Device(key="KDD", password="FDV7F12TSW")

wolk_device = wolk.WolkConnect(device, host="54.72.159.61", port=8883, ca_cert="ca_local_wolkabout.crt") # Establish a connection to the WolkAbout IoT Platform print("Connecting to WolkAbout IoT Platform") wolk_device.connect() rpi = revpimodio2.RevPiModIO(autorefresh=True)

  1. For Modbus RTU Connection #client = ModbusClient(method = 'rtu', port='/dev/ttyRS485', stopbits=1, bytesize=8, parity='E',baudrate=19200,timeout=1,strict=False) #connection = client.connect() #print(connection)

def main(): """Connect to WolkAbout IoT Platform and send a random sensor reading."""

    publish_period_seconds = 5
    # LS1 Level sensor 1 LS2 Level sensor 2 VS1 Velocity sensor 1 VS2 Velocity sensor 2
    while True:
        try:
            #first set of the sensors
            LS1 = rpi.io.InputValue_1.value*0.059056-205.825
            LS2 = rpi.io.InputValue_2.value*0.059056-205.825
            VS1 = rpi.io.InputValue_3.value*0.0025-10
            VS2 = rpi.io.InputValue_4.value*0.0025-10
            #sensors from RTU1
            #Temp1= (client.read_input_registers(58, 1, unit=1))
            #Temp2 = Temp1.registers
            #Temp = float(Temp2[0])/100
            Temp1 = rpi.io.Temperature.value/100
            Temp2 = rpi.io.Temperature2.value/100
            #mu1= (client.read_input_registers(66, 1, unit=1))
            #mu2 = mu1.registers
            #mu = float(mu2[0])/100
            mu1 = rpi.io.Viscosity.value/100
            mu2 = rpi.io.Viscosity2.value/100
            #rho1= (client.read_input_registers(74, 1, unit=1))
            #rho2 = rho1.registers
            #rho = float(rho2[0])/100
            rho1 = rpi.io.Density.value/100
            rho2 = rpi.io.Density2.value/100
            #publshing data
            #wolk_device.add_sensor_readings({"LS1": LS1,"LS2": LS2,"VS1": VS1,"VS2": VS2,"Temp1": Temp1,"rho1": rho1,"mu1": mu1,"Temp2": Temp2,"rho2": rho2,"mu2": mu2})
            print('Publishing "Level Sensor 1": ' + str(LS1))
            print('Publishing "Level Sensor 2": ' + str(LS2))
            print('Publishing "Velocity Sensor 1": ' + str(VS1))
            print('Publishing "Velocity Sensor 2": ' + str(VS2))
            print('Publishing "Temperature_RTU1": ' + str(Temp1))
            print('Publishing "Viscosity_RTU1": ' + str(mu1))
            print('Publishing "Density_RTU1": ' + str(rho1))
            print('Publishing "Temperature_RTU2": ' + str(Temp2))
            print('Publishing "Viscosity_RTU2": ' + str(mu2))
            print('Publishing "Density_RTU2": ' + str(rho2))
            #wolk_device.publish()
            time.sleep(publish_period_seconds)
        except KeyboardInterrupt:
            print("\tReceived KeyboardInterrupt. Exiting script")
            wolk_device.disconnect()
            sys.exit()

if _name_ == "__main__": main() ...............Code End................... Hope that you can help me. I have a fee account in Thingspeak, only 1 channel with 8 fields which is enough for my current project for time being. Wish you a nice day

Currently i am using lora from my end node to my dragino gateway and from my gateway, i push the sensor data up to thingspeak. i want to check that when my temperature graph hits above 30 it will send down a 1 or a command to my gateway and my gateway will transmit it to my end node to take action. i research and saw that react is one of the solution for on top but i do not know which action and how to use that specific action for this scenario.

Sai Teja Kavuri
Sai Teja Kavuri
Última actividad el 13 de Mzo. de 2022

hello, i have done my iot project using thingspeak as the monitoring source and its working well and good.But now i need get text message to a mobile when the field value gets reached to given threshold value and i have to get a alert text message.Is there any way to resolve my problem from thigspeak data to alert text message.

Thankyou.

Hi,

I am using Ublox SARA-R410M to send (cellular) data to ThingSpeak cloud. I found in the Ublox manual that AT+UHTTPC (POST data command) can do the job. The link below is the location which my data will be saved on ThingSpeak (field1):

"https://api.thingspeak.com/update?api_key=WRITE_API_KEY&field1="

Note that the "WRITE_API_KEY" is 16 characters (combination of letters and numbers).

AT command: AT+UHTTPC=<profile_id>,5, path,<filename>,<data>,<HTTP_content_type>

Based on the information above, which items should I use for path and filename? And how can I use this command in Arduino code?

I appreciate any help in advance.

Abbas

If you are a student or researcher looking for a project idea, have a look at the MathWorks Excellence in Innovation site. There is at least one IoT-based project for a Smart watering system, and a project with a Digital twin of a pneumatic system. If you ask me, most of the other projects could also be enhanced with an IoT based component shared on ThingSpeak!

#include <Keypad.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <SoftwareSerial.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
SoftwareSerial ESP01(2, 3);
const byte ROWS = 4; // four rows
const byte COLS = 3; // three columns
char keys[ROWS][COLS] = { // keypad labels
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};
byte rowPins[ROWS] = {12, 7, 8, 10};          //connect to keypad pins 12, 7, 8, 10
byte colPins[COLS] = {11, 13, 9};             // connect to keypad pins 11, 13, 9 column pinouts
Keypad customKeypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
#define Password_Length 5
#define DEBUG true
#define IP "184.106.153.149"
// define pin numbers
int buzzer = 5; // buzzer is connected to pin 5
int PIR = 6;    // PIR is connected to pin 6
// intruder alarm password
char Data[Password_Length];
char Master[Password_Length] = "1234";
byte data_count = 0, master_count = 0;
bool Pass_is_good;
char customKey;
int val = 0;
// thingspeak & WiFi
String apiKey = "xxxxxxxxxxxxxxxx"; // thingspeak API key
void setup() {
lcd.init(); 
lcd.backlight();
pinMode(buzzer, OUTPUT);
pinMode(PIR, INPUT);
Serial.begin(9600); 
while (!Serial){
}
Serial.println("Starting...");
ESP01.begin(9600);
// Reset ESP8266, put it into mode 1 i.e. STA only, make it join hotspot / AP, 
// establish single connection
ESP01.println();
sendData("AT+RST\r\n",2000,DEBUG);
sendData("AT+CWMODE=1\r\n",2000,DEBUG);
sendData("AT+CWJAP=\"AiPhone\",\"123889\"\r\n",20000,DEBUG);  
sendData("AT+CIPMUX=0\r\n",4000,DEBUG);
// Make TCP connection
String cmd = "AT+CIPSTART=\"TCP\",\"";
cmd += "184.106.153.149"; // Thingspeak.com's IP address  
cmd += "\",80\r\n";
sendData(cmd,4000,DEBUG);  
// Read PIR sensor value 
  val = digitalRead(PIR);
  // check if there was a state transition
    String val1 = String(val);
    if (val == HIGH)
    {
      Serial.println("Motion detected!");
      delay(10);
      Serial.println(val1);
    }
    else
    {
      Serial.println("Asleep");
      delay(10);
      //String val1 = String(val);
      Serial.println(val1);
    }
      //String val1 = String(val);
      //Serial.println(val1);
//Prepare GET string
String getStr = "GET /update?api_key=";
getStr += apiKey;
getStr += "&field1=";
getStr += val1;
getStr +="\r\n";
// Send data length & GET string
ESP01.print("AT+CIPSEND=");
ESP01.println (getStr.length());
Serial.print("AT+CIPSEND=");
Serial.println(getStr.length());
delay(500);
if(ESP01.find (">"))
{
  Serial.print(">");
  sendData(getStr, 2000, DEBUG);
}
//Close connection, wait a while before repeating
sendData("AT+CIPCLOSE", 16000, DEBUG); // 15 seconds delay between updates
}
if true
  % code
endvoid loop() {
if (digitalRead(PIR) == HIGH)
{
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("Enter Password: ");
    customKey = customKeypad.getKey();
    if (customKey)
    {
      Data[data_count] = customKey;
      lcd.setCursor(data_count, 1);
      lcd.print(Data[data_count]);
      data_count++;
    }
    if (data_count == Password_Length - 1)
    {
      lcd.clear();
      if (!strcmp(Data, Master))
      {
        lcd.print("OK");
        digitalWrite(buzzer, HIGH);
        delay(200);
        digitalWrite(buzzer, LOW);
        delay(200);
        digitalWrite(buzzer, HIGH);
        delay(200);
        digitalWrite(buzzer, LOW);
      }
      else
      {
        lcd.print("Wrong Password");
        digitalWrite(buzzer, HIGH);
        delay(1000);
        digitalWrite(buzzer, LOW);
      }
      lcd.clear();
      clearData();
    }
  }
  else
    {
      lcd.noBacklight();      // turn backlight off
      lcd.clear();            // clear display
      delay(250);
    }
}
String sendData(String command, const int timeout, boolean debug)
{
  String response = "";
  ESP01.print(command);
  long int time = millis();
    while( (time+timeout) > millis())
    {
      while(ESP01.available())
      {
        // "Construct" response from ESP01 as follows 
         // - this is to be displayed on Serial Monitor. 
        char c = ESP01.read(); // read the next character.
        response+=c;
      }  
    }
    if(debug)
    {
      Serial.print(response);
    }
    return (response);
}
void clearData() {
  while (data_count != 0)
{
  Data[data_count--] = 0;
  }
  return;
}
Noora_cube
Noora_cube
Última actividad el 11 de Feb. de 2022

Hi, this is my first question here... hope not to bother you all. Is it possible to stop a sensor from collecting data by using ThingSpeak/MQTT broker/MQTT protocol? How? I'm working with a MAX30102 for oxigen and bpm detection and I need to stop the sensor from ThingSpeak or at least this is what I was asked to do. At the moment I can't figure out how to do this except by using the APIkey and the HTTP protocol but my task was to only use MQTT protocol. Hope someone can help me finding a new point of view about this topic/problem.

EDIT: I solved the problem. I used another client, MQTTx to be precise, in order to send messages in a field of control. So, at the beginning I had just two fields (BPM and SpO2), then I added a third field of control. The board WeMos, connected to the sensor MH-ET LIVE MAX30102 was used to process the sensor's data and send them to Thingspeak every 15 seconds wherease the client desktop MQTTx was also connected to ThingSpeak's broker and enbled for both publish and subscribe and I used it to send messages of ON and OFF, literally, as payload for the control field. This messages were passed to the callBack function and the payload was checked in order to change the state of my code, nested in a switch system. Thamk's for the help to you all :) If you're interested to the code and the settings just let me know.

Hi Everyone,

Today mistakenly i clear the working channel instead of testing channel which have more then 27000 Environmental Sensor readings so is there any option where i can get back my that data?

Thank you.

     we are doing a project on health monitoring system. We have made all the required changes in the code but our data is not being uploaded in thingspeak.It would be of great help if you can suggest some way.
    #include <SoftwareSerial.h>
    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    #include <SoftwareSerial.h>
    float pulse = 0;
    float temp = 0;
    SoftwareSerial ser(9,10);
    String apiKey = "xxxxxxxxxxxxxxxx";
    // 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=\"Harshini Arulkumaran\",\"prythian\"";
    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 Detected"); //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 += "192.168.137.1"; // 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");
    }
pema chowden
pema chowden
Última actividad el 18 de Nov. de 2021

i am trying to decode the below sketch to integrate TTNv3 to thingspeak.

can someone help me with this issue

#include <lmic.h>
#include <dht.h>
#include <hal/hal.h>
#include <SPI.h>
dht DHT;
#define DHT11_PIN 5
#define PIN_A A0
float temperature,humidity;      
float tem,hum;
unsigned int count = 1;        //For times count
String datastring1="";        
String datastring2="";        
String datastring3="";
static uint8_t mydata[11] = {0x01,0x67,0x00,0x00,0x02,0x68,0x00,0x03,0x65,0x00,0x00};
/* LoRaWAN NwkSKey, network session key
   This is the default Semtech key, which is used by the prototype TTN
   network initially.
   ttn*/
static const PROGMEM u1_t NWKSKEY[16] = { 0x72, 0x13, 0xF8, 0xF0, 0x9A, 0x3C, 0xF9, 0xE5, 0xE6, 0x01, 0xDA,0xAC, 0x32, 0xBA, 0x37 };
/* LoRaWAN AppSKey, application session key
   This is the default Semtech key, which is used by the prototype TTN
   network initially.
   ttn*/
static const u1_t PROGMEM APPSKEY[16] = { 0x2F, 0xF5, 0xF4, 0x08, 0x4E, 0x37, 0x20, 0x02, 0xBA, 0x2B, 0xED,  0x40, 0x24, 0xA2, 0x945 };
/*
 LoRaWAN end-device address (DevAddr)
 See http://thethingsnetwork.org/wiki/AddressSpace
 ttn*/
static const u4_t DEVADDR = 0x260D0CA5;
/* These callbacks are only used in over-the-air activation, so they are
  left empty here (we cannot leave them out completely unless
   DISABLE_JOIN is set in config.h, otherwise the linker will complain).*/
void os_getArtEui (u1_t* buf) { }
void os_getDevEui (u1_t* buf) { }
void os_getDevKey (u1_t* buf) { }
static osjob_t initjob,sendjob,blinkjob;
/* Schedule TX every this many seconds (might become longer due to duty
 cycle limitations).*/
const unsigned TX_INTERVAL = 10;
// Pin mapping
const lmic_pinmap lmic_pins = {
    .nss = 10,
    .rxtx = LMIC_UNUSED_PIN,
    .rst = 9,
    .dio = {2, 6, 7},
};
void do_send(osjob_t* j){
    // Check if there is not a current TX/RX job running
    if (LMIC.opmode & OP_TXRXPEND) {
        Serial.println("OP_TXRXPEND, not sending");
    } else {
          dhtTem();
          light();
          // Prepare upstream data transmission at the next possible time.
          //  LMIC_setTxData2(1,datasend,sizeof(datasend)-1,0);
          LMIC_setTxData2(1, mydata, sizeof(mydata), 0);
          Serial.println("Packet queued");
          Serial.print("LMIC.freq:");
          Serial.println(LMIC.freq);
          Serial.println("Receive data:");
      } 
      // Next TX is scheduled after TX_COMPLETE event.
  }
void onEvent (ev_t ev) {
    Serial.print(os_getTime());
    Serial.print(": ");
    Serial.println(ev);
    switch(ev) {
        case EV_SCAN_TIMEOUT:
            Serial.println(F("EV_SCAN_TIMEOUT"));
            break;
        case EV_BEACON_FOUND:
            Serial.println(F("EV_BEACON_FOUND"));
            break;
        case EV_BEACON_MISSED:
            Serial.println(F("EV_BEACON_MISSED"));
            break;
        case EV_BEACON_TRACKED:
            Serial.println(F("EV_BEACON_TRACKED"));
            break;
        case EV_JOINING:
            Serial.println(F("EV_JOINING"));
            break;
        case EV_JOINED:
            Serial.println(F("EV_JOINED"));
            break;
        case EV_RFU1:
            Serial.println(F("EV_RFU1"));
            break;
        case EV_JOIN_FAILED:
            Serial.println(F("EV_JOIN_FAILED"));
            break;
        case EV_REJOIN_FAILED:
            Serial.println(F("EV_REJOIN_FAILED"));
            break;
        case EV_TXCOMPLETE:
            Serial.println(F("EV_TXCOMPLETE (includes waiting for RX windows)"));
            if(LMIC.dataLen) {
                // data received in rx slot after tx
                Serial.print(F("Data Received: "));
                Serial.write(LMIC.frame+LMIC.dataBeg, LMIC.dataLen);
                Serial.println();
            }
            // Schedule next transmission
            os_setTimedCallback(&sendjob, os_getTime()+sec2osticks(TX_INTERVAL), do_send);
            break;
        case EV_LOST_TSYNC:
            Serial.println(F("EV_LOST_TSYNC"));
            break;
        case EV_RESET:
            Serial.println(F("EV_RESET"));
            break;
        case EV_RXCOMPLETE:
            // data received in ping slot
            Serial.println(F("EV_RXCOMPLETE"));
            break;
        case EV_LINK_DEAD:
            Serial.println(F("EV_LINK_DEAD"));
            break;
        case EV_LINK_ALIVE:
            Serial.println(F("EV_LINK_ALIVE"));
            break;
         default:
            Serial.println(F("Unknown event"));
            break;
    }
}
void setup() {
     // initialize digital pin  as an output.
      Serial.begin(9600);
      while(!Serial);
      Serial.println("Connect to TTN and Send data to mydevice(Use DHT11 Sensor):");
      #ifdef VCC_ENABLE
      // For Pinoccio Scout boards
      pinMode(VCC_ENABLE, OUTPUT);
      digitalWrite(VCC_ENABLE, HIGH);
      delay(1000);
      #endif
      // LMIC init
      os_init();
      // Reset the MAC state. Session and pending data transfers will be discarded.
      LMIC_reset();
      /*LMIC_setClockError(MAX_CLOCK_ERROR * 1/100);
       Set static session parameters. Instead of dynamically establishing a session
       by joining the network, precomputed session parameters are be provided.*/
      #ifdef PROGMEM
      /* On AVR, these values are stored in flash and only copied to RAM
         once. Copy them to a temporary buffer here, LMIC_setSession will
         copy them into a buffer of its own again.*/
      uint8_t appskey[sizeof(APPSKEY)];
      uint8_t nwkskey[sizeof(NWKSKEY)];
      memcpy_P(appskey, APPSKEY, sizeof(APPSKEY));
      memcpy_P(nwkskey, NWKSKEY, sizeof(NWKSKEY));
      LMIC_setSession (0x1, DEVADDR, nwkskey, appskey);
      #else
      // If not running an AVR with PROGMEM, just use the arrays directly 
      LMIC_setSession (0x1, DEVADDR, NWKSKEY, APPSKEY);
      #endif
       for (int channel=0; channel<8; ++channel) {
      LMIC_disableChannel(channel);
    }
    for (int channel=16; channel<72; ++channel) {
       LMIC_disableChannel(channel);
    }
      // Disable link check validation
      LMIC_setLinkCheckMode(0);
      // TTN uses SF9 for its RX2 window.
      LMIC.dn2Dr = DR_SF9;
      // Set data rate and transmit power (note: txpow seems to be ignored by the library)
      LMIC_setDrTxpow(DR_SF7,14);
      // Start job
      do_send(&sendjob);
  }
  void dhtTem()
  {
         int16_t tem1;
         temperature = DHT.read11(DHT11_PIN);    //Temperature detection
         tem = DHT.temperature*1.0;      
        float humidity = DHT.read11(DHT11_PIN);
        float hum = DHT.humidity* 1.0;
        Serial.print(F("###########    "));
         Serial.print(F("NO."));
         Serial.print(count);
         Serial.println(F("    ###########"));
         Serial.println(F("The temperautre and humidity :"));
         Serial.print(F("["));
         Serial.print(tem);
         Serial.print(F("℃"));
         Serial.print(F(","));
         Serial.print(hum);
         Serial.print(F("%"));
         Serial.print(F("]"));
         Serial.println("");
         count++;
         tem1=(tem*10);
         mydata[2] = tem1>>8;
         mydata[3]= tem1;
         mydata[6] = hum * 2;
}
void light(){
      int16_t lux;
      int val,val1;
      val=analogRead(PIN_A);
     // Serial.print(F("a:"));
      //Serial.println(val);
      delay(500);
      val1=val*1.0;
      lux=val1;
      mydata[9]=lux>>8;
      mydata[10]=lux;
       //Serial.print(lux);
}
void loop() {
    os_runloop_once();
}
pema chowden
pema chowden
Última actividad el 18 de Nov. de 2021

Hi there,

I have tried to get the data on thingspeak via integrating it on the things Network. but the GPS data I am receiving on the thingspeak is delayed by 2 mins.

is there any way I can code to send JSON file straight on thingspeak from the sensor or the gateway?

Following is the ardiuno sketch

#include <lmic.h>
#include <hal/hal.h>
#include <SPI.h>
#include <SoftwareSerial.h>
#include <TinyGPS.h>
TinyGPS gps;
SoftwareSerial ss(3, 4); // Arduino RX, TX to conenct to GPS module.
static void smartdelay(unsigned long ms);
unsigned int count = 1;        //For times count
String datastring1="";        
String datastring2="";        
String datastring3="";
uint8_t datasend[20];     //Used to store GPS data for uploading
char gps_lon[20]={"\0"};  //Storage GPS info
char gps_lat[20]={"\0"}; //Storage latitude
char gps_alt[20]={"\0"}; //Storage altitude
float flat, flon,falt;
static uint8_t mydata[] = "Hello, world!";      //For test using.
/* LoRaWAN NwkSKey, network session key
   This is the default Semtech key, which is used by the prototype TTN
   network initially.
   ttn*/
static const PROGMEM u1_t NWKSKEY[16] =  { 0xE4, 0x2A, 0x93, 0x96, 0xF7, 0xC9, 0x65, 0x9E, 0xF8, 0x90, 0xC6, 0xA0, 0x1A, 0x88, 0xF7, 0x47 };
/* LoRaWAN AppSKey, application session key
   This is the default Semtech key, which is used by the prototype TTN
   network initially.
   ttn*/
static const u1_t PROGMEM APPSKEY[16] = { 0x75, 0x43, 0x26, 0xA1, 0x82, 0x79, 0x7F, 0xCF, 0x3C, 0x1D, 0xBF, 0xF9, 0xBF, 0xCB, 0xC6, 0xD9 };
/*
 LoRaWAN end-device address (DevAddr)
 See http://thethingsnetwork.org/wiki/AddressSpace
 ttn*/
static const u4_t DEVADDR = 0x260111D1;
/* These callbacks are only used in over-the-air activation, so they are
  left empty here (we cannot leave them out completely unless
   DISABLE_JOIN is set in config.h, otherwise the linker will complain).*/
void os_getArtEui (u1_t* buf) { }
void os_getDevEui (u1_t* buf) { }
void os_getDevKey (u1_t* buf) { }
static osjob_t initjob,sendjob,blinkjob;
/* Schedule TX every this many seconds (might become longer due to duty
 cycle limitations).*/
const unsigned TX_INTERVAL = 20;
// Pin mapping
const lmic_pinmap lmic_pins = {
    .nss = 10,
    .rxtx = LMIC_UNUSED_PIN,
    .rst = 9,
    .dio = {2, 6, 7},
};
void do_send(osjob_t* j){
    // Check if there is not a current TX/RX job running
    if (LMIC.opmode & OP_TXRXPEND) {
        Serial.println("OP_TXRXPEND, not sending");
    } else {
        GPSRead();
        GPSWrite();
          // Prepare upstream data transmission at the next possible time.
            LMIC_setTxData2(1,datasend,sizeof(datasend)-1,0);
          //LMIC_setTxData2(1, mydata, sizeof(mydata)-1, 0);
          Serial.println("Packet queued");
          Serial.print("LMIC.freq:");
          Serial.println(LMIC.freq);
          Serial.println("");
          Serial.println("");
          Serial.println("Receive data:");
      } 
      // Next TX is scheduled after TX_COMPLETE event.
  }
void onEvent (ev_t ev) {
    Serial.print(os_getTime());
    Serial.print(": ");
    Serial.println(ev);
    switch(ev) {
        case EV_SCAN_TIMEOUT:
            Serial.println("EV_SCAN_TIMEOUT");
            break;
        case EV_BEACON_FOUND:
            Serial.println("EV_BEACON_FOUND");
            break;
        case EV_BEACON_MISSED:
            Serial.println("EV_BEACON_MISSED");
            break;
        case EV_BEACON_TRACKED:
            Serial.println("EV_BEACON_TRACKED");
            break;
        case EV_JOINING:
            Serial.println("EV_JOINING");
            break;
        case EV_JOINED:
            Serial.println("EV_JOINED");
            break;
        case EV_RFU1:
            Serial.println("EV_RFU1");
            break;
        case EV_JOIN_FAILED:
            Serial.println("EV_JOIN_FAILED");
            break;
        case EV_REJOIN_FAILED:
            Serial.println("EV_REJOIN_FAILED");
            break;
        case EV_TXCOMPLETE:
            Serial.println("EV_TXCOMPLETE (includes waiting for RX windows)");
            if(LMIC.dataLen) {
                // data received in rx slot after tx
                Serial.print("Data Received: ");
                Serial.write(LMIC.frame+LMIC.dataBeg, LMIC.dataLen);
                Serial.println();
            }
            // Schedule next transmission
            os_setTimedCallback(&sendjob, os_getTime()+sec2osticks(TX_INTERVAL), do_send);
            break;
        case EV_LOST_TSYNC:
            Serial.println("EV_LOST_TSYNC");
            break;
        case EV_RESET:
            Serial.println("EV_RESET");
            break;
        case EV_RXCOMPLETE:
            // data received in ping slot
            Serial.println("EV_RXCOMPLETE");
            break;
        case EV_LINK_DEAD:
            Serial.println("EV_LINK_DEAD");
            break;
        case EV_LINK_ALIVE:
            Serial.println("EV_LINK_ALIVE");
            break;
         default:
            Serial.println("Unknown event");
            break;
    }
}
void setup() {
     // initialize digital pin  as an output.
      Serial.begin(9600);
       ss.begin(9600);  
      while(!Serial);
      Serial.println("LoRa GPS Example---- ");
      Serial.println("Connect to TTN");
      #ifdef VCC_ENABLE
      // For Pinoccio Scout boards
      pinMode(VCC_ENABLE, OUTPUT);
      digitalWrite(VCC_ENABLE, HIGH);
      delay(1000);
      #endif
      // LMIC init
      os_init();
      // Reset the MAC state. Session and pending data transfers will be discarded.
      LMIC_reset();
      /*LMIC_setClockError(MAX_CLOCK_ERROR * 1/100);
       Set static session parameters. Instead of dynamically establishing a session
       by joining the network, precomputed session parameters are be provided.*/
      #ifdef PROGMEM
      /* On AVR, these values are stored in flash and only copied to RAM
         once. Copy them to a temporary buffer here, LMIC_setSession will
         copy them into a buffer of its own again.*/
      uint8_t appskey[sizeof(APPSKEY)];
      uint8_t nwkskey[sizeof(NWKSKEY)];
      memcpy_P(appskey, APPSKEY, sizeof(APPSKEY));
      memcpy_P(nwkskey, NWKSKEY, sizeof(NWKSKEY));
      LMIC_setSession (0x1, DEVADDR, nwkskey, appskey);
      #else
      // If not running an AVR with PROGMEM, just use the arrays directly 
      LMIC_setSession (0x1, DEVADDR, NWKSKEY, APPSKEY);
      #endif
      // Disable link check validation
      LMIC_setLinkCheckMode(0);
      // TTN uses SF9 for its RX2 window.
      LMIC.dn2Dr = DR_SF9;
      // Set data rate and transmit power (note: txpow seems to be ignored by the library)
      LMIC_setDrTxpow(DR_SF7,14);
      // Start job
      do_send(&sendjob);
  }
void GPSRead()
{
  unsigned long age;
  gps.f_get_position(&flat, &flon, &age);
  falt=gps.f_altitude();  //get altitude    
  flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : flat, 6;   
  flon == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : flon, 6;//save six decimal places 
  falt == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : falt, 2;//save two decimal places
}
void GPSWrite()
{
  /*Convert GPS data to format*/
  datastring1 +=dtostrf(flat, 0, 4, gps_lat);   
  datastring2 +=dtostrf(flon, 0, 4, gps_lon);
  //datastring3 +=dtostrf(falt, 0, 2, gps_alt);
    if(flon!=1000.000000)
    {  
    strcat(gps_lon,",");
    strcat(gps_lon,gps_lat); 
    //strcat(gps_lon,","); 
    //strcat(gps_lon,gps_alt);
      int i = 0;
    for(i = 0; i < 2; i++)
    {
        //datasend.toFloat();
        atof(gps_lon);
       //Serial.println((char*)datasend);
      Serial.println("Testing converted data:");
      Serial.println(gps_lon);
      // atof(gps_alt);
      // Serial.print(gps_alt);
    }
    strcpy(datasend,gps_lon); //the format of datasend is longtitude,latitude,altitude
    Serial.print("###########    ");
    Serial.print("NO.");
    Serial.print(count);
    Serial.println("    ###########");
    Serial.println("The longtitude and latitude are:");
    Serial.print("[");
    Serial.print((char*)datasend);
    Serial.print("]");
    Serial.print("");
    /*
    for(int k = 0; k < 20;k++)
    {
    Serial.print("[");
    Serial.print(datasend[k], HEX);
    Serial.print("]");
    }
    Serial.println("");
    Serial.println("");*/
    count++;
    }
    int32_t lng = flat * 10000;
    int32_t lat = flon * 10000;
    datasend[0] = lat;
    datasend[1] = lat >> 8;
    datasend[2] = lat >> 16;
    datasend[3] = lng;
    datasend[4] = lng >> 8;
    datasend[5] = lng >> 16;
    smartdelay(1000);
  }
static void smartdelay(unsigned long ms)
{
  unsigned long start = millis();
  do 
  {
    while (ss.available())
    {
      gps.encode(ss.read());
    }
  } while (millis() - start < ms);
}
void loop() {
    os_runloop_once();
}

Hello everyone! i want to send current sensor data using Arduino and nodeMCU to thingspeak. is there anyone who worked on something before. your responses will be highly appreciatable. thanks in advance

We've started a new video series on how and why to use ThingSpeak. IoT from Data to Action . Most of you pros here at the forum probably already know this stuff, but there's some great overview material in these videos if you are interested. Two of four planned movies are posted, Ill let you know again when the others come out too. -Christopher

Hello,

I am working on a project which measures the water level in a well and the temperature of the water. Currently, we have a few of these units deployed in the field and they are working well, but our environmental engineer does not like the water level graphs because they are not "intuitive" enough. The water levels displayed on our graphs are simply the distance between the surface of the water and our distance sensor, so when the water in the well rises, the y-axis value drops, which bothers the environmental guy. Is there a way to flip the y-axis without driving back out to these rural locations and flashing revised code to the mcu? I have been looking around the channel and graph settings and I do not see anything. Google has taken me to some matlab forum links which suggest changing values in objects, which I do not think is any help right now.

Any help is appreciated.