I'm trying to let my Arduino and esp8266 send data to thingsboard and then subscribe to thingsboard's mqtt channel and get a timestamp from it but for some unknown reason, it just doesn't work. Checked server-side and it was ok, tried postman to simulate request and also getting the correct response from the server.
Also, I had read the documentation about esp8266 and it somehow did state that it only can have 1 connection simultaneously. But tried to let my Arduino to only subscribe to channel but it still doesn't work.
My code:(I'm using Arduino Mega for this)
#include "DHT.h"
#include <WiFiEspClient.h>
#include <WiFiEsp.h>
#include <WiFiEspUdp.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <TimeLib.h>
#define WIFI_AP "CEC"
#define WIFI_PASSWORD "#CEC#2017#CEC#"
#define TOKEN "A1_TEST_TOKEN"
// DHT
#define DHTPIN 2
#define DHTTYPE DHT22
char thingsboardServer[] = "192.168.0.250";
// Initialize the Ethernet client object
WiFiEspClient espClient;
// Initialize DHT sensor.
DHT dht(DHTPIN, DHTTYPE);
PubSubClient client(espClient);
int status = WL_IDLE_STATUS;
unsigned long lastSend;
unsigned long lastSync;
void setup() {
// initialize serial for debugging
Serial.begin(9600);
Serial1.begin(9600);
Serial2.begin(9600);
//serial pin
pinMode(LED_RUN_pin, OUTPUT);
//dht.begin();
InitWiFi();
lastSend = 0;
lastSync = 0;
//client subscribe thingsboard rpc PUBLISH msg
client.setServer( thingsboardServer, 1883 );
client.setCallback(on_message);
}
void loop() {
status = WiFi.status();
if ( status != WL_CONNECTED) {
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(WIFI_AP);
// Connect to WPA/WPA2 network
status = WiFi.begin(WIFI_AP, WIFI_PASSWORD);
delay(500);
}
}
if ( !client.connected() ) {
reconnect();
}
if ( millis() - lastSend > 30000 ) { // Update and send after 30 seconds
getAndSendTemperatureAndHumidityData();
lastSend = millis();
}
client.loop();
}
void getAndSendTemperatureAndHumidityData()
{
Serial.println("Collecting temperature data.");
// Reading temperature or humidity takes about 250 milliseconds!
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" *C ");
String temperature = String(t);
String humidity = String(h);
// Prepare a JSON payload string
String payload = "{";
payload += "\"temperature\":"; payload += temperature; payload += ",";
payload += "\"humidity\":"; payload += humidity;
payload += "}";
// Send payload
char attributes[100];
payload.toCharArray( attributes, 100 );
client.publish( "v1/devices/me/rpc/request/1", attributes , 1);
//Serial.println( attributes );
}
// Prepare a JSON payload string
String payload = "{method: getTime, params:{}}";
// Send payload
char attributes[100];
payload.toCharArray( attributes, 100 );
client.publish( "v1/A1_TEST_TOKEN/rpc", attributes );
//Serial.println( attributes );
}
void InitWiFi()
{
// initialize serial for ESP module
Serial1.begin(9600);
// initialize ESP module
WiFi.init(&Serial1);
// check for the presence of the shield
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue
while (false);
}
Serial.println("Connecting to AP ...");
// attempt to connect to WiFi network
while ( status != WL_CONNECTED) {
// Connect to WPA/WPA2 network
status = WiFi.begin(WIFI_AP, WIFI_PASSWORD);
delay(500);
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
//Serial.print("Connecting to Thingsboard node ...");
// Attempt to connect (clientId, username, password)
if ( client.connect("Arduino Uno Device", TOKEN, NULL) ) {
Serial.println( "[DONE]" );
delay(500);
// Serial.println("Subscribing RPC");
client.subscribe("v1/devices/me/rpc/request/+");
} else {
Serial.print( "[FAILED] [ rc = " );
Serial.print( client.state() );
Serial.println( " : retrying in 20 seconds]" );
// Wait 20 seconds before retrying
delay( 20000 );
}
}
}
void printDigits(int digits){
// utility function for digital clock display: prints preceding colon and leading 0
Serial.print(":");
if(digits < 10)
Serial.print('0');
Serial.print(digits);
}
// The callback for when a PUBLISH message is received from the server.
void on_message (char* topic, byte* payload, unsigned int length) {
//Serial.println("On message");
char json[length + 1];
strncpy (json, (char*)payload, length);
json[length] = '\23';
Serial.print("Topic: ");
Serial.println(topic);
Serial.print("Message: ");
Serial.println(json);
// Decode JSON request
StaticJsonBuffer<200> jsonBuffer;
JsonObject& data = jsonBuffer.parseObject((char*)json);
if (!data.success())
{
Serial.println("parseObject() failed");
return;
}
}
Probably a stupid remark, but is your TOKEN a valid Thingsboard device token? I assume you entered the value A1_TEST_TOKEN to hide your real authentication token.
I also assume you are trying to send sensor data (telemetry) to Thingsboard. Why did you decide to use the RPC API for sending data? I think it might be easier to use the MQTT Device API instead.
I don't have any experience in developing for Arduino. I am using Thingsboard together with a Raspberry PI to write and display sensor data. Hope you find a solution for your problem!
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'm trying to send data from my Wemos to Node-red via MQTT. I created a nested object I want to send to MQTT. From the serial of Arduino IDE the output is this (and that's what I want):
[{"AcX":-1,"AcY":-1,"AcZ":-1},{"AcX":-1,"AcY":-1,"AcZ":-1},{"AcX":-1,"AcY":-1,"AcZ":-1},{"AcX":-1,"AcY":-1,"AcZ":-1},{"AcX":-1,"AcY":-1,"AcZ":-1}]
It seems all correct but the debug node show nothing. what am I missing?
Here's the code:
//LIBRARY
#include <ESP8266WiFi.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>
#include <PubSubClient.h>
#include<Wire.h>
//JSON Array and mqtt data
#include <ArduinoJson.h>
#define MQTT_BUFFER 512
//MPU
const int MPU = 0x68; // I2C address of the MPU-6050
int16_t AcX, AcY, AcZ;
// IP adress Raspberry Pi
const char* mqttServer = "raspi-hyperink";
const int mqttPort = 1883;
// Set web server port number to 80
WiFiServer server(80);
// Variable to store the HTTP request
String header;
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
//MPU
Wire.begin();
Wire.beginTransmission(MPU);
Wire.write(0x6B); // PWR_MGMT_1 register
Wire.write(0); // set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
//SERIAL
Serial.begin(115200);
// WiFiManager
// Local intialization.
WiFiManager wifiManager;
// Uncomment and run it once, if you want to erase all the stored information
//wifiManager.resetSettings();
// set custom ip for portal
//wifiManager.setAPConfig(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");
// if you get here you have connected to the WiFi
Serial.println("Connected.");
//server.begin();
//CLIENT
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
server.begin();
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
Serial.println("-----------------------");
}
//RECONNECT FUNCTION
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("esp8266")) {
Serial.println("connected");
// Once connected, publish an announcement...
//client.publish("outTopic", "hello world");
// ... and resubscribe
//client.subscribe("inTopic");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop(){
WiFiClient(espClient) = server.available(); // Listen for incoming clients
if (espClient) { // If a new client connects,
Serial.println("New Client."); // print a message out in the serial port
String currentLine = ""; // make a String to hold incoming data from the client
while (espClient.connected()) { // loop while the client's connected
if (espClient.available()) { // if there's bytes to read from the client,
char c = espClient.read(); // read a byte, then
Serial.write(c); // print it out the serial monitor
header += c;
if (c == '\n') { // if the byte is a newline character
// if the current line is blank, you got two newline characters in a row.
// that's the end of the client HTTP request, so send a response:
if (currentLine.length() == 0) {
// HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
// and a content-type so the client knows what's coming, then a blank line:
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println();
// Display the HTML web page
client.println("<!DOCTYPE html><html>");
client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
client.println("<link rel=\"icon\" href=\"data:,\">");
// Web Page Heading
client.println("<body><h1>ESP8266 Web Server</h1>");
// The HTTP response ends with another blank line
client.println();
// Break out of the while loop
break;
} else { // if you got a newline, then clear currentLine
currentLine = "";
}
} else if (c != '\r') { // if you got anything else but a carriage return character,
currentLine += c; // add it to the end of the currentLine
}
}
}
// Clear the header variable
header = "";
// Close the connection
espClient.stop();
Serial.println("Client disconnected.");
Serial.println("");
}
if (!client.connected()) {
reconnect();
}
client.loop();
//compute the required size
const size_t CAPACITY = JSON_ARRAY_SIZE(5) + 5*JSON_OBJECT_SIZE(3);
//allocate the memory for the document
StaticJsonDocument<CAPACITY> doc;
//Create an empty array
JsonArray arr = doc.to<JsonArray>();
//definiamo quanti campioni registrare prima di inviarli tramite mqtt
for (int i=0; i<5; i++){
//MPU reading
Wire.beginTransmission(MPU);
Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H)
Wire.endTransmission(false);
Wire.requestFrom(MPU, 14, true); // request a total of 14 registers
AcX = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
AcY = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
AcZ = Wire.read() << 8 | Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
//Create JSON Array
JsonObject obj = doc.createNestedObject();
obj["AcX"] = AcX;
obj["AcY"] = AcY;
obj["AcZ"] = AcZ;
delay(3000);
}
//MQTT PUBLISHING JSON PACKAGE
char mqttData[MQTT_BUFFER];
serializeJson(doc, mqttData);
Serial.println(mqttData);
client.publish("esp8266", mqttData);
//client.subscribe("esp8266");
client.subscribe("esp8266");
delay(10000);
//Inserire un ciclo WHILE dove
//mentre il wifi è connesso invia i dati all'mqtt
//altrimenti li salva e basta
}
This is the mqtt node
Node-red debug
Normally debug should show you what you are publishing to your MQTT broker. As simple troubleshooting I would start moving backwards:
Replace the NodeRED client by any other one. Is the problem still there? Very likely it will be meaning that the problem is not on the MQTT client.
So we move a step "backwards"
Replace the MQTT Broker, use another one from the internet, one that you know works fine. The problem, is it still there? If it's not there, voilà, you found the problem (the broker), if it's still there, it means that the issue is on client publishing your msgs. It might be the msg itself.
So we move a step "backwards"
Replace you msg by another one, much simpler. Does it work ?
You get the idea :)
I am working on a simple device that alerts me when a button is pushed. At this time I am just trying to get the ESP8266 to activate the webhook event on it's own. It will connect to the wifi, but will not activate the event. I don't know if I'm going about this the wrong way or not. The http.Get() command returns back a -1. How do I activate the webhook? Any help is appreciated. The code is below.
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
const char* ssid="ATT2506";
const char* password = "XXXXXXXX";
int ledPin = 2;
void setup() {
pinMode(ledPin,OUTPUT);
digitalWrite(ledPin,HIGH);
Serial.begin(115200);
Serial.println();
Serial.print("Wifi connecting to ");
Serial.println( ssid );
WiFi.begin(ssid,password);
Serial.println();
Serial.print("Connecting");
while( WiFi.status() != WL_CONNECTED ){
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("Wifi Connected Success!");
Serial.print("NodeMCU IP Address : ");
Serial.println(WiFi.localIP() );
digitalWrite( ledPin , LOW);
}
void loop() {
if (WiFi.status() != WL_CONNECTED){
digitalWrite( ledPin , HIGH);
}
if (1==1) { //Check WiFi connection status
HTTPClient http; //Declare an object of class HTTPClient
http.begin("https://maker.ifttt.com/trigger/csalarm/with/key/XXXXXXXXXXX"); //Specify request destination
int httpCode = http.GET(); //Send the request
Serial.println(httpCode);
if (httpCode > 0) { //Check the returning code
String payload = http.getString(); //Get the request response payload
Serial.println(1); //Print the response payload
}
http.end(); //Close connection
}
delay(30000); //Send a request every 30 seconds
}
I'm trying every solution but no way....
I have the official Antenova GSM shield and the sensor DS18B20.
If I connect only the GSM shield without the sensor, I get -127 from the sensor and the shield is able to do the HTTP post to my server successfully. If the sensor is connected, it returns the right temperature, but the client.connect(server, port) never returns. I set the sensor pin to 12 instead of 2 to avoid problems, but seem like they are in conflict. I'm already using the external power supply.
// libraries
#include <GSM.h>
#include <OneWire.h>
#include <DallasTemperature.h>
// PIN Number
#define PINNUMBER "1218"
// APN data
#define GPRS_APN "web.omnitel.it" // replace your GPRS APN
#define GPRS_LOGIN "" // replace with your GPRS login
#define GPRS_PASSWORD "" // replace with your GPRS password
// Data wire is plugged into pin 2 on the Arduino
#define ONE_WIRE_BUS 12
// Setup a oneWire instance to communicate with any OneWire devices
// (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);
// initialize the library instance
GSMClient client;
GPRS gprs;
GSM gsmAccess;
// URL, path & port (for example: arduino.cc)
char server[] = "mancioboxblog.altervista.org";
char path[] = "/add.php";
int port = 80; // port 80 is the default for HTTP
// check the connection status
int con = 0;
// string to save the temp
String data = "";
// temp random
long temp;
void setup() {
//file version
Serial.println("Version: 1.6");
// initialize serial communications and wait for port to open:
Serial.begin(9600);
/* only for old USB usually not required
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}*/
Serial.println("Starting Arduino web client.");
// connection state
boolean notConnected = true;
// After starting the modem with GSM.begin()
// attach the shield to the GPRS network with the APN, login and password
while (notConnected) {
Serial.println("I'm trying to connect");
if ((gsmAccess.begin(PINNUMBER) == GSM_READY) &
(gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD) == GPRS_READY)) {
notConnected = false;
} else {
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("I'm connected");
// this operation is faster than connect to sim card
// Start up the temperature sensor library
Serial.println("initialize sensors");
sensors.begin();
// wait the the gsm shield is initialized
delay(1000);
}
void loop() {
/* GET THE TEMPERATURE */
// call sensors.requestTemperatures() to issue a global temperature
// request to all devices on the bus
Serial.print(" Requesting temperatures...");
sensors.requestTemperatures(); // Send the command to get temperatures
Serial.println("DONE");
Serial.print("Temperature for Device 1 is: ");
temp = sensors.getTempCByIndex(0);
Serial.print(temp); // Why "byIndex"?
// You can have more than one IC on the same bus.
// 0 refers to the first IC on the wire
//only for test
//temp = random(33);
data = "temp=" + (String)temp;
Serial.println("temp stored = " + data);
delay(2000);
con = client.connect(server, port);
// wait connection engaged
delay(2000);
// if you get a connection, report back via serial:
if (con == 1) {
Serial.println("connected");
// Make a HTTP request:
client.print("POST ");
client.print(path);
client.println(" HTTP/1.1");
client.print("Host: ");
client.println(server);
client.println("Content-Type: application/x-www-form-urlencoded; charset=UTF-8");
client.println("Connection: close");
client.print("Content-Length: ");
client.println(data.length());
client.println("");
client.println(data);
client.println("");
//what I'm sending
Serial.print("POST ");
Serial.print(path);
Serial.println(" HTTP/1.1");
Serial.print("Host: ");
Serial.println(server);
Serial.println("Content-Type: application/x-www-form-urlencoded; charset=UTF-8");
Serial.println("Connection: close");
Serial.print("Content-Length: ");
Serial.println(data.length());
Serial.println("");
Serial.println(data);
Serial.println("");
// if you didn't get a connection to the server:
} else if(con == -1){
Serial.println("connection failed: TIMED_OUT -1");
} else if(con == -2){
Serial.println("connection failed: INVALID_SERVER -2");
} else if(con == -3){
Serial.println("connection failed: TRUNCATED -3");
} else if(con == -4){
Serial.println("connection failed: INVALID_RESPONSE -4");
}
if(client.connected()){
client.stop(); // DISCONNECT FROM THE SERVER
Serial.println("enter in the if and stop the client");
}else{
Serial.println("the client is not connected");
}
//keep over 2 second otherwise is not able to close and reopen connection
delay(2000); // WAIT MINUTES BEFORE SENDING AGAIN
Serial.println("code repeat");
}
Is there a problem with my code? Maybe I shouldn't read the sensor before the client connects?