Arduino Wifi Shield connections die after a few seconds of inactivity - arduino

I have recently bought the Arduino WiFi Shield and I have updated the firmware to the latest version available.
I am using Webduino to create a kind of web service so I can check the pin's statuses and set their values to HIGH or LOW.
Everything work fine for the first seconds, however after a few seconds of inactivity, I can see the red error led turns on and later, when it recovers the connection to the network I cannot communicate again with the shield and I have to restart the Arduino board.
I have checked many posts in forums and I have seen there are more people with the same issue. Many of them talk about an issue in relation with the firmware, so it looks like there is a bug which is causing the issue.
Does anyone have an idea why it is happening? Could you point me into the right direction?
You can see my source code attached, so maybe you can see something wrong.
#include <SPI.h>
#include <WiFi.h>
#include <Streaming.h>
#define WEBDUINO_SERIAL_DEBUGGING 1
#include <WebServer.h>
#include <sha1.h>
char ssid[] = "******";
char pass[] = "******";
IPAddress ip(192,168,1,210);
int status = WL_IDLE_STATUS;
unsigned long sessionId;
#define WEBDUINO_METHOD_NOT_ALLOWED_MESSAGE "<h1>405 Requested method is not supported for resource</h1>"
#define CREDENTIALS "********"
#define PREFIX ""
#define ANALOG_PINS_AVAILABLE 5
#define DIGITAL_PINS_AVAILABLE 9
WebServer webserver(PREFIX, 80);
void welcome(WebServer &server) {
P(welcomeMsg1) = "HTTP/1.0 200 OK" CRLF;
server.printP(welcomeMsg1);
P(welcomeMsg2) =
"Content-Type: text/html" CRLF
CRLF
"<h1>Welcome to the web service</h1>";
server.printP(welcomeMsg2);
}
void httpMethodNotAllowed(WebServer &server) {
P(methodNotAllowedMsg1) = "HTTP/1.0 405 Method Not Allowed" CRLF;
server.printP(methodNotAllowedMsg1);
P(methodNotAllowedMsg2) =
"Content-Type: text/html" CRLF
CRLF
WEBDUINO_METHOD_NOT_ALLOWED_MESSAGE;
server.printP(methodNotAllowedMsg2);
}
void pinValuesJSON(WebServer &server) {
char sessionIdHeader[21];
sprintf(sessionIdHeader, "SessionId: %lu" CRLF, sessionId);
server.httpSuccess("application/json; charset=utf-8", sessionIdHeader);
server << "{";
server << "\"d2\":" << digitalRead(2) << ",";
server << "\"d3\":" << digitalRead(3) << ",";
server << "\"d5\":" << digitalRead(5) << ",";
server << "\"d6\":" << digitalRead(6);
server << "}";
}
void write(char *pin, char *value) {
if (pin[0] == 'a') {
analogWrite(strtoul(pin + 1, NULL, 10), strtoul(value, NULL, 10));
} else if (pin[0] == 'd') {
digitalWrite(strtoul(pin + 1, NULL, 10), strtoul(value, NULL, 10));
}
}
void defaultCmd(WebServer &server, WebServer::ConnectionType type, char *url_tail, bool tail_complete) {
if (server.checkCredentials(CREDENTIALS)) {
if (type == WebServer::GET) {
welcome(server);
} else {
httpMethodNotAllowed(server);
}
} else {
server.httpUnauthorized();
}
}
void pinsCmd(WebServer &server, WebServer::ConnectionType type, char *url_tail, bool tail_complete) {
#define PINLEN 5
#define VALUELEN 5
if (server.checkCredentials(CREDENTIALS)) {
if (type == WebServer::GET) {
pinValuesJSON(server);
} else if (type == WebServer::PUT) {
bool repeat;
char pin[PINLEN];
char value[VALUELEN];
do {
repeat = server.readPOSTparam(pin, PINLEN, value, VALUELEN);
write(pin, value);
} while (repeat);
pinValuesJSON(server);
}
} else {
server.httpUnauthorized();
}
}
void setup() {
randomSeed(analogRead(0));
sessionId = random(999999999);
/* Pins
* 13: SCK
* 12: MISO
* 11: MOSI
* 10: SS for WiFi
* 9: L9 (yellow) => Informational LED
* 7: Handshake between shield and Arduino
* 4: SS for SD card */
/* When SD card peripheral is not being used, it's necessary to set
pin 4 as an output and write a high to it */
pinMode(4, OUTPUT);
digitalWrite(4, HIGH);
/* Socket pins */
pinMode(2, OUTPUT);
digitalWrite(2, LOW);
pinMode(3, OUTPUT);
digitalWrite(3, LOW);
pinMode(5, OUTPUT);
digitalWrite(5, LOW);
pinMode(6, OUTPUT);
digitalWrite(6, LOW);
WiFi.config(ip);
while (status != WL_CONNECTED) {
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
delay(4000);
}
webserver.setDefaultCommand(&defaultCmd);
webserver.addCommand("pins", &pinsCmd);
/* start the webserver */
webserver.begin();
digitalWrite(8, HIGH);
}
void loop() {
/* process incoming connections one at a time forever */
webserver.processConnection();
}

Related

Ethernet Shield Stops After a While

I use Ethernet shield (W5100) and RC522 on my Arduino Uno. It works 1 or 2 hours (sometimes 15 minutes - sometimes 2 days) After this random time, it stops working. I mean stop with, RC-522 module don't read cards, and ethernet shield can't connect server. When i unplug power (1.5A - 12 V power suply) and re-plug it, it starts working successfully.
I need to this system works forever... This system reads mifare card, and sends to the server, after that it checks reply, and if the reply is "1", it triggers relay. (relay is 5V simple relay)
Some people said "Change your adaptor", and i changed it, nothing changed.
Some people said " use 10 microfarad capasitor between rst and gnd pin" and nothing changed.
and some people said, "this is arduino dude, it is for just studend give up and use stm32", and i didn't apply this suggestion yet. I want to know why this happens.
#include <SPI.h>
#include <Ethernet.h>
#include <MFRC522.h>
//Mac address of ethernet shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xEA };
//My Network info, i use static ip
byte ip[] = { 172, 16, 64, 78 };
byte gateway[] = { 172, 16, 64, 1 };
byte myserver[] = { 172, 16, 64, 46 };
byte subnet[] = { 255, 255, 255, 0 };
String CardInfo = "";
EthernetClient client;
String GateNo = "0";
String DeviceNo = "100";
String Answer = "";
MFRC522 mfrc522;
byte Key[] = { 0xff,0xff,0xff,0xff,0xff,0xff };
MFRC522::MIFARE_Key key;
void setup(){
//Disabling SD Card
pinMode(4,OUTPUT);
digitalWrite(4,HIGH);
Ethernet.begin(mac, ip, subnet, gateway);
KeyCreate();
mfrc522.PCD_Init(2, 8);
mfrc522.PCD_DumpVersionToSerial();
}
void sendGET()
{
//I used this line to guarantee the disconnect from server
client.stop();
Answer = "";
if (client.connect(myserver, 81)) {
client.println("GET /AccessCheck/CardNo=" + CardInfo + "&GateNo=" + GateNo + "&DeviceNo=" + DeviceNo + " HTTP/1.0");
client.println("Authorization: Basic xxxxxxxxxxxx");
client.println();
}
else {
//Ethernet.begin(mac, ip, subnet, gateway);
return;
}
int connectLoop = 0;
while(client.connected())
{
while(client.available())
{
char c = client.read();
Answer = Answer + c;
connectLoop = 0;
}
delay(1);
connectLoop++;
if(connectLoop > 5000)
{
client.stop();
return;
}
}
client.stop();
}
//This function disables eth and enable rc522 (and reverse)
void Switch(int i)
{
switch (i)
{
case 0:
digitalWrite(10, HIGH);
digitalWrite(2, LOW);
break;
case 1:
digitalWrite(2, HIGH);
digitalWrite(10, LOW);
break;
}
}
void AccessControl()
{
int AnswerLength = Answer.length();
pinMode(5, OUTPUT);
digitalWrite(5, HIGH);
if(Answer[AnswerLength-1] == 49)
{
digitalWrite(5, LOW);
delay(100);
digitalWrite(5, HIGH);
}
pinMode(5, INPUT);
pinMode(6, INPUT);
delay(1000);
}
void ReadCard()
{
byte len = 18;
MFRC522::StatusCode status;
byte MyBuffer[18];
status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 10, &key, &(mfrc522.uid));
status = mfrc522.MIFARE_Read(10, MyBuffer, &len);
int counter = 0;
//This line is check for turkish character
if(MyBuffer[0] == 221)
{
CardInfo = "X";
for (int i = 1; i < 16; i++)
{
if (MyBuffer[i] != 32)
{
CardInfo = CardInfo + (char)MyBuffer[i];
}
}
}
else
{
CardInfo = "";
for (int i = 0; i < 16; i++)
{
if (MyBuffer[i] != 32)
{
CardInfo = CardInfo + (char)MyBuffer[i];
}
}
}
mfrc522.PICC_HaltA();
mfrc522.PCD_StopCrypto1();
return;
}
void KeyCreate()
{
for (int i = 0; i < 6; i++)
{
key.keyByte[i] = Key[i];
}
}
void loop(){
Switch(0);
if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial()) {
ReadCard();
Switch(1);
sendGET();
AccessControl();
}
}
I expect it runs without freezing
Actual result is ethernet shield freezes after a while
I am using watchdog in some script . This functionality could reset auomatically your arduino if you dont reset the watchdog during the lapse.
you execute wdt_enable() in the setup() and wd_reset() at the beginning of the loop
time before watchdog firing argument of wdt_enable()
-------------------------------------------------------
15mS WDTO_15MS
30mS WDTO_30MS
60mS WDTO_60MS
120mS WDTO_120MS
250mS WDTO_250MS
500mS WDTO_500MS
1S WDTO_1S
2S WDTO_2S
4S WDTO_4S
8S WDTO_8S
example of use:
#include <avr/wdt.h>
void setup()
{
wdt_enable(WDTO_4S); // enable the watchdog
// will fire after 4s without reset
}
void loop(){
wdt_reset(); // resets the watchdog timer count
:
:
// if program hangs more than 4s, launch the reset of arduino
}

Can I temporarily disable Arduino Serial data receive?

I am working on a project and I encountered some problems.
I am using a DHT11 temperature sensor, an Arduino Uno and a TFT LCD display 2.2-inch model ITDB02-2.2.
What I want my project to do is to use 2 functioning modes for the sensor that I can select from the keyboard at the beginning of the program(one which is normal and one which will be used on special occasions)(so I need serial communication).
I noticed that the screen does not function if I start a serial communication at any rate so I used Arduino Serial.begin(9600) and Serial.end() for the mode selecting part of the program.
THE PROBLEM: My Arduino is still sending data through serial port even if I ended the serial communication and is looking like this:
I found out that Serial.end() function does not shut off serial communication but just the rate of communication. I am curious if you have any idea that I can use in order to get rid of the extra data, to neglect it before the computer receives it.
I`m stuck. I thought that interruptions would be a solution but they are not as far as I researched on the internet.
My ARDUINO CODE:
#include <SimpleDHT.h>
#include <UTFT.h>
UTFT myGLCD(ITDB22,A5,A4,A3,A2);
SimpleDHT11 dht11;
// Declare which fonts we will be using
extern uint8_t BigFont[];
//dht sensor data pin
int dataPinSensor1 = 12;
char mode;
int del;
void setup()
{
Serial.begin(9600);
Serial.print("Select functioning mode");
mode=SensorModeSelect(mode);
Serial.end();
pinMode(12, INPUT);
}
void loop()
{
if(mode=='1') {
FirstFuncMode(dataPinSensor1);
}
if(mode=='2') {
SecondFuncMode(dataPinSensor1,del);
}
delay(10);
}
char SensorModeSelect(char in)
{
char mode='0';
while(mode=='0') {
if(Serial.available() > 0) {
mode=Serial.read();
}
}
if (mode == '1') {
Serial.print("\nMOD1 SELECTED: press t key to aquire data \n");
}
if (mode == '2') {
Serial.print("\nMOD2 SELECTED: press q if you want to quit auto mode \n");
Serial.print("Select the data aquisition period(not smaller than 1 second) \n");
}
return mode;
}
int DataAqPeriod()
{
int del=0;
while(del==0) {
while(Serial.available() > 0) {
//Get char and convert to int
char a = Serial.read();
int c = a-48;
del *= 10;
del += c;
delay(10);
}
}
del*=1000;
return del;
}
void FirstFuncMode(int dataPinSensor1)
{
byte temperature = 0;
byte humidity = 0;
int err = SimpleDHTErrSuccess;
bool DispCond=false;
Serial.begin(9600);
delay(1500);
if (Serial.read() == 't' ) {
DispCond=true;
//read temperature and compare it with an error value
if((err = dht11.read(dataPinSensor1, &temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
Serial.print("unreliable measurement or unselected functioning mode");
}
byte f = temperature * 1.8 + 32;
Serial.print((int)temperature);
Serial.print(" *C, ");
Serial.print((int)f);
Serial.print(" *F, ");
Serial.print((int)humidity);
Serial.println(" H humidity");
delay(1500);
}
Serial.end();
if(DispCond==true) {
//Setup the LCD
myGLCD.InitLCD();
myGLCD.setFont(BigFont);
//print value on LCD
displayNoInit((int)temperature,(int)humidity);
}
}
void SecondFuncMode(int dataPinSensor1,int del)
{
bool q=false;
byte temperature = 0;
byte humidity = 0;
int err = SimpleDHTErrSuccess;
Serial.begin(9600);
del=DataAqPeriod();
Serial.end();
//Setup the LCD
myGLCD.InitLCD();
myGLCD.setFont(BigFont);
while(q==false) {
Serial.begin(9600);
//read temperature and compare it with an error value
if((err = dht11.read(dataPinSensor1, &temperature, &humidity, NULL)) != SimpleDHTErrSuccess) {
Serial.print("unreliable measurement or unselected functioning mode \n");
}
float f = temperature * 1.8 + 32;
Serial.print((int)temperature);
Serial.print(" *C, ");
Serial.print((int)f);
Serial.print(" *F, ");
Serial.print((int)humidity);
Serial.println(" H humidity");
delay(del);
if(Serial.read() == 'q')
q=true;
Serial.end();
displayNoInit((int)temperature,(int)humidity);
delay(10);
}
}
void displayNoInit(int temperature,int humidity)
{
//effective data display
myGLCD.clrScr();
myGLCD.setColor(255, 255, 0);
myGLCD.setBackColor(10,10,10);
myGLCD.print(" Temperature ", CENTER, 10);
myGLCD.setColor(254, 254, 254);
myGLCD.printNumI(temperature, CENTER, 45);
myGLCD.setColor(255, 255, 0);
myGLCD.print("C ", RIGHT, 45);
myGLCD.print("Relative Hum.", CENTER, 90);
myGLCD.setColor(204, 245, 250);
myGLCD.printNumI(humidity, CENTER, 120);
myGLCD.print("%", RIGHT, 120);
}
You are correct in the definition that Serial.end() does not disable the serial monitor, only the interrupts. After calling Serial.end() you can disable the serial monitor like so.
#include <avr/io.h>
// Save status register, disable interrupts
uint8_t oldSREG = SREG;
cli();
// Disable TX and RX
cbi(UCSRB, RXEN);
cbi(UCSRB, TXEN);
// Disable RX ISR
cbi(UCSRB, RXCIE);
// Flush the internal buffer
Serial.flush();
// Restore status register
SREG = oldSREG;

Feather Huzzah MQTT

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.

PIC16F628A to Arduino RF Communication Fails (433MHz)

I have pic16f628a and Arduino UNO...
I use MikroC for PIC...
I use 433 mhz transmitter and receiver.
My purpose is reading datas from Arduino UNO which I send from PIC16F628A; but I couldn't success it...
The circuit of PIC16F628A (Transmitter):
The circuit of Transmitter
I connected first pin of receiver to +5V of Arduino;
second pin of receiver to 12.pin of Arduino,
last pin of receiver to GND pin of Arduino.
Transmitter(PIC16F628A):
char pre[15]={'U','U','U','U','U',255,255,255,255,255,0,0,0,0,0}; //start bytes...
char ileri[3]={'f','r','w'};
char geri[3]={'b','c','k'};
char dur[3]={'d', 'u', 'r'};
char i=0,j=0;
void kurulum()
{
CMCON= 7;
TRISB= 2;
UART1_Init(2400);
delay_ms(100);
}
void main()
{
kurulum();
while(1)
{
for(i=0;i<15;i++)
{
UART1_Write(pre[i]);
}
for(j=0;j<10;j++)
{
for(i=0;i<3;i++)
{
while(!UART1_Tx_Idle());
UART1_Write(ileri[i]);
}
}
//*************************************************************
for(i=0;i<15;i++)
{
UART1_Write(pre[i]);
}
for(j=0;j<10;j++)
{
for(i=0;i<3;i++)
{
while(!UART1_Tx_Idle());
UART1_Write(geri[i]);
}
}
for(i=0;i<15;i++)
{
UART1_Write(pre[i]);
}
for(j=0;j<10;j++)
{
for(i=0;i<3;i++)
{
while(!UART1_Tx_Idle());
UART1_Write(dur[i]);
}
}
}
}
Receiver (Arduino):
// receiver.pde
//
// Simple example of how to use VirtualWire to receive messages
// Implements a simplex (one-way) receiver with an Rx-B1 module
//
// See VirtualWire.h for detailed API docs
// Author: Mike McCauley (mikem#airspayce.com)
// Copyright (C) 2008 Mike McCauley
// $Id: receiver.pde,v 1.3 2009/03/30 00:07:24 mikem Exp $
#include <VirtualWire.h>
const int led_pin = 13;
const int receive_pin = 12;
void setup()
{
delay(1000);
Serial.begin(9600); // Debugging only
Serial.println("setup");
// Initialise the IO and ISR
vw_set_rx_pin(receive_pin);
//vw_set_ptt_inverted(true); // Required for DR3100
vw_setup(2400); // Bits per sec
vw_rx_start(); // Start the receiver PLL running
pinMode(led_pin, OUTPUT);
}
void loop()
{
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;
if (vw_get_message(buf, &buflen)) // Non-blocking
{
int i;
digitalWrite(led_pin, HIGH); // Flash a light to show received good message
// Message with a good checksum received, dump it.
Serial.print("Got: ");
for (i = 0; i < buflen; i++)
{
Serial.print(buf[i], HEX);
Serial.print(' ');
}
Serial.println();
digitalWrite(led_pin, LOW);
}
}
I tried this code; but it didn't work...
There is another code;
void setup() {
Serial.begin(2400);
}
void loop() {
if (Serial.available() > 0){
Serial.println(Serial.read());
}
}
Before trying it; I connected data pin of receiver to RX pin of Arduino...
I usually got '0' byte.i
It didn't work as I desired...
SOLVED
The tests I have done so far were already taking the true datas but I was viewing them as numbers...
That's why I couldn't understand that It was working well.
Let's have a look at codes;
Transmitter:
The same as transmitter code at question message
Arduino (Receiver):
char x, msg[6];
int i= 0;
void setup() {
Serial.begin(2400);
}
void loop() {
if (Serial.available() > 0){
msg[i] = Serial.read();
if (msg[0]=='f' || msg[0] == 'b' || msg[0] == 'd'){
i++;
}
if (i==3){
Serial.println(msg);
i = 0;
msg[0]=0;
}
}
}
msg[0]=='f' || msg[0] == 'b' || msg[0] == 'd'
The purpose of comparison above is catching "frw", "bck" or "dur" messages which I sent transmitter...
The data pin of the receiver should be connected RX pin of the Arduino...

Send Mirf values with ethercard

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);
}
}

Resources