When I upload the code to try 2-way communication of LoRa Sx1278 with Arduino UNO it fails to work. I am using 2 modules with the same code. This is the output I receive:
23:09:27.186 -> Received packet: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^' with RSSI -70
23:09:28.207 -> Sending message
I understand the module receives a message but fails to read it, and the second LoRa module with the receiver code fails.
Here is my code:
#include <Wire.h>
#include <SPI.h>
#include <LoRa.h>
String outgoing;
byte msgCount = 0; // count of outgoing messages
byte localAddress = 0xBB; // address of this device
byte destination = 0xFF; // destination to send to
long lastSendTime = 0; // last send time
int interval = 300; // interval between sends
void setup() {
Serial.begin(115200);
while (!Serial);
Serial.println("LoRa Two-Way Communication");
if (!LoRa.begin(433E6)) {
Serial.println("Starting LoRa failed!");
delay(100);
while (1);
}
}
void loop() {
if (millis() - lastSendTime > interval) {
String message = "data from sensors";
Serial.println("Sending message");
sendMessage(message);
// Serial.println("Sending " + message);
lastSendTime = millis(); // timestamp the message
interval = random(50) + 300; // 2-3 seconds
}
// parse for a packet, and call onReceive with the result:
onReceive(LoRa.parsePacket());
}
void sendMessage(String outgoing) {
LoRa.beginPacket(); // start packet
LoRa.write(destination); // add destination address
LoRa.write(localAddress); // add sender address
LoRa.write(msgCount); // add message ID
LoRa.write(outgoing.length()); // add payload length
LoRa.print(outgoing); // add payload
LoRa.endPacket(); // finish packet and send it
msgCount++; // increment message ID
}
void onReceive(int packetSize) {
if (packetSize == 0) return;
// read packet header bytes:
int recipient = LoRa.read(); // recipient address
byte sender = LoRa.read(); // sender address
byte incomingMsgId = LoRa.read(); // incoming msg ID
byte incomingLength = LoRa.read(); // incoming msg length
// received a packet
Serial.print("Received packet: ");
String LoRaData = LoRa.readString();
Serial.print(LoRaData);
// read packet
while (LoRa.available()) {
Serial.print((char)LoRa.read());
}
// print RSSI of packet
Serial.print("' with RSSI ");
Serial.println(LoRa.packetRssi());
delay(1000);
}
I got the code from a tutorial and changed it so it is used to test the module for 2-way communication. Earlier, I tried an example from the library "LoRa Sender" and "LoRa Receiver" and it works flawlessly, so this isn't a hardware issue as far as I am concerned.
There are a few things that are not quite right in the code, but the main one is this: interval = random(50) + 300; // 2-3 seconds That's nowhere near 2 seconds. interval is in milliseconds, so a maximum of 50+300 will give you 0.35 seconds. Which means that both devices are transmitting NON-STOP, and can't hear each other. Try something like 2000 + random(1000)... Although there are better ways to get a random than using random. But anyway.
Also, stay off 433e6, it's a busy frequency, and if there are people nearby with a car remote control, you'll receive a lot of stuff not from you.
Related
I'm using this example from the Sparkfun Arduino Library
/*
Use ESP32 WiFi to get RTCM data from RTK2Go (caster) as a Client
By: SparkFun Electronics / Nathan Seidle
Date: November 18th, 2021
License: MIT. See license file for more information but you can
basically do whatever you want with this code.
This example shows how to obtain RTCM data from a NTRIP Caster over WiFi
and push it over I2C to a ZED-F9x.
It's confusing, but the Arduino is acting as a 'client' to a 'caster'. In this case we will
use RTK2Go.com as our caster because it is free. See the NTRIPServer example to see how
to push RTCM data to the caster.
You will need to have a valid mountpoint available. To see available mountpoints go here: http://rtk2go.com:2101/
This is a proof of concept to show how to connect to a caster via HTTP. Using WiFi for a rover
is generally a bad idea because of limited WiFi range in the field.
For more information about NTRIP Clients and the differences between Rev1 and Rev2 of the protocol
please see: https://www.use-snip.com/kb/knowledge-base/ntrip-rev1-versus-rev2-formats/
Feel like supporting open source hardware?
Buy a board from SparkFun!
ZED-F9P RTK2: https://www.sparkfun.com/products/16481
RTK Surveyor: https://www.sparkfun.com/products/18443
RTK Express: https://www.sparkfun.com/products/18442
Hardware Connections:
Plug a Qwiic cable into the GNSS and a ESP32 Thing Plus
If you don't have a platform with a Qwiic connection use the SparkFun Qwiic Breadboard Jumper (https://www.sparkfun.com/products/14425)
Open the serial monitor at 115200 baud to see the output
*/
#include <WiFi.h>
#include "secrets.h"
#include <SparkFun_u-blox_GNSS_Arduino_Library.h> //http://librarymanager/All#SparkFun_u-blox_GNSS
SFE_UBLOX_GNSS myGNSS;
//The ESP32 core has a built in base64 library but not every platform does
//We'll use an external lib if necessary.
#if defined(ARDUINO_ARCH_ESP32)
#include "base64.h" //Built-in ESP32 library
#else
#include <Base64.h> //nfriendly library from https://github.com/adamvr/arduino-base64, will work with any platform
#endif
//Global variables
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
long lastReceivedRTCM_ms = 0; //5 RTCM messages take approximately ~300ms to arrive at 115200bps
int maxTimeBeforeHangup_ms = 10000; //If we fail to get a complete RTCM frame after 10s, then disconnect from caster
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
void setup()
{
Serial.begin(115200);
Serial.println(F("NTRIP testing"));
Wire.begin(); //Start I2C
if (myGNSS.begin() == false) //Connect to the Ublox module using Wire port
{
Serial.println(F("u-blox GPS not detected at default I2C address. Please check wiring. Freezing."));
while (1);
}
Serial.println(F("u-blox module connected"));
myGNSS.setI2COutput(COM_TYPE_UBX); //Turn off NMEA noise
myGNSS.setPortInput(COM_PORT_I2C, COM_TYPE_UBX | COM_TYPE_NMEA | COM_TYPE_RTCM3); //Be sure RTCM3 input is enabled. UBX + RTCM3 is not a valid state.
myGNSS.setNavigationFrequency(1); //Set output in Hz.
Serial.print(F("Connecting to local WiFi"));
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(F("."));
}
Serial.println();
Serial.print(F("WiFi connected with IP: "));
Serial.println(WiFi.localIP());
while (Serial.available()) Serial.read();
}
void loop()
{
if (Serial.available())
{
beginClient();
while (Serial.available()) Serial.read(); //Empty buffer of any newline chars
}
Serial.println(F("Press any key to start NTRIP Client."));
delay(1000);
}
//Connect to NTRIP Caster, receive RTCM, and push to ZED module over I2C
void beginClient()
{
WiFiClient ntripClient;
long rtcmCount = 0;
Serial.println(F("Subscribing to Caster. Press key to stop"));
delay(10); //Wait for any serial to arrive
while (Serial.available()) Serial.read(); //Flush
while (Serial.available() == 0)
{
//Connect if we are not already. Limit to 5s between attempts.
if (ntripClient.connected() == false)
{
Serial.print(F("Opening socket to "));
Serial.println(casterHost);
if (ntripClient.connect(casterHost, casterPort) == false) //Attempt connection
{
Serial.println(F("Connection to caster failed"));
return;
}
else
{
Serial.print(F("Connected to "));
Serial.print(casterHost);
Serial.print(F(": "));
Serial.println(casterPort);
Serial.print(F("Requesting NTRIP Data from mount point "));
Serial.println(mountPoint);
const int SERVER_BUFFER_SIZE = 512;
char serverRequest[SERVER_BUFFER_SIZE];
snprintf(serverRequest, SERVER_BUFFER_SIZE, "GET /%s HTTP/1.0\r\nUser-Agent: NTRIP SparkFun u-blox Client v1.0\r\n",
mountPoint);
char credentials[512];
if (strlen(casterUser) == 0)
{
strncpy(credentials, "Accept: */*\r\nConnection: close\r\n", sizeof(credentials));
}
else
{
//Pass base64 encoded user:pw
char userCredentials[sizeof(casterUser) + sizeof(casterUserPW) + 1]; //The ':' takes up a spot
snprintf(userCredentials, sizeof(userCredentials), "%s:%s", casterUser, casterUserPW);
Serial.print(F("Sending credentials: "));
Serial.println(userCredentials);
#if defined(ARDUINO_ARCH_ESP32)
//Encode with ESP32 built-in library
base64 b;
String strEncodedCredentials = b.encode(userCredentials);
char encodedCredentials[strEncodedCredentials.length() + 1];
strEncodedCredentials.toCharArray(encodedCredentials, sizeof(encodedCredentials)); //Convert String to char array
snprintf(credentials, sizeof(credentials), "Authorization: Basic %s\r\n", encodedCredentials);
#else
//Encode with nfriendly library
int encodedLen = base64_enc_len(strlen(userCredentials));
char encodedCredentials[encodedLen]; //Create array large enough to house encoded data
base64_encode(encodedCredentials, userCredentials, strlen(userCredentials)); //Note: Input array is consumed
#endif
}
strncat(serverRequest, credentials, SERVER_BUFFER_SIZE);
strncat(serverRequest, "\r\n", SERVER_BUFFER_SIZE);
Serial.print(F("serverRequest size: "));
Serial.print(strlen(serverRequest));
Serial.print(F(" of "));
Serial.print(sizeof(serverRequest));
Serial.println(F(" bytes available"));
Serial.println(F("Sending server request:"));
Serial.println(serverRequest);
ntripClient.write(serverRequest, strlen(serverRequest));
//Wait for response
unsigned long timeout = millis();
while (ntripClient.available() == 0)
{
if (millis() - timeout > 5000)
{
Serial.println(F("Caster timed out!"));
ntripClient.stop();
return;
}
delay(10);
}
//Check reply
bool connectionSuccess = false;
char response[512];
int responseSpot = 0;
while (ntripClient.available())
{
if (responseSpot == sizeof(response) - 1) break;
response[responseSpot++] = ntripClient.read();
if (strstr(response, "200") > 0) //Look for 'ICY 200 OK'
connectionSuccess = true;
if (strstr(response, "401") > 0) //Look for '401 Unauthorized'
{
Serial.println(F("Hey - your credentials look bad! Check you caster username and password."));
connectionSuccess = false;
}
}
response[responseSpot] = '\0';
Serial.print(F("Caster responded with: "));
Serial.println(response);
if (connectionSuccess == false)
{
Serial.print(F("Failed to connect to "));
Serial.print(casterHost);
Serial.print(F(": "));
Serial.println(response);
return;
}
else
{
Serial.print(F("Connected to "));
Serial.println(casterHost);
lastReceivedRTCM_ms = millis(); //Reset timeout
}
} //End attempt to connect
} //End connected == false
if (ntripClient.connected() == true)
{
uint8_t rtcmData[512 * 4]; //Most incoming data is around 500 bytes but may be larger
rtcmCount = 0;
//Print any available RTCM data
while (ntripClient.available())
{
//Serial.write(ntripClient.read()); //Pipe to serial port is fine but beware, it's a lot of binary data
rtcmData[rtcmCount++] = ntripClient.read();
if (rtcmCount == sizeof(rtcmData)) break;
}
if (rtcmCount > 0)
{
lastReceivedRTCM_ms = millis();
//Push RTCM to GNSS module over I2C
myGNSS.pushRawData(rtcmData, rtcmCount, false);
Serial.print(F("RTCM pushed to ZED: "));
Serial.println(rtcmCount);
}
}
//Close socket if we don't have new data for 10s
if (millis() - lastReceivedRTCM_ms > maxTimeBeforeHangup_ms)
{
Serial.println(F("RTCM timeout. Disconnecting..."));
if (ntripClient.connected() == true)
ntripClient.stop();
return;
}
delay(10);
}
Serial.println(F("User pressed a key"));
Serial.println(F("Disconnecting..."));
ntripClient.stop();
}
on an ESP32 Thing Plus C with a ZED-F9P and it's working fine, but it only outputs RTCM data. How do I apply the RTCM data to the GPS data and achieve RTK? My goal is to have the ESP32 Thing Plus C output RTK Latitude and Longitude to the serial monitor.
Example output:
RTCM pushed to ZED: 163
RTCM pushed to ZED: 311
RTCM pushed to ZED: 1694
RTCM pushed to ZED: 1332
Any ideas would be appeciated! Thanks
Answered by PaulZC on Sparkfun Forum
Hi Jacob,
It sounds like everything is working OK. But, correct, there is
nothing in that example to actually print out the position.
Please try Example17. It is better-structured and uses callbacks to:
display your position; and push NMEA GGA data to the server. Some
NTRIP servers require the GGA data, others don't. If the GGA data
causes problems, you can comment this line to disable the push:
https://github.com/sparkfun/SparkFun_u- ... ck.ino#L81
Have fun! Paul
I have an application that gets the Arduino Nano information and sends it to ESP-01 via UART. The ESP-01 send this to MQTT.
NANO CODE:
#include "DHTesp.h"
#include <ArduinoJson.h>
#include <SoftwareSerial.h>
#define gasSensor A1
#define dhtPin 5
#define rain A2
#define soil A3
#define ldr A4
DHTesp dht;
void setup() {
Serial.begin(115200);
pinMode(gasSensor, INPUT);
pinMode(rain, INPUT);
pinMode(soil, INPUT);
pinMode(ldr, INPUT);
digitalWrite(dhtPin, LOW);
dht.setup(dhtPin, DHTesp::DHT11);
}
void loop() {
delay(dht.getMinimumSamplingPeriod());
float humidity = dht.getHumidity();
float temperature = dht.getTemperature();
DynamicJsonBuffer jBuffer;
JsonObject& measure = jBuffer.createObject();
JsonObject& data = jBuffer.createObject();
measure["gas"] = analogRead(gasSensor);
measure["humidity"] = humidity;
measure["temperature"] = temperature;
measure["heatindex"] = dht.computeHeatIndex(temperature, humidity, false);
measure["rain"] = analogRead(rain);
measure["soil"] = analogRead(soil);
measure["ldr"] = analogRead(ldr);
data["measure"] = measure;
data.printTo(Serial);
}
ESP-01 CODE:
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* mqtt_server = "0.0.0.0";
WiFiClient espClient;
PubSubClient client(espClient);
char mystr[100];
void setup() {
Serial.begin(115200);
WiFi.begin("", "");
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println();
Serial.print("Connected to IP: ");
Serial.println(WiFi.localIP());
client.setServer(mqtt_server, 1883);
}
void loop() {
if (client.connect("ESP")) {
Serial.println("STATUS MQTT-ESP: OK");
while (true) {
Serial.readBytes(mystr, 108);
client.publish("esp", mystr);
delay(1000);
}
} else {
Serial.println("STATUS MQTT-ESP: OFF");
}
}
But, I'm getting strange characters into MQTT:
And, at the connection between NANO <-uart-> Computer, the JSON is normal:
Someone could help me?
Thanks.
I am basing this answer on a bit of assumptions as I don't have an Arduino at hand.
You send your data like this:
data.printTo(Serial);
This sends the string holding the formatted JSON data. This does not include the terminating 0 byte.
Then you receive it like this:
char mystr[100];
...
while(true){
Serial.readBytes(mystr, 108);
client.publish("esp", mystr);
delay(1000);
}
This has multiple errors:
You do not care if you got any bytes at all. The method returns the number of bytes but you do not handle the return value at all. If you got 0 bytes within the timeout value, you will just send the previous message again instead of waiting for valid data.
You cannot put 108 bytes into memory location of 100 bytes.
You put an array of char into the publish method that does not contain any termination. How should that method know how many characters are really part of the string?
Try this:
while(true){
size_t num = Serial.readBytes(mystr, sizeof(mystr)-1);
mystr[num] = 0;
client.publish("esp", mystr);
delay(1000);
}
You do not have any protocol that allows you to detect when a message starts or ends. UART communiation is a byte stream without any boundaries for datagrams. You must ensure that you know what belongs to a message and what does not. This also means that you can never know if you have a complete message in your receive bufffer or an incomplete or even more than one message. It's up to you to detect and split messages. Fixing this is a bit more complex. I can only give some hints what you need to do.
a) Detect message boundaries:
You might send some terminator like \n, 0 or similar after each JSON string and scan for this extra byte on receiver side.
Or you can send the length of the string before you send the string.
You could also just check on receiver side when you have a matching pair of {}. This would not require any change on sender side.
b) Collect messages:
Call your read function as long as it takes until you detect the end of a string.
You might need to use intermediate buffer to collect multiple read buffers.
c) Forward messages:
As soon as you detected the end of a message, forward it via publish function.
Then move the remaining content of your collection buffer to the start of that buffer.
If you immediately find the end of another message, repeat that step.
If you don't find any complete message, continue to collect more data until the next message is complete.
I am new to the esp32 and LoRa messaging.
I am following the two examples in the heltect esp32 lora library.
The two modules I am using to send and receive data have an oled display... and I print their values to the serial monitor. The data values appear on the oled display but they are random characters in the serial monitor like this... "⸮⸮3⸮⸮JS⸮⸮⸮⸮⸮J)⸮⸮".
My question is how can I receive data from the sender in string/float/integer like form so I can perform logic on them. I am new to c++ and lora so any help is welcome.
I am pretty sure this(the first code block directly below this paragraph) is the piece of code responsible for printing the received message, but it is not printing in any type of format I can work with even when I change the "char" dtype to String.
while (LoRa.available()) {
Serial.print((char)LoRa.read());
}
Receiver Code
/*
Check the new incoming messages, and print via serialin 115200 baud rate.
by Aaron.Lee from HelTec AutoMation, ChengDu, China
成都惠利特自动化科技有限公司
www.heltec.cn
this project also realess in GitHub:
https://github.com/Heltec-Aaron-Lee/WiFi_Kit_series
*/
#include "heltec.h"
#define BAND 915E6 //you can set band here directly,e.g. 868E6,915E6
void setup() {
//WIFI Kit series V1 not support Vext control
Heltec.begin(true /*DisplayEnable Enable*/, true /*Heltec.LoRa Disable*/, true /*Serial Enable*/, true /*PABOOST Enable*/, BAND /*long BAND*/);
}
void loop() {
// try to parse packet
int packetSize = LoRa.parsePacket();
if (packetSize) {
// received a packet
Serial.print("Received packet '");
// read packet
while (LoRa.available()) {
Serial.print((char)LoRa.read());
}
// print RSSI of packet
Serial.print("' with RSSI ");
Serial.println(LoRa.packetRssi());
}
}
Sender Code
/*
Basic test program, send date at the BAND you seted.
by Aaron.Lee from HelTec AutoMation, ChengDu, China
成都惠利特自动化科技有限公司
www.heltec.cn
this project also realess in GitHub:
https://github.com/Heltec-Aaron-Lee/WiFi_Kit_series
*/
#include "heltec.h"
#define BAND 915E6 //you can set band here directly,e.g. 868E6,915E6
int counter = 0;
void setup() {
//WIFI Kit series V1 not support Vext control
Heltec.begin(true /*DisplayEnable Enable*/, true /*Heltec.LoRa Disable*/, true /*Serial Enable*/, true /*PABOOST Enable*/, BAND /*long BAND*/);
}
void loop() {
Serial.print("Sending packet: ");
Serial.println(counter);
// send packet
LoRa.beginPacket();
/*
* LoRa.setTxPower(txPower,RFOUT_pin);
* txPower -- 0 ~ 20
* RFOUT_pin could be RF_PACONFIG_PASELECT_PABOOST or RF_PACONFIG_PASELECT_RFO
* - RF_PACONFIG_PASELECT_PABOOST -- LoRa single output via PABOOST, maximum output 20dBm
* - RF_PACONFIG_PASELECT_RFO -- LoRa single output via RFO_HF / RFO_LF, maximum output 14dBm
*/
LoRa.setTxPower(14,RF_PACONFIG_PASELECT_PABOOST);
LoRa.print("hello ");
LoRa.print(counter);
LoRa.endPacket();
counter++;
digitalWrite(25, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(25, LOW); // turn the LED off by making the voltage LOW
delay(1000); // wait for a second
}
Perhaps, the serial monitor is configured with the wrong Baud Rate? In my case, default in IDE was 9600, but ESP32 sent with 115200. You can change the Baud Rate in a combobox in the serial monitor.
I'm in the middle of a project, and at a loss. I managed to get 2 Arduinos to talk to each other over SPI, but the slave stops during a series of transfers, seemingly without reason.
And what's really disturbing is that if I send more transfers from the master it continues the series, as if it was waiting to continue.
I'm thinking there's some acknowledgement or flag that stops code execution, but I have no idea.
#include <SPI.h>
boolean ack = 0;
#define ACK 2
byte buffer = 0;
byte rx = 0;
bool SSlast = HIGH;
byte clr = 0;
void stat_upd(byte dat, byte ric) {
Serial.println("---------------------------------------------");
Serial.println("Sent:");
Serial.println(dat, HEX);
Serial.println("Received:"); // 0x81 in teoria
Serial.println(ric, HEX);
return;
}
// Initialize SPI slave.
void SlaveInit(void) {
// Initialize SPI pins.
pinMode(SCK, INPUT);
pinMode(MOSI, INPUT);
pinMode(MISO, INPUT);
pinMode(SS, INPUT);
pinMode(ACK, OUTPUT);
// Enable SPI as slave.
SPCR = 0x6F;
clr = SPSR;
clr = SPDR;
SPI.begin();
}
// SPI Transfer.
byte SPItransfer(byte value) {
byte temp = 0;
SPDR = value;
// temp =SPI.transfer(value);
while (!(SPSR & (1 << SPIF)));
digitalWrite(ACK, LOW);
delay(1);
digitalWrite(ACK, HIGH);
delay(10);
return SPDR;
}
// The setup() function runs after reset.
void setup() { ///////////////// setup
Serial.begin(9600);
SlaveInit();
Serial.println("MC Initialized");
}
void loop() { ////////////// loop
// Slave Enabled?
if (!digitalRead(SS)) {
rx = SPItransfer(0x00);
stat_upd(0x00, rx);
rx = SPItransfer(0x08);
stat_upd(0x08, rx);
rx = SPItransfer(0x5a);
stat_upd(0x5a, rx);
rx = SPItransfer(0x5d);
stat_upd(0x5d, rx);
rx = SPItransfer(0x5c);
stat_upd(0x5c, rx);
rx = SPItransfer(0x5d);
stat_upd(0x5d, rx);
rx = SPItransfer(0x04);
stat_upd(0x04, rx);
rx = SPItransfer(0x00);
stat_upd(0x00, rx);
rx = SPItransfer(0x00);
stat_upd(0x00, rx);
rx = SPItransfer(0x80);
stat_upd(0x80, rx);
}
}
This is a bit of a guess, but my guesses wrt Arduino code are correct more often then not.
Check how you are sending the data via the Master.
As per this code, the slave waits for the SS pin to go low, then talks to the SPI and then clears the ack pin for 1 millisecond and then sends the communicaiton data via the serial port to the PC.
The problem I see here is that 1 millisecond is too small of a time frame for the master to detect it correctly.
So my guess is that, you have written the master code in such a manner, that it does not look at the ACK pin. Which means that the master will clear the SS pin, do the communication and then clear the SS pin immediately.
This is an issue because the slave talks to the serial port once this communication is done. Which means that when the master sets the SS pin low again, the slave might be sending data to the serial monitor, and may miss out on the communication altogether.
To fix this you need to change the slave code to continuously talk to the master while the SS pin is low, and only send the data back to the serial monitor when the SS pin becomes high.
I´m having a few problems with the Xively API for Arduino. My project consists of sending data collected by analog sensors through the Ethernet Shield and print them it in the Xively website (in my account for now). The problem is, i´ve to send two different variables to xively: one for the LDR values (LDREsq) and the other for the temperature values that is being gathered with a DHT_11 temperature sensor. However, i can only send the LDR values, not the temeperature ones. I´ve built two void functions one for each variable and both are connect to xively using different API Keys. But i just can´t upload the temperature values.
Here is my code - only the two functions - sendData for the LDREsq and sendData2 for the DHT.temperature which is read earlier (if you don´t understand one thing just tell me, i´ll explain because part of the code may be in portuguese):
`void sendData(int thisData) {
// if there's a successful connection:
if (client.connect(server, 80)) {
Serial.println("connecting...");
// send the HTTP PUT request:
client.print("PUT /v2/feeds/");
client.print(FEEDID);
client.println(".csv HTTP/1.1");
client.println("Host: api.xively.com");
client.print("X-ApiKey: ");//http://forum.arduino.cc/index.php?PHPSESSID=tork80mn5auvtpqsblge27jvn1&topic=229543.0
client.println(APIKEY);
client.print("User-Agent: ");
client.println(USERAGENT);
client.print("Content-Length: ");
// calculate the length of the sensor reading in bytes:
// 8 bytes for "sensor1," + number of digits of the data:
int thisLength = 8 + getLength(thisData);
client.println(thisLength);
// last pieces of the HTTP PUT request:
client.println("Content-Type: text/csv");
client.println("Connection: close");
client.println();
// here's the actual content of the PUT request:
client.print("LDREsq,");// the coma in the end is needed:
client.println(thisData);
Serial.println ("Success!");
}
else {
// if you couldn't make a connection:
Serial.println();
Serial.println("connection failed");
Serial.println("disconnecting.");
Serial.println();
client.stop();
}
// note the time that the connection was made or attempted:
lastConnectionTime = millis();
}
// This method calculates the number of digits in the
// sensor reading. Since each digit of the ASCII decimal
// representation is a byte, the number of digits equals
// the number of bytes:
void sendData2(int thisData2) {
// if there's a successful connection:
if (client.connect(server, 80)) {
Serial.println("connecting2...");
// send the HTTP PUT request:
client.print("PUT /v2/feeds/");
client.print(FEEDID);
client.println(".csv HTTP/1.1");
client.println("Host: api.xively.com");
client.print("X-ApiKey: ");//http://forum.arduino.cc/index.php?PHPSESSID=tork80mn5auvtpqsblge27jvn1&topic=229543.0
client.println(APIKEY_2);
client.print("User-Agent: ");
client.println(USERAGENT);
client.print("Content-Length: ");
// calculate the length of the sensor reading in bytes:
// 8 bytes for "sensor1," + number of digits of the data:
int thisLength = 8 + getLength(thisData2);
client.println(thisLength);
// last pieces of the HTTP PUT request:
client.println("Content-Type: text/csv");
client.println("Connection: close");
client.println();
// here's the actual content of the PUT request:
client.print("Temperatura,");
client.println(thisData2);
Serial.println ("Success 2!");
}
else {
// if you couldn't make a connection:
Serial.println("connection failed 2");
Serial.println();
Serial.println("disconnecting 2.");
client.stop();
}
// note the time that the connection was made or attempted:
lastConnectionTime = millis();
}`
And this is where those are called
temp3++;
if(temp3 >= 20)
{
sendData2(DHT.temperature);
delay(100);
temp3 = 0;
}
temp2++;
if (temp2 >= 10)
{
sendData(estadoLDREsq);
temp2 = 0;
}
Just let the Xivley library do the work for you:
#include <SPI.h>
#include <Ethernet.h>
#include <Xively.h>
// MAC address for your Ethernet shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// Your Xively key to let you upload data
char xivelyKey[] = "[Put your Key here]";
// Define a datastream textual name
char sensorId[] = "TEMP_001";
// Create as many datastreams you need (one in this case)
XivelyDatastream datastreams[] = {
XivelyDatastream(sensorId, strlen(sensorId), DATASTREAM_FLOAT),
};
// Finally, wrap the datastreams into a feed
XivelyFeed feed([put your feed number here], datastreams, 1); // Where 1 is the number of datastreams we are wrapping
// Create a Etherent client
EthernetClient client;
// Let Xively know about the Ethernet client
XivelyClient xivelyclient(client);
// Run all the setup you need
void setup(void) {
Serial.begin(9600);
while (Ethernet.begin(mac) != 1){
Serial.println("Error getting IP address via DHCP, trying again...");
delay(15000);
}
}
// Loop over
void loop(void) {
// Read your sensor
float celsius = [put your sensor reading value here];
// Copy sensor reading to the apropriate datastream
datastreams[0].setFloat(celsius);
// Ask Xively lib to PUT all datastreams values at once
int ret = xivelyclient.put(feed, xivelyKey);
// Printout PUT result
Serial.print("xivelyclient.put returned ");
Serial.println(ret);
// Wait 10 sec.
delay(10000);
}