I have created two datastream in xively from one I want to send data on xively and from one I want to get but while using put method it is changing my both value but I dont want to update one of the data stream i am using xively.put method for this
#include <SPI.h> //spi library
#include <Ethernet.h> //ethernet library
#include <HttpClient.h>//http client library
#include <Xively.h> //xively library
//using the mac id of ethernrt shield Mac_ID = 90-A2-DA-0E-99-85
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0E, 0x99, 0x85 };
//Xively api key for upload and download
char xivelyKey[] = "api_key";
// Dtastream id i.e Device create in Xively account with same name otherwise will get an error
char ledId[] = "led";
char sensorId[]="stepper";
int sensorPin = A0; // select the input pin for the potentiometer
int ledPin = 13; // select the pin for the LED
int sensorValue = 0;
//Initializing the xively datastream for the devices created in xively account
XivelyDatastream datastreams[] = {
XivelyDatastream(ledId, strlen(ledId), DATASTREAM_FLOAT),
XivelyDatastream(sensorId, strlen(sensorId), DATASTREAM_FLOAT),
};
//The transmission happen through feed initialize it
//XivelyFeed feed(FEED_ID,XIVELY_DATASTREAM,NO_OF_DATASTREAM)
XivelyFeed feed(feedid, datastreams, 2);
//Initializing the ethernet client for http support
EthernetClient myclient;
//Use the ethernet client to initialize xively client
XivelyClient xivelyclient(myclient);
/* Initial setup of arduino */
void setup(){
/* initialize the serial communication to monitor the transmission */
//starting the serial communication with the baud rate 9600
Serial.begin(9600);
Serial.println("Serial Communication started");
Serial.println();
//assigning the ip address using dhcp
while (Ethernet.begin(mac) != 1){
Serial.println("Error getting IP address via DHCP, trying again...");
delay(15000);
}
}
/* loop for doing continous upload and dowload of data*/
void loop(){
int sensor;
sensor=analogRead(sensorPin);
datastreams[1].setFloat(sensor);
/* uploading the data */
Serial.print("uploading data of stepper");
Serial.println(datastreams[1].getFloat());
Serial.println("Uploading it to Xively");
while((xivelyclient.put(feed, xivelyKey) != 200));
Serial.println();
delay(15000);
Serial.println("uploading of data completed");
/* finidh uploading data*/
/* Downloading the data*/
Serial.println("downloading data");
while((xivelyclient.get(feed, xivelyKey) != 200));
Serial.println("Datastream is...");
Serial.println(feed[0]);
Serial.println("Datastream is...");
Serial.println(feed[1]);
Serial.print("stepper motor downloaded data is: ");
Serial.println(feed[1].getFloat());
Serial.println("downloadind data completed");
Serial.println();
delay(15000);
/* Downloading data completed */
}
Make two XivelyDatastream: one with the Id that you want to send and the other with what you want to read.
Otherwise everything is updated in the datastream.
// Setup two different streams:
XivelyDatastream datastreams_get[] = {
XivelyDatastream(sensorId, strlen(sensorId), DATASTREAM_FLOAT),
};
XivelyDatastream datastreams_put[] = {
XivelyDatastream(ledId, strlen(ledId), DATASTREAM_FLOAT),
};
//The transmission happen through feed initialize it
//XivelyFeed feed(FEED_ID,XIVELY_DATASTREAM,NO_OF_DATASTREAM)
XivelyFeed feedget(feedid, datastreams_get, 1);
XivelyFeed feedput(feedid, datastreams_put, 1);
// then use different stream definitions for PUT and GET:
xivelyclient.get(feedget, xivelyKey);
xivelyclient.put(feedput, xivelyKey);
Related
I have connected an ESP32 LoRa to a moisture sensor. I have a script for reading data from the sensor, which works perfectly fine on its own:
#define SensorPin 27
float sensorValue = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println(analogRead(SensorPin));
delay(1000);
}
It returns about 1800-2000 when it is in some dirt.
I then want to send the data to another ESP32 LoRa, where i have used this tutorial: https://randomnerdtutorials.com/esp-now-two-way-communication-esp32/
It works fine in terms of sending data between the ESPs, but now my sensor constantly returns 0, which is super weird.
#include <esp_now.h>
#include <WiFi.h>
#include <Wire.h>
#define SensorPin 27
float sensorValue = 0;
// REPLACE WITH THE MAC Address of your receiver
uint8_t broadcastAddress[] = {0xA8, 0x03, 0x2A, 0xF3, 0x27, 0x88};
// Define variables to store BME280 readings to be sent
float temperature;
// Define variables to store incoming readings
float incomingTemp;
// Variable to store if sending data was successful
String success;
//Structure example to send data
//Must match the receiver structure
typedef struct struct_message {
float temp;
} struct_message;
// Create a struct_message called BME280Readings to hold sensor readings
struct_message BME280Readings;
// Create a struct_message to hold incoming sensor readings
struct_message incomingReadings;
esp_now_peer_info_t peerInfo;
// Callback when data is sent
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
Serial.print("\r\nLast Packet Send Status:\t");
Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
if (status ==0){
success = "Delivery Success :)";
}
else{
success = "Delivery Fail :(";
}
}
// Callback when data is received
void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) {
memcpy(&incomingReadings, incomingData, sizeof(incomingReadings));
Serial.print("Bytes received: ");
Serial.println(len);
incomingTemp = incomingReadings.temp;
}
void setup() {
// Init Serial Monitor
Serial.begin(115200);
// Set device as a Wi-Fi Station
WiFi.mode(WIFI_STA);
// Init ESP-NOW
if (esp_now_init() != ESP_OK) {
Serial.println("Error initializing ESP-NOW");
return;
}
// Once ESPNow is successfully Init, we will register for Send CB to
// get the status of Trasnmitted packet
esp_now_register_send_cb(OnDataSent);
// Register peer
memcpy(peerInfo.peer_addr, broadcastAddress, 6);
peerInfo.channel = 0;
peerInfo.encrypt = false;
// Add peer
if (esp_now_add_peer(&peerInfo) != ESP_OK){
Serial.println("Failed to add peer");
return;
}
// Register for a callback function that will be called when data is received
esp_now_register_recv_cb(OnDataRecv);
}
void loop() {
Serial.println("Sensor readings:");
getReadings();
// Set values to send
BME280Readings.temp = analogRead(SensorPin); // This returned 1800-2000 before, now it returns 0
// Send message via ESP-NOW
esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &BME280Readings, sizeof(BME280Readings));
if (result == ESP_OK) {
Serial.println("Sent with success");
}
else {
Serial.println("Error sending the data");
}
//updateDisplay();
delay(5000);
}
void getReadings(){
temperature = analogRead(SensorPin);
}
void updateDisplay(){ // currently not using this method because I do not care about getting data from the other ESP right now.
// Display Readings in Serial Monitor
Serial.println("INCOMING READINGS");
Serial.print("Temperature: ");
Serial.print(incomingReadings.temp);
Serial.println(" ºC");
}
When using WiFi - you can't use the ADC2 pins for analog input. I've seen the same issue. Here's a link showing a discussion on the ESP32 github pages.
Switch your sensor to one of the ADC1 pins and it should work.
i have a problem in my arduino code, i'm using esp8266 to get data from a sensor, and i have to send this data to node red dashboard using mqtt protocol. The problem is that i couldn't publish a "string".
this is my code:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#define Potentiometer A0
char ssid[] = "Fixbox-71CD43"; // your network SSID (name)
char pass[] = "ZTA0NWY2"; // your network password (use for WPA, or use as key for WEP)
//int keyIndex = 0; // your network key Index number (needed only for WEP)
const char* mqtt_server = "192.168.0.4";
int status = WL_IDLE_STATUS;
// if you don't want to use DNS (and reduce your sketch size)
// use the static IP instead of the name for the server:
// IPAddress server(74,125,232,128); // static IP for Google (no DNS)
//char server[] = "www.google.com"; // name address for Google (using DNS)
WiFiClient espclient;
PubSubClient client(espclient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
//char msg[MSG_BUFFER_SIZE];
//char message[50];
int sensorValue;
float VWC, Threshold1, Threshold2 , SubCalSlope, SubCalIntercept;
void setup() {
//*********************//*********************
// Declare variables for four 10HS sensors
//*********************//*********************
//*********************//*********************
unsigned long lastMsg = 0;
//*********************//*********************
//*********************//*********************
// SUBSTRATE CALIBRATION: You have to convert the voltage to VWC using soil or substrate specific calibration. Decagon has generic calibrations (check the 10HS manual at http://manuals.decagon.com/Manuals/13508_10HS_Web.pdf) or you can determine your own calibration. We used our own calibration for Fafard 1P (peat: perlite, Conrad Fafard, Inc., Agawam, MA)
SubCalSlope = 1.1785;
SubCalIntercept = -0.4938;
// IRRIGATION THRESHOLDS: Values used to trigger irrigation when the sensor readings are below a specific VWC (in units of m3/m3 or L/L)
Threshold1 = 0.4;
Threshold2 = 0.6;
//*********************//*********************
Serial.begin(115200);
// Configure digital pins D2 and D3 as outputs to apply voltage to all four sensors (D2: sensor 1 and 2; D3, sensor 3 and 4)
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
// client.setCallback(callback);
// initialize serial communication:
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// initialize the WiFi module:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi module not detected");
// don't continue:
while (true);
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to WiFi network ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println("Connected.\nWiFi network status:");
printWifiStatus();
Serial.println("\nStarting connection to MQTT server...");
client.setServer(mqtt_server, 1883);
// if you get a connection, report back via serial:
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("GW_sensor/humidity", "hello world");
client.publish("GW_sensor/salinity", "hello world");
// ... and resubscribe
client.subscribe("GW_sensor/#");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi device's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
}
void loop() {
char msg[10];
char msgtext[25];
String themsg;
// if there are incoming bytes available
// from the server, read them and print them:
// if the server's disconnected, stop the client:
if (!client.connected()) {
reconnect();
}
client.loop();
//*********************
// Apply power to 10HS sensor
// Wait 10 ms,
delay(10);
// Measure the analog output from sensor #1 and #2 (red wires connected to analog pins A0 and A1)
sensorValue = analogRead(0);
// And turn the power to the sensors off
digitalWrite(2, LOW);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 1.1V) that is used to calculate the VWC using a calibration equation
VWC = sensorValue * (1.1/1023.0) * SubCalSlope + SubCalIntercept;
//*********************//*********************
// Print the VWC
Serial.print("VWC (m3/m3): ");
Serial.print(" = ");
Serial.print(VWC);
//*********************//*********************
unsigned long now = millis();
//send data every 6 second
if (now - lastMsg > 500) {
lastMsg = now;
// Check to see if the VWC reading is below Threshold1
if (VWC < Threshold1) {
// If so, write an error message to the screen
Serial.print("WARNING:(too low) Irrigation needed. ");
sprintf(msgtext,"Irrigation needed",VWC);
}
// If the measured VWC is > Threshold2
if (VWC > Threshold2) {
// Write an error message to the screen
Serial.print("WARNING:(too high) Irrigation not needed. ");
sprintf(msgtext,"Irrigation not needed",VWC);
}
sprintf(msg,"%i",VWC);
//publish sensor data to MQTT broker
client.publish("GW_sensor/VWC_msg", msgtext);
client.publish("GW_sensor/VWC_val", msg);
}
please can you help me to fix my code? it can only send the values to the broker and the msg.
thank you all!
Payload isn't a "String", its a char buffer.
You need something like this:
snprintf (msg, BUF_SIZE, "msg: %i", VWC)
client.publish("GW_sensor/VWC_msg", msg)
The PubSubClient repo even has an ESP8266 example: https://github.com/knolleary/pubsubclient/blob/master/examples/mqtt_esp8266/mqtt_esp8266.ino
I have a project in which I use an Arduino UNO and an esp8266-01.
The Arduino is used to gather water high and water low sensor information and then transmit that information over to turn on/off a latching relay for a water valve to fill my pool. It also turns off and on a solar panel to charge my batteries and also turns off and on the esp8266.
I want to be able to connect to the wifi every time the esp8266 comes on and then send water level sensor information and battery level sensor information up to thingSpeak.
In the following code I have made it so that the first time the esp8266 is powered up it tries to connect to the local wifi but since no ip and password is provided it go to access point mode and opens a sign in page. I also provide the user to input their thingSpeak write api. This data is saved to the esp8266's eeprom so that in the future it will auto connect and send information to thingSpeak. This works fine.
My problem is getting the information from the water level sensor and the battery level into the esp8266. I was first gathering the data on the Arduino and then having the esp8266 connect and upload the information using AT commands using SerialSoftware. However to get the AUTOCONNECT to work I had to reprogram the esp8266 and now it doesn't respond to AT commands. I have tried to reprogram the RX and TX pins on the ESP but it only has two reading when there is water present it reads 1024 and no water is 0. Nothing in between. The battery level doesn't register anything. Can I do this using the TX and RX pins somehow as an analog input or can I take the information (numbers) gathered on the Arduino and had them off to the ESP8266 using the TX (arduino) and RX (ESP)to send them to ThingSpeak. I am at a loss and need help.
Here is the code on the ESP8266
#include <FS.h>
#include <ESP8266WiFi.h> //https://github.com/esp8266/Arduino
#include <EEPROM.h>
//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
#include <ArduinoJson.h>
//NEW STUFF START
char Password[36]="";
char apiKey[16]="";
WiFiClient client;
//eeprom new end
char defaultHost[100] = ""; //Thing Speak IP address (sometime the web address causes issues with ESP's :/
long itt = 500;
long itt2 = 500;
const byte wifiResetPin = 13;
int interruptPinDebounce = 0;
long debouncing_time = 1000;
volatile unsigned long wifiResetLastMillis = 0;
bool shouldSaveConfig = false;
void saveConfigCallback () {
Serial.println("Should save config");
shouldSaveConfig = true;}
void handleWifiReset(){
if(millis()<wifiResetLastMillis){
wifiResetLastMillis = millis();
}
if((millis() - wifiResetLastMillis)>= debouncing_time){
Serial.println("Clearing WiFi data resetting");
WiFiManager wifiManager;
wifiManager.resetSettings();
SPIFFS.format();
ESP.reset();
delay(1000);
}
wifiResetLastMillis = millis();
}
int addr = 0;
void setup() {
//EEPROM.begin(512); //Initialize EEPROM
WiFiManager wifiManager;
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(wifiResetPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(wifiResetPin), handleWifiReset,FALLING);
WiFiManagerParameter customAPIKey("apiKey", "ThingSpeakWriteAPI", apiKey, 16);
//END NEW STUFF
//WiFiManager
//Local intialization. Once its business is done, there is no need to keep it around
//WiFiManager wifiManager;
//NEW STUFF START
//wifiManager.setSaveConfigCallback(saveConfigCallback);
wifiManager.addParameter(&customAPIKey);
//END NEW STUFF
//reset saved settings
//wifiManager.resetSettings();
//set custom ip for portal
//wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
//fetches ssid and pass from eeprom and tries to connect
//if it does not connect it starts an access point with the specified name
//here "AutoConnectAP"
//and goes into a blocking loop awaiting configuration
wifiManager.autoConnect("AutoConnectAP");
Serial.println("Connected");
//NEW STUFF START
strcpy(apiKey, customAPIKey.getValue());
if (shouldSaveConfig) {
Serial.println("saving config");
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.createObject();
json["defaultHost"] = defaultHost;
json["apiKey"] = apiKey;
Serial.println("API");
Serial.print(apiKey);
String apiKey2 = String(apiKey);
File configFile = SPIFFS.open("/config.json", "w");
if (!configFile) {
Serial.println("failed to open config file for writing");
}
json.printTo(configFile);
json.printTo(Serial);
delay(1000);
configFile.close();
//end save
}
Serial.println("local ip");
Serial.println(WiFi.localIP());
//END NEW STUFF
//or use this for auto generated name ESP + ChipID
//wifiManager.autoConnect();
//Serial.println("WriteApi");
//Serial.println(apiKey);
//if you get here you have connected to the WiFi
//Serial.println("K)");
//save the custom parameters to FS
strcpy(apiKey,customAPIKey.getValue());
EEPROM.begin(512); //Initialize EEPROM
// write appropriate byte of the EEPROM.
// these values will remain there when the board is
// turned off.
EEPROM.write(addr, 'A'); //Write character A
addr++; //Increment address
EEPROM.write(addr, 'B'); //Write character A
addr++; //Increment address
EEPROM.write(addr, 'C'); //Write character A
//Write string to eeprom
String www = apiKey;
for(int i=0;i<www.length();i++) //loop upto string lenght www.length() returns length of string
{
EEPROM.write(0x0F+i,www[i]); //Write one by one with starting address of 0x0F
}
EEPROM.commit(); //Store data to EEPROM
//Read string from eeprom
}
//callback notifying us of the need to save config
void loop() {
Serial.begin(115200);
WiFiManager wifiManager;
if (WiFi.status() == WL_DISCONNECTED) {
wifiManager.autoConnect("AutoConnectAP");}
delay(5000);
if (WiFi.status() == WL_CONNECTED) { Serial.println("Connected");
WiFiClient client;
long itt = 500;
long itt2 = 500;
char defaultHost[100] = "api.thingspeak.com";
//HERE IS WHERE I CHANGE THE TX AND RX PIN FUNCTION
pinMode(1, FUNCTION_3);
pinMode(3, FUNCTION_3);
//THEN I ASSIGN THEM AS INPUT PINS
pinMode(1,INPUT);
pinMode(3,INPUT);
//ASSIGN EACH PIN TO AN INTERGER
const int waterInPin = 3; // Analog input pin that the potentiometer is attached to
const int BatteryInPin = 1; // Analog input pin that the battery is attached to
int waterSensorInValue;//reading our water lever sensor
int waterSensorOutValue;//conversion of water sensor value
int BatterySensorInValue;//reading our water lever sensor
int BatterySensorOutValue;//conversion of water sensor value
// put your main code here, to run repeatedly:
waterSensorInValue = analogRead(waterInPin);
BatterySensorInValue = analogRead(BatteryInPin);
waterSensorOutValue = map(waterSensorInValue,0,1024,0,225);
BatterySensorOutValue = map(BatterySensorInValue,0,1024,0,225);
Serial.println("WaterOutValue = ");
Serial.println(waterSensorOutValue );
Serial.println("WaterInValue = ");
Serial.println(waterSensorInValue );
Serial.println("BatteryOutValue = ");
Serial.println(BatterySensorOutValue );
Serial.println("BatteryInValue = ");
Serial.println(BatterySensorInValue);
//ASSIGN THE INPUT VALUES TO UPLOAD LONGS
itt = waterSensorInValue;
itt2 = BatterySensorInValue;
EEPROM.begin(512);
Serial.println(""); //Goto next line, as ESP sends some garbage when you reset it
Serial.print(char(EEPROM.read(addr))); //Read from address 0x00
addr++; //Increment address
Serial.print(char(EEPROM.read(addr))); //Read from address 0x01
addr++; //Increment address
Serial.println(char(EEPROM.read(addr))); //Read from address 0x02
//Read string from eeprom
String www;
//Here we dont know how many bytes to read it is better practice to use some terminating character
//Lets do it manually www.circuits4you.com total length is 20 characters
for(int i=0;i<16;i++)
{
www = www + char(EEPROM.read(0x0F+i)); //Read one by one with starting address of 0x0F
}
Serial.print(www); //Print the text on serial monitor
if (client.connect(defaultHost,80))
{ // "184.106.153.149" or api.thingspeak.com
itt++; //Replace with a sensor reading or something useful
//UPLOAD TO THINGSPEAK
String postStr = www;
postStr +="&field1=";
postStr += String(itt);
postStr +="&field2=";
postStr += String(itt2);
postStr += "\r\n\r\n\r\n";
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: "+String (www)+"\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(postStr.length());
client.print("\n\n\n");
client.print(postStr);
Serial.println("% send to Thingspeak");
}
client.stop();
Serial.println("Waiting…");
}
delay(55000);
}
As I said almost everything works ok. The ESP8266 comes on when the Arduino turns it on. The sensor comes on and gets the value. A value is uploaded to ThingSpeak (just not a useful one.
Any Ideas, suggestions, examples, tutorials will be greatly appreciated. Thanks.
My suggestion is use only one ESP32 to do all this work.
It´s much simpler and easier than using two micro-controllers.
You can use the ESP32 to read and send the sensor data and save the trouble of communicating two different micros.
I am using Arduino Mega2560 and GPRS Shield Sim900 and trying to send data to Xively using the code below.
What should I change in this code to send data to Xively with Sim900 GPRS Shield?
/*
* Xively WiFi Sensor Tutorial
*
* This sketch is designed to take sensors (from photocell) and
* upload the values to Xively at consistant intervals. At the
* same time it gets a setable value from Xively to adjust the
* brigthness of an LED. This sketch is reusable and can be
* adapted for use with many different sensors.
*
* Derived from Xively Ardino Sensor Client by Sam Mulube.
*
* By Calum Barnes 3-4-2013
* BSD 3-Clause License - [http://opensource.org/licenses/BSD-3-Clause]
* Copyright (c) 2013 Calum Barnes
*/
#include <SPI.h>
#include <WiFi.h>
#include <HttpClient.h>
#include <Xively.h>
char ssid[] = "SSID_HERE"; // your network SSID (name)
char pass[] = "PASS_HERE"; // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
// Your Xively key to let you upload data
char xivelyKey[] = "API_KEY_HERE";
//your xively feed ID
#define xivelyFeed FEED_ID_HERE
//datastreams
char sensorID[] = "LIGHT_SENSOR_CHANNEL";
char ledID[] = "LED_CHANNEL";
// Analog pin which we're monitoring (0 and 1 are used by the Ethernet shield)
#define sensorPin A2
//led connected pin
#define ledPin 9
// Define the strings for our datastream IDs
XivelyDatastream datastreams[] = {
XivelyDatastream(sensorID, strlen(sensorID), DATASTREAM_FLOAT),
XivelyDatastream(ledID, strlen(ledID), DATASTREAM_FLOAT),
};
// Finally, wrap the datastreams into a feed
XivelyFeed feed(xivelyFeed, datastreams, 2 /* number of datastreams */);
WiFiClient client;
XivelyClient xivelyclient(client);
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm \n");
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
//pin setup
pinMode(sensorPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.println("Starting single datastream upload to Xively...");
Serial.println();
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid, keyIndex, pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println("Connected to wifi");
printWifiStatus();
}
void loop() {
//adjust LED level. set from Xively
int getReturn = xivelyclient.get(feed, xivelyKey); //get data from xively
if (getReturn > 0) {
Serial.println("LED Datastream");
Serial.println(feed[1]);
} else {
Serial.println("HTTP Error");
}
//write value to LED - change brightness
int level = feed[1].getFloat();
if (level < 0) {
level = 0;
} else if (level > 255) {
level = 255;
}
//actually write the value
digitalWrite(ledPin, level);
//read sensor values
int sensorValue = analogRead(sensorPin);
datastreams[0].setFloat(sensorValue);
//print the sensor valye
Serial.print("Read sensor value ");
Serial.println(datastreams[0].getFloat());
//send value to xively
Serial.println("Uploading it to Xively");
int ret = xivelyclient.put(feed, xivelyKey);
//return message
Serial.print("xivelyclient.put returned ");
Serial.println(ret);
Serial.println("");
//delay between calls
delay(15000);
}
Added a temperature and humidity sensor (DHT11) to the standard Cosm Arduino sensor client example. Works for a short while then data streams flat line.
Any idea what could be causing the problem?
Many thanks
Staza
/**
* Cosm Arduino sensor client example.
*
`` * This sketch demonstrates connecting an Arduino to Cosm (https://cosm.com),
* using the new Arduino library to send and receive data.
/**
DHT11 temp and humidity sensor added to the COSM example code
**/
#include <SPI.h>
#include <Ethernet.h>
#include <HttpClient.h>
#include <Cosm.h>
#include <dht11.h>
//DHT11*********************************************************************
dht11 DHT11;
#define DHT11PIN 7//pin DHT11 sensor is connected to
//DHT11*********************************************************************
#define API_KEY "xxxxxx" // your Cosm API key
#define FEED_ID xxxxx // your Cosm feed ID
// MAC address for your Ethernet shield
byte mac[] = {xxxx, xxxx, xxxx, xxxx, xxxx, xxxx};
// Analog pin which we're monitoring (0 and 1 are used by the Ethernet shield)
int sensorPin = 2;
unsigned long lastConnectionTime = 0; // last time we connected to Cosm
const unsigned long connectionInterval = 15000; // delay between connecting to Cosm in milliseconds
// Initialize the Cosm library
// Define the string for our datastream ID
char sensorId[] = "sensor_reading";
char sensorId2[] = "DHT11_humidity_sensor_reading";
char sensorId3[] = "DHT11_temperature_sensor_reading";
CosmDatastream datastreams[] = {
CosmDatastream(sensorId, strlen(sensorId), DATASTREAM_FLOAT),
CosmDatastream(sensorId2, strlen(sensorId2), DATASTREAM_FLOAT),
CosmDatastream(sensorId3, strlen(sensorId3), DATASTREAM_FLOAT),
};
// Wrap the datastream into a feed
CosmFeed feed(FEED_ID, datastreams, 3 /* number of datastreams */);
EthernetClient client;
CosmClient cosmclient(client);
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println("Cosm Sensor Client Example");
Serial.println("==========================");
Serial.println("Initializing network");
while (Ethernet.begin(mac) != 1) {
Serial.println("Error getting IP address via DHCP, trying again...");
delay(15000);
}
Serial.println("Network initialized");
Serial.println();
}
void loop() {
// main program loop
if (millis() - lastConnectionTime > connectionInterval) {
//check DHT11 sensor is working OK
int chk = DHT11.read(DHT11PIN);
Serial.print("Read DHT11 sensor: ");
switch (chk)
{
case 0: Serial.println("OK"); break;
case -1: Serial.println("Checksum error"); break;
case -2: Serial.println("Time out error"); break;
default: Serial.println("Unknown error"); break;
}
sendData(); // send data to Cosm
getData(); // read the datastream back from Cosm
lastConnectionTime = millis(); // update connection time so we wait before connecting again
}
}
// send the supplied values to Cosm, printing some debug information as we go
void sendData() {
int sensorValue = analogRead(sensorPin);
int humidityDHT11 = ((float)DHT11.humidity);
int tempDHT11 = ((float)DHT11.temperature);
datastreams[0].setFloat(sensorValue);
datastreams[1].setFloat(humidityDHT11); //DHT11 humidity value*******
datastreams[2].setFloat(tempDHT11); //DHT11 temp value********
Serial.print("Read sensor value ");
Serial.println(datastreams[0].getFloat());
Serial.print("Read DHT11 humidity sensor value ");
Serial.println(datastreams[1].getFloat());
Serial.print("Read DHT11 temperature sensor value ");
Serial.println(datastreams[2].getFloat());
Serial.println("Uploading to Cosm");
int ret = cosmclient.put(feed, API_KEY);
Serial.print("PUT return code: ");
Serial.println(ret);
Serial.println();
}
// get the value of the datastream from Cosm, printing out the value we received
void getData() {
Serial.println("Reading data from Cosm");
int ret = cosmclient.get(feed, API_KEY);
Serial.print("GET return code: ");
Serial.println(ret);
if (ret > 0) {
Serial.print("Datastream is: ");
Serial.println(feed[0]);
Serial.print("Sensor value is: ");
Serial.println(feed[0].getFloat());
Serial.print("Datastream is: ");
Serial.println(feed[1]);
Serial.print("Sensor value is: ");
Serial.println(feed[1].getFloat());
Serial.print("Datastream is: ");
Serial.println(feed[2]);
Serial.print("Sensor value is: ");
Serial.println(feed[2].getFloat());
}
Serial.println();
}
Cosm has a debug page which might give you a clue as to what's going wrong.
This is currently located at: https://cosm.com/users/YOURUSERNAME/debug and it lists all incoming requests in real time as they come through. If your device works initially, you should see it start making requests successfully, and depending on how long it takes till it flatlines you might be able to keep this page open and hopefully see when it starts failing.
Do you see anything in the Arduino serial output when it seems to stop working, or does it seem like the Arduino is still happily sending data?
The other thing you could try is using Wireshark to inspect network traffic over the wire. Setting this up is slightly more involved however, so I'd suggest trying the other approaches first.
If none of this seems feasible I'd suggest mailing Cosm support with your feed details and have them look into it.
Seconding smulube's suggestion to monitor the serial output. Additionally, eliminate the variable of the COSM code & Ethernet: start debugging the issue with a sketch that is just taking readings from the DHT11 and monitor what's going on in the Arduino's serial output on your computer (in the Tools dropdown menu).
I just received my DHT22 (RHT03) from Sparkfun last night and tried several samples that wouldn't compile (my fault, I'm sure). The sample that worked "out of the box" for me with my Arduino Uno came from Tom Boyd's page (be sure to scroll to the bottom for the most recent code): DHT11 / Aosong AM2302 humidity and temperature sensor
I'm curious: how long did it take for your sensor to flatline? I integrated the code from Tom with the Cosm code and it's been running without interruption for me for an hour now.
Cheers,
Reeves