i've been trying to build a system that detects in one room of the house the temperature using an esp8266 and a dht11 sensor, this esp sends the data to a webserver while the ESP12F grabs this data and should turn the relay on when a certain value is reached, however i can't get the relay to work, as soon as i upload the code, the led on the module turns but not at its full power, i tried with another code to see if it was just a faulty relay, but it works perfectly with the same connections. The code from the client side of the system is below:
#include "ESP8266WiFi.h"
#include "ESP8266HTTPClient.h"
#include "WiFiClient.h"
#include "ESP8266WiFiMulti.h"
ESP8266WiFiMulti WiFiMulti;
const char* ssid = "*******";
const char* password = "********";
//Your IP address or domain name with URL path
const char* serverNameTemp = "http://192.168.1.188/temperature";
const char* serverNameHumi = "http://192.168.1.188/humidity";
const char* serverNamePres = "http://192.168.1.188/pressure";
#include "Wire.h"
#include "Adafruit_GFX.h"
#include "Adafruit_SSD1306.h"
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
String temperature;
String humidity;
String pressure;
const int relay = 5;
float temp_int = temperature.toFloat();
unsigned long previousMillis = 0;
const long interval = 2000;
void setup() {
Serial.begin(115200);
Serial.println();
pinMode(relay,OUTPUT);
digitalWrite(relay,LOW);
// Address 0x3C for 128x64, you might need to change this value (use an I2C scanner)
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
display.clearDisplay();
display.setTextColor(WHITE);
int int_temp = temperature.toFloat();
WiFi.mode(WIFI_STA);
WiFiMulti.addAP(ssid, password);
while((WiFiMulti.run() == WL_CONNECTED)) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected to WiFi");
}
void loop() {
unsigned long currentMillis = millis();
if(currentMillis - previousMillis >= interval) {
// Check WiFi connection status
if ((WiFiMulti.run() == WL_CONNECTED)) {
int int_temp = temperature.toFloat();
temperature = httpGETRequest(serverNameTemp);
humidity = httpGETRequest(serverNameHumi);
pressure = httpGETRequest(serverNamePres);
if(int_temp < 26){
digitalWrite(relay,LOW);
}
else if (int_temp > 26){
digitalWrite(relay,HIGH);
}
Serial.println("Temperature: " + temperature + " *C - Humidity: " + humidity + " % - Pressure: " + pressure + " hPa");
Serial.println(int_temp);
Serial.println(temperature.toFloat());
display.clearDisplay();
// display temperature
display.setTextSize(2);
display.setCursor(0,0);
display.print("T: ");
display.print(temperature);
display.print(" ");
display.setTextSize(1);
display.cp437(true);
display.write(248);
display.setTextSize(2);
display.print("C");
// display humidity
display.setTextSize(2);
display.setCursor(0, 25);
display.print("H: ");
display.print(humidity);
display.print(" %");
// display pressure
display.setTextSize(2);
display.setCursor(0, 50);
display.print("P:");
display.print(pressure);
display.setTextSize(1);
display.setCursor(110, 56);
display.print("hPa");
display.display();
// save the last HTTP GET Request
previousMillis = currentMillis;
}
else {
Serial.println("WiFi Disconnected");
}
}
}
String httpGETRequest(const char* serverName) {
WiFiClient client;
HTTPClient http;
// Your IP address with path or Domain name with URL path
http.begin(client, serverName);
// Send HTTP POST request
int httpResponseCode = http.GET();
String payload = "--";
if (httpResponseCode>0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
payload = http.getString();
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
return payload;
}
Related
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 wrtitten a code for automatically watering plant using esp8266, dht11, moisture sensor but my code has some error, i dont know how to fix it
#include <DHT.h>
#include <ESP8266WiFi.h>
String apiKey = "X5AQ3EGIKMBYW31H"; // Enter your Write API key here
const char* server = "api.thingspeak.com";
const char *ssid = "CircuitLoop"; // Enter your WiFi Name
const char *pass = "circuitdigest101"; // Enter your WiFi Password
#define DHTPIN D3 // GPIO Pin where the dht11 is connected
DHT dht(DHTPIN, DHT11);
WiFiClient client;
const int moisturePin = A0; // moisteure sensor pin
const int motorPin = D0;
unsigned long interval = 10000;
unsigned long previousMillis = 0;
unsigned long interval1 = 1000;
unsigned long previousMillis1 = 0;
float moisturePercentage; //moisture reading
float h; // humidity reading
float t; //temperature reading
void setup()
{
Serial.begin(115200);
delay(10);
pinMode(motorPin, OUTPUT);
digitalWrite(motorPin, LOW); // keep motor off initally
dht.begin();
Serial.println("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print("."); // print ... till not connected
}
Serial.println("");
Serial.println("WiFi connected");
}
void loop()
{
unsigned long currentMillis = millis(); // grab current time
h = dht.readHumidity(); // read humiduty
t = dht.readTemperature(); // read temperature
if (isnan(h) || isnan(t))
{
Serial.println("Failed to read from DHT sensor!");
return;
}
moisturePercentage = ( 100.00 - ( (analogRead(moisturePin) / 1023.00) * 100.00 ) );
if ((unsigned long)(currentMillis - previousMillis1) >= interval1) {
Serial.print("Soil Moisture is = ");
Serial.print(moisturePercentage);
Serial.println("%");
previousMillis1 = millis();
}
if (moisturePercentage < 50) {
digitalWrite(motorPin, HIGH); // tun on motor
}
if (moisturePercentage > 50 && moisturePercentage < 55) {
digitalWrite(motorPin, HIGH); //turn on motor pump
}
if (moisturePercentage > 56) {
digitalWrite(motorPin, LOW); // turn off mottor
}
if ((unsigned long)(currentMillis - previousMillis) >= interval) {
sendThingspeak(); //send data to thing speak
previousMillis = millis();
client.stop();
}
}
void sendThingspeak() {
if (client.connect(server, 80))
{
String postStr = apiKey; // add api key in the postStr string
postStr += "&field1=";
postStr += String(moisturePercentage); // add mositure readin
postStr += "&field2=";
postStr += String(t); // add tempr readin
postStr += "&field3=";
postStr += String(h); // add humidity readin
postStr += "\r\n\r\n";
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(postStr.length()); //send lenght of the string
client.print("\n\n");
client.print(postStr); // send complete string
Serial.print("Moisture Percentage: ");
Serial.print(moisturePercentage);
Serial.print("%. Temperature: ");
Serial.print(t);
Serial.print(" C, Humidity: ");
Serial.print(h);
Serial.println("%. Sent to Thingspeak.");
}
}
This is the error which i get
Arduino: 1.8.9 (Windows 8.1), Board: "Generic ESP8266 Module, 80 MHz, Flash, Disabled, All SSL ciphers (most compatible), ck, 26 MHz, 40MHz, DOUT (compatible), 512K (no SPIFFS), 2, nonos-sdk 2.2.1 (legacy), v2 Lower Memory, Disabled, None, Only Sketch, 115200"
sketch_oct03a:7:16: error: 'D3' was not declared in this scope
#define DHTPIN D3 // GPIO Pin where the dht11 is connected
^
C:\Users\Shweta\Desktop\Libraries\sketch_oct03a\sketch_oct03a.ino:8:9: note: in expansion of macro 'DHTPIN'
DHT dht(DHTPIN, DHT11);
^
sketch_oct03a:12:22: error: 'D0' was not declared in this scope
const int motorPin = D0;
^
exit status 1
'D3' was not declared in this scope
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
Digital pins are not prefixed with D, unlike their analog counterparts.
#define DHTPIN 3
const int motorPin = 0;
I got this ESP32 Radio source code from this site.
I love it because its very simple radio and works fine on ESP32.
But sometime the sound is very choppy.
I suspect maybe because a lack of proper buffers, but I don't know how to fix it.
The code:
/*
WITHOUT OLED, only ESP32 & VS1053
VS1053 - connections detail
XRST = EN (D3)
MISO = D19
MOSI = D23
SCLK = D18
VCC = 5V / 3.3 V
Gnd = Gnd
*/
#include <VS1053.h> //ESP_VS1053_Library
#include <Preferences.h> //For reading and writing into the ROM memory
Preferences preferences;
unsigned int counter,old_counter,new_counter;
#include "helloMp3.h"
#include <WiFi.h>
#include <HTTPClient.h>
#include <esp_wifi.h>
char ssid[] = "SSID"; // your network SSID (name)
char pass[] = "PASSWORD"; // your network password
char *host[7] = {"184.95.47.178","us4.internet-radio.com","us3.internet-radio.com","us3.internet-radio.com","174.36.206.197","sj64.hnux.com","uk7.internet-radio.com"};
char *path[7] = {"/","/","/live.m3u","/","/","/","/"};
int port[7] = {9328,8266,8371,8297,8000,80,8226};
char *sname[7] = {"Love-Radio-USA","Smooth-Jazz-Florida","Best-Rock-Radio","Country-Radio","Venice-Classic-Radio","Smooth-Jazz-Global","UK-Top-40"};
int change=13;
bool x=true;
int status = WL_IDLE_STATUS;
WiFiClient client;
uint8_t mp3buff[32]; // vs1053 likes 32 bytes at a time
// Wiring of VS1053 board (SPI connected in a standard way)
#define VS1053_CS 32 //32
#define VS1053_DCS 33 //33
#define VS1053_DREQ 35 //15
#define VOLUME 100 // volume level 0-100
VS1053 player(VS1053_CS, VS1053_DCS, VS1053_DREQ);
void setup () {
pinMode(change,INPUT_PULLUP);
// initialize SPI
Serial.begin(115200);
delay(500);
// initialize SPI bus;
SPI.begin();
// initialize VS1053 player
player.begin();
// player.switchToMp3Mode(); // optional, some boards require this
player.setVolume(VOLUME);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
// display.drawString(0,15," Connecting..");
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected");
Serial.print("IP address:");
Serial.println(WiFi.localIP());
preferences.begin("my-app", false);
counter = preferences.getUInt("counter", 0);
old_counter=counter;
Serial.printf("Current counter value1: %u\n", counter);
//if(counter>0) counter=0;
//Serial.printf("Current counter value2: %u\n", counter);
delay(100);
player.playChunk(hello2, sizeof(hello2)); //VS1053 is wake up & running
station_connect(counter);
}
void loop() {
if (client.available() > 0) {
uint8_t bytesread = client.read(mp3buff, 32);
player.playChunk(mp3buff, bytesread);
}
if(digitalRead(change)==0 and x==true){
x=false;
counter = counter+1;
if(counter>6) counter=0;
preferences.putUInt("counter",counter);
new_counter=counter;
Serial.printf("Old_Counter: %u\n",old_counter);
Serial.printf("New_Counter: %u\n",new_counter);
Serial.printf("Set counter to new_value: %u\n", counter);
delay(500);
if(old_counter != new_counter) {
player.softReset();
x=true;
station_connect(new_counter);
preferences.putUInt("counter",new_counter);
}
}
}
void station_connect (int station_no ) {
if (client.connect(host[station_no],port[station_no]) ) {
Serial.println("Connected now");
}
Serial.print(host[station_no]);
Serial.println(path[station_no]);
Serial.println(sname[station_no]);
client.print(String("GET ") + path[station_no] + " HTTP/1.1\r\n" +
"Host: " + host[station_no] + "\r\n" +
"Connection: close\r\n\r\n");
}
How to improve the sound quality? Please help
Thanks for all the helpers! :)
I'm attempting to connect my Feather Huzzah to a local MQTT server but the program keeps blowing up and throwing a stack trace. When I attempt to decode the stack trace it's just empty, more frequently I only get part of the stack trace. Here's the code that I'm running, most of it is pretty similar to the pub/sub client example code for Arduino. I've tried erasing the flash on the device, that didn't seem to help.
Even stranger is that it worked once, but as soon as I tried it again adding the callback the code stopped working and blows up. If I try removing the callback nothing changes. I've tried stripping out a lot of the code just to see if I can get a consistent connection to MQTT, but that doesn't seem to be working either. The MQTT server is the latest Mosquitto from Ubuntu 18.04.
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <PubSubClient.h>
const char* ssid = "xxxxxxxx";
const char* password = "xxxxxxxxx";
const int hallPin = 14;
const int ledPin = 0;
const char* mqtt_server = "mosquitto.localdomain";
long lastMsg = 0;
char msg[100];
int value = 0;
int hallState = 0;
WiFiClient espClient;
PubSubClient client(espClient);
WiFiUDP ntpUDP;
// By default 'time.nist.gov' is used with 60 seconds update interval and
// no offset
NTPClient timeClient(ntpUDP);
// Setup and connect to the wifi
void setup_wifi() {
delay(100);
Serial.print("Connecting to: ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Wifi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.println("Gateway: ");
Serial.println(WiFi.gatewayIP());
}
//Reconnect to the MQTT broker
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("/homeassistant/devices/doorbell", "hello world");
// ... and resubscribe
client.subscribe("/homeassistant/doorbell/receiver");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
//Process messages incoming from the broker
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
}
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(hallPin, INPUT);
Serial.begin(115200);
setup_wifi();
timeClient.begin();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (WiFi.status() != WL_CONNECTED) {
setup_wifi();
}
if (!client.connected()) {
reconnect();
}
hallState = digitalRead(hallPin);
if (hallState == LOW) {
digitalWrite(ledPin, HIGH);
generateAndSendMessage();
delay(1000); //Add in a delay so it doesn't send messages extremely rapidly
} else {
digitalWrite(ledPin, LOW);
}
}
void generateAndSendMessage() {
timeClient.update();
StaticJsonBuffer<100> jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
root["sensor"] = "doorbell";
root["time"] = timeClient.getEpochTime();
root["value"] = 1;
root.printTo(msg);
Serial.println(msg);
client.publish("/homeassistant/devices/doorbell", msg);
}
Looking at the generateAndSendMessage function, I believe you are having an issue due to the size of the MQTT buffer.
The MQTT buffer is by default set to 128 bytes. This includes the length of the channel name along with the message.
The length of you channel is 32 bytes, and the json buffer you used to make the message is 100 bytes long. So you might just be exceeding the 128 byte mark.
Just declare this before including the PubSubClient.h
#define MQTT_MAX_PACKET_SIZE 200
This macro defines the buffer size of the PubSubClient to 200. You can change it to whatever you believe is required.
I hope this helps.
I have project where I'm getting data over nRF24L01 and using Mirf to that. Now I'm working for Hub which need to send data to my webservice. For ethernet my choice was ENC28j60 with ethercard library.
Question : How I can wait data from Mirf and just send data forward with Ethercard browseUrl? I can send data without Mirf but there's some loop which I'm not understand.
My code :
#include <SPI.h>
#include <Mirf.h>
#include <nRF24L01.h>
#include <MirfHardwareSpiDriver.h>
#include <EtherCard.h>
// Set network settings
static byte mymac[] = { 0x74, 0x69, 0x69, 0x2D, 0x30, 0x31 };
byte Ethernet::buffer[700];
static uint32_t timer;
// My webservice
const char website[] PROGMEM = "my.webservice.com";
// Mirf variables
int tmpVal1;
// Local components
const int Yellow = 6;
const int Blue = 5;
void setup() {
Serial.begin(57600);
// Setup leds
pinMode(Yellow, OUTPUT);
digitalWrite(Yellow, LOW);
pinMode(Blue, OUTPUT);
digitalWrite(Blue, LOW);
setupMirf();
setupEthernet();
}
void loop() {
// Waiting to get date from Mirf
while (!Mirf.dataReady()) {
//ether.packetLoop(ether.packetReceive());
}
Mirf.getData((byte *)&tmpVal1);
Serial.print(tmpVal1);
Serial.println(F(" C"));
// Receive responses
ether.packetLoop(ether.packetReceive());
if (millis() > timer) {
timer = millis() + 5000;
//Serial.println();
Serial.println("Sending data to webservice : ");
ether.browseUrl(PSTR("/sendingdata.asmx/sendingdata?"), "Device=100&DeviceValue=80", website, my_callback);
}
//ShowLedNotification();
}
// called when the client request is complete
static void my_callback (byte status, word off, word len) {
Serial.println(">>>");
Ethernet::buffer[off+300] = 0;
Serial.print((const char*) Ethernet::buffer + off);
Serial.println("...");
digitalWrite(Blue,HIGH);
delay(200);
digitalWrite(Blue,LOW);
}
void ShowLedNotification() {
if (tmpVal1 > 0 ) {
digitalWrite(Yellow, HIGH);
delay(1000);
digitalWrite(Yellow, LOW);
}
else
{
digitalWrite(Blue, HIGH);
delay(1000);
digitalWrite(Blue, LOW);
}
}
long readVcc() {
long result;
// Read 1.1V reference against AVcc
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
delay(2); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Convert
while (bit_is_set(ADCSRA,ADSC));
result = ADCL;
result |= ADCH<<8;
result = 1126400L / result; // Back-calculate AVcc in mV
return result;
}
//Setting up network and getting DHCP IP
void setupEthernet() {
Serial.println(F("Setting up network and DHCP"));
Serial.print(F("MAC: "));
for (byte i = 0; i < 6; ++i) {
Serial.print(mymac[i], HEX);
if (i < 5)
Serial.print(':');
}
Serial.println();
if (ether.begin(sizeof Ethernet::buffer, mymac) == 0)
Serial.println(F("Failed to access Ethernet controller"));
Serial.println(F("Setting up DHCP"));
if (!ether.dhcpSetup())
Serial.println(F("DHCP failed"));
ether.printIp("My IP: ", ether.myip);
ether.printIp("Netmask: ", ether.netmask);
ether.printIp("GW IP: ", ether.gwip);
ether.printIp("DNS IP: ", ether.dnsip);
// Check network connection
if (!ether.dnsLookup(website))
Serial.println("DNS failed");
ether.printIp("SRV: ", ether.hisip);
}
void setupMirf() {
//Initialize nRF24
Serial.println(F("Initializing Mirf"));
Mirf.spi = &MirfHardwareSpi;
Mirf.init();
Mirf.setRADDR((byte *)"serv1");
Mirf.payload = sizeof(tmpVal1);
// we use channel 90 as it is outside of WLAN bands
// or channels used by wireless surveillance cameras
Mirf.channel = 90;
Mirf.config();
}
Did get that work. Now using if clause not while Mirf.dataReady()
void loop() {
if (Mirf.dataReady()) {
Mirf.getData((byte *)&tmpVal1);
Serial.print(tmpVal1);
Serial.println(F(" C"));
ShowLedNotification();
// Send data to webservice
if (millis() > timer) {
timer = millis() + 5000;
Serial.println("Sending data to webservice");
String myVarsStr = "Device=";
myVarsStr += myDeviceID;
myVarsStr += "&DeviceValue=";
myVarsStr += tmpVal1;
char myVarsCh[40];
myVarsStr.toCharArray(myVarsCh, 40);
ether.browseUrl(PSTR("/receivedata.asmx/ReceiveData?"), myVarsCh, website, my_callback);
}
}
else
{
word pos = ether.packetReceive();
word len = ether.packetLoop(pos);
delay(200);
}
}