ESP32 printing weird chars infinitely, maybe due to EMI (Electromagnetic Interference) - arduino

I am working on ESP32 WebSocket communication. And after lot of hard work I'm facing serious problem that, In Serial Monitor Esp32 is printing weird chars infinitely. so to run esp32 perfectly every time I have to restart my esp32 board.
Esp32 board controlling devices(bulb, tube light, sockets etc.) perfectly but this problem occurring only with fan whenever I try to control using remotely or manually. But it running very smoothly on breadboard or when I'm not powering relay module with AC voltage.
Image of Error in Serial Monitor
I tried different different connections but problem is same.
when this problem is occurring
Case1. when fan connected with relay and trying to ON/OFF remotely or manually.
Case2. fan is disconnected from relay but connected with manual switch and trying to
ON/OFF.
I figured out or maybe I'm wrong that whenever I'm trying to control fan, it produce high EMI(Electromagnetic Interference) and that EMI cause an error(printing random chars infinitely in serial monitor) to ESP32.
Here is the main Circuit Diagram
Here is the code:-
#include <ArduinoWebsockets.h>
#include <WiFi.h>
#include <ArduinoJson.h>
#define ESP_NAME "Room 1"
//-----------------Appliances/Relay pins declaration or OUTPUT PINS------------------
#define Tubelight 22
#define Bulb 23
#define Fan 18
#define Socket1 19
//---------------Switches pin declaration or INPUT PINS-------------------
#define switch1 32
#define switch2 33
#define switch3 25
#define switch4 26
//--------------------Network Credentials------------------------------
const char* ssid = "xxxxxxxxxxxx"; //Enter SSID
const char* password = "xxxxxxxxxxxx"; //Enter Password
const char* websockets_connection_string = "wss://xxxxxxxx.glitch.me"; //server address
//------------------Eliminate Switch buttons debounce effect--------------------
unsigned long lastDebounceTime = 0;
int debounceDelay = 600;
//------------------------Switches Previous state---------------------
bool switch1_prev_state = HIGH; //here HIGH work as LOW in INPUT_PULLUP pinMode
bool switch2_prev_state = HIGH;
bool switch3_prev_state = HIGH;
bool switch4_prev_state = HIGH;
bool wb_config_state = false;
//------------------------Websocket Variables------------------------------
using namespace websockets;
WebsocketsClient clientt;
StaticJsonDocument<200> doc; //for parsing data sent from server
// This certificate was updated 15.04.2021, issues on Mar 15th 2021, expired on June 13th 2021
const char echo_org_ssl_ca_cert[] PROGMEM = \
"-----BEGIN CERTIFICATE-----\n" \
"MIIEZTCCA02gAwIBAgIQQAF1BIMUpMghjISpDBbN3zANBgkqhkiG9w0BAQsFADA/\n" \
"MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT\n" \
"DkRTVCBSb290IENBIFgzMB4XDTIwMTAwNzE5MjE0MFoXDTIxMDkyOTE5MjE0MFow\n" \
"MjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUxldCdzIEVuY3J5cHQxCzAJBgNVBAMT\n" \
"AlIzMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuwIVKMz2oJTTDxLs\n" \
"jVWSw/iC8ZmmekKIp10mqrUrucVMsa+Oa/l1yKPXD0eUFFU1V4yeqKI5GfWCPEKp\n" \
"Tm71O8Mu243AsFzzWTjn7c9p8FoLG77AlCQlh/o3cbMT5xys4Zvv2+Q7RVJFlqnB\n" \
"U840yFLuta7tj95gcOKlVKu2bQ6XpUA0ayvTvGbrZjR8+muLj1cpmfgwF126cm/7\n" \
"gcWt0oZYPRfH5wm78Sv3htzB2nFd1EbjzK0lwYi8YGd1ZrPxGPeiXOZT/zqItkel\n" \
"/xMY6pgJdz+dU/nPAeX1pnAXFK9jpP+Zs5Od3FOnBv5IhR2haa4ldbsTzFID9e1R\n" \
"oYvbFQIDAQABo4IBaDCCAWQwEgYDVR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8E\n" \
"BAMCAYYwSwYIKwYBBQUHAQEEPzA9MDsGCCsGAQUFBzAChi9odHRwOi8vYXBwcy5p\n" \
"ZGVudHJ1c3QuY29tL3Jvb3RzL2RzdHJvb3RjYXgzLnA3YzAfBgNVHSMEGDAWgBTE\n" \
"p7Gkeyxx+tvhS5B1/8QVYIWJEDBUBgNVHSAETTBLMAgGBmeBDAECATA/BgsrBgEE\n" \
"AYLfEwEBATAwMC4GCCsGAQUFBwIBFiJodHRwOi8vY3BzLnJvb3QteDEubGV0c2Vu\n" \
"Y3J5cHQub3JnMDwGA1UdHwQ1MDMwMaAvoC2GK2h0dHA6Ly9jcmwuaWRlbnRydXN0\n" \
"LmNvbS9EU1RST09UQ0FYM0NSTC5jcmwwHQYDVR0OBBYEFBQusxe3WFbLrlAJQOYf\n" \
"r52LFMLGMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjANBgkqhkiG9w0B\n" \
"AQsFAAOCAQEA2UzgyfWEiDcx27sT4rP8i2tiEmxYt0l+PAK3qB8oYevO4C5z70kH\n" \
"ejWEHx2taPDY/laBL21/WKZuNTYQHHPD5b1tXgHXbnL7KqC401dk5VvCadTQsvd8\n" \
"S8MXjohyc9z9/G2948kLjmE6Flh9dDYrVYA9x2O+hEPGOaEOa1eePynBgPayvUfL\n" \
"qjBstzLhWVQLGAkXXmNs+5ZnPBxzDJOLxhF2JIbeQAcH5H0tZrUlo5ZYyOqA7s9p\n" \
"O5b85o3AM/OJ+CktFBQtfvBhcJVd9wvlwPsk+uyOy2HI7mNxKKgsBTt375teA2Tw\n" \
"UdHkhVNcsAKX1H7GNNLOEADksd86wuoXvg==\n" \
"-----END CERTIFICATE-----\n";
void onMessageCallback(WebsocketsMessage message)//get messages From server
{
Serial.print("Got Message: ");
Serial.println(message.data());
// Deserialize the JSON document
DeserializationError error = deserializeJson(doc, message.data());
// Test if parsing succeeds.
if (error){
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.f_str());
return;
}
//store status of appliance
bool sts = doc["status"]=="ON"?LOW:HIGH; //here relay work in reverse
if(doc["room_name"] == ESP_NAME)
{
if(doc["appliance"] == "Tubelight")
{
digitalWrite(Tubelight, sts);
}
else if(doc["appliance"] == "Bulb")
{
digitalWrite(Bulb, sts);
}
else if(doc["appliance"] == "Fan")
{
digitalWrite(Fan, sts);
}
else if(doc["appliance"] == "Socket1")
{
digitalWrite(Socket1, sts);
}
}
else
{
Serial.println("False Room Name");
}
}
void onEventsCallback(WebsocketsEvent event, String data) {
if(event == WebsocketsEvent::ConnectionOpened) {
Serial.println("Connnection Opened");
} else if(event == WebsocketsEvent::ConnectionClosed) {
Serial.println("Connnection Closed");
wb_config_state = false;
// clientt.connect(websockets_connection_string);
} else if(event == WebsocketsEvent::GotPing) {
Serial.println("Got a Ping!");
} else if(event == WebsocketsEvent::GotPong) {
Serial.println("Got a Pong!");
}
}
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password); //Connecting to wifi
while(WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(200);
}
Serial.println("\nSuccessfully Connected with WiFi.");
//-------------------Pinmode Setup----------------------
//for relay or output
pinMode(Tubelight, OUTPUT);
pinMode(Bulb, OUTPUT);
pinMode(Fan, OUTPUT);
pinMode(Socket1, OUTPUT);
//pinMode for Switches
pinMode(switch1, INPUT_PULLUP);
pinMode(switch2, INPUT_PULLUP);
pinMode(switch3, INPUT_PULLUP);
pinMode(switch4, INPUT_PULLUP);
//-----------Prevent relay from jump start----------------
digitalWrite(Tubelight, HIGH);
digitalWrite(Bulb, HIGH);
digitalWrite(Fan, HIGH);
digitalWrite(Socket1, HIGH);
}
void loop()
{
if(WiFi.status() == WL_CONNECTED)
{
if(wb_config_state==false){
wb_config();
wb_config_state = true;
}else{clientt.poll();}
}
else{
WiFi.reconnect();
}
mannual();
}
void wb_config()
{
//--------------------Websocket communication establishment-------------------
clientt.onMessage(onMessageCallback);// run callback when messages are received
clientt.onEvent(onEventsCallback);// run callback when events are occuring
clientt.setCACert(echo_org_ssl_ca_cert);// Before connecting, set the ssl fingerprint of the server
clientt.addHeader("User-Agent", "Satya");//Add header
clientt.connect(websockets_connection_string);// Connect to server
clientt.ping();// Send a ping
}
void mannual()
{
//--------------------------------Switch 1----------------------------------
if((digitalRead(switch1)==HIGH)&& switch1_prev_state==LOW && debounce())
{
// Serial.println("Switch 1 / Tubelight --> OFF");
build_send_data("Tubelight", "OFF");
digitalWrite(Tubelight, HIGH);
switch1_prev_state = HIGH;
lastDebounceTime = millis();
}
if(digitalRead(switch1)==LOW && switch1_prev_state==HIGH && debounce())
{
// Serial.println("Switch 1 / Tubelight --> ON");
build_send_data("Tubelight", "ON");
digitalWrite(Tubelight, LOW);
switch1_prev_state = LOW;
lastDebounceTime = millis();
}
//--------------------------------Switch 2----------------------------------
if((digitalRead(switch2)==HIGH)&& switch2_prev_state==LOW && debounce())
{
// Serial.println("Switch 2 / Bulb --> OFF");
build_send_data("Bulb", "OFF");
digitalWrite(Bulb, HIGH);
switch2_prev_state = HIGH;
lastDebounceTime = millis();
}
if(digitalRead(switch2)==LOW && switch2_prev_state==HIGH && debounce())
{
// Serial.println("Switch 2 / Bulb --> ON");
build_send_data("Bulb", "ON");
digitalWrite(Bulb, LOW);
switch2_prev_state = LOW;
lastDebounceTime = millis();
}
//--------------------------------Switch 3----------------------------------
if((digitalRead(switch3)==HIGH)&& switch3_prev_state==LOW && debounce())
{
// Serial.println("Switch 3 / Fan --> OFF");
build_send_data("Fan", "OFF");
digitalWrite(Fan, HIGH);
switch3_prev_state = HIGH;
lastDebounceTime = millis();
}
if(digitalRead(switch3)==LOW && switch3_prev_state==HIGH && debounce())
{
// Serial.println("Switch 3 / Fan --> ON");
build_send_data("Fan", "ON");
digitalWrite(Fan, LOW);
switch3_prev_state = LOW;
lastDebounceTime = millis();
}
//--------------------------------Switch 4----------------------------------
if((digitalRead(switch4)==HIGH)&& switch4_prev_state==LOW && debounce())
{
// Serial.println("Switch 4 / Socket1 --> OFF");
build_send_data("Socket1", "OFF");
digitalWrite(Socket1, HIGH);
switch4_prev_state = HIGH;
lastDebounceTime = millis();
}
if(digitalRead(switch4)==LOW && switch4_prev_state==HIGH && debounce())
{
// Serial.println("Switch 4 / Socket1 --> ON");
build_send_data("Socket1", "ON");
digitalWrite(Socket1, LOW);
switch4_prev_state = LOW;
lastDebounceTime = millis();
}
}
void build_send_data(String appliance, String sts)
{
if(WiFi.status() == WL_CONNECTED)
{
doc["from"] = "ESP32";
doc["client_name"] = ESP_NAME;
doc["room_name"] = "Room 1";
doc["appliance"] = appliance;
doc["status"] = sts;
String send_data;
serializeJson(doc, send_data);
Serial.print("Send Message : ");
Serial.println(send_data);
clientt.send(send_data);
}
}
bool debounce()
{
return ((millis() - lastDebounceTime)> debounceDelay);
}
please help me to solve my problem and forgive me for any mistake in my english😊.

Could you try to use pull down (or pull up) resistors on the switches (the switch side of the pins)? Problem is if the 5V (i hope you don’t apply 5V to the pins?) falls away from the switch, the pins are floating.

Related

Single command relay on/off

Hey I have a home automation project I've been working on recently, in which I have an Arduino Mega with an Ethernet shield.
The Mega is waiting for Telnet commands. When a command is received, it turns a relay on. I then have an auto-hotkey script that sends Telnet commands when I press specific keys on my Windows PC.
My problem is that I plan to use 4 relays and right now I have to assign two keys per relay(one for on and for off).
I researched and found about impulse relays, but due to the lockdown, I can't buy any. I tried to find/write code that implemented the same idea in a simple relay but failed.
So, my question is, How do you trigger a relay on/off with a single command?
The code I am using:
#include <SPI.h>
#include <Ethernet.h>
int backlight = 7;
int fan = 6;
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network.
// gateway and subnet are optional:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,21,108);
IPAddress gateway(192,168,21,21);
IPAddress subnet(255, 255, 255, 0);
// telnet defaults to port 23
EthernetServer server(23);
boolean alreadyConnected = false; // whether or not the client was connected previously
String commandString;
void setup() {
pinMode(fan, OUTPUT);
pinMode(backlight, OUTPUT);
Ethernet.begin(mac, ip, gateway, subnet);
// start listening for clients
server.begin();
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
Serial.print("Chat server address:");
Serial.println(Ethernet.localIP());
}
void loop() {
// wait for a new client:
EthernetClient client = server.available();
// when the client sends the first byte, say hello:
if (client) {
if (!alreadyConnected) {
// clear out the input buffer:
client.flush();
commandString = ""; //clear the commandString variable
server.println("--> Please type your command and hit Return...");
alreadyConnected = true;
}
while (client.available()) {
// read the bytes incoming from the client:
char newChar = client.read();
if (newChar == 0x0D) { //If a 0x0D is received, a Carriage Return, then evaluate the command
server.print("Received this command: ");
server.println(commandString);
processCommand(commandString);
} else {
Serial.println(newChar);
commandString += newChar;
}
}
}
}
void processCommand(String command)
{
server.print("Processing command ");
server.println(command);
if (command.indexOf("backlight1") > -1){
server.println("Backlight On command received");
digitalWrite(backlight, HIGH); // sets the LED on
server.println("Backlight was turned on");
commandString = "";
return;
}
if (command.indexOf("backlight0") > -1){
Serial.println("Backlight Off command received");
digitalWrite(backlight, LOW); // sets the LED off
server.println("Backlight was turned off");
commandString = "";
return;;
}
if (command.indexOf("fan1") > -1){
server.println("fan On command received");
digitalWrite(fan, HIGH); // sets the LED on
server.println("Fan was turned on");
commandString = "";
return;
}
if (command.indexOf("fan0") > -1 ){
Serial.println("fan Off command received");
digitalWrite(fan, LOW); // sets the LED off
server.println("Fan was turned off");
commandString = "";
return;
}
commandString = "";
instructions();
}
void instructions()
{
server.println("Please use one of these commands:");
server.println("* backlight1, to turn backlight on");
server.println("* backlight0, to turn off the backligt");
server.println("* fan1, to turn on the fan");
server.println("* fan0, to turn off the fan");
}
If you want to have a single command (= toggle) you need a global bool var for each relay:
bool fanIsOn = false;
// The toggle command is fan
if (command.indexOf("fan") > -1 && fanIsOn == false){
server.println("fan On command received");
digitalWrite(fan, HIGH); // sets the LED on
server.println("Fan was turned on");
fanIsOn = true;
commandString = "";
return;
}
if (command.indexOf("fan") > -1 && fanIsOn == true){
Serial.println("fan Off command received");
digitalWrite(fan, LOW); // sets the LED off
server.println("Fan was turned off");
fanIsOn = false;
commandString = "";
return;
}
Hope this was what you meant

Openhab doesn't change the status of switch from manual overide

I have just made an account because of this particular problem I'm having with OpenHAB. I was following a tutorial from this https://openhardwarecoza.wordpress.com/2015/03/29/openhab-mqtt-arduino-and-esp8266-part-3-hardware-arduino-with-ethernet-shield/ site but since the reply there didn't help me. I decided to go to this site.
I have successfully installed OpenHAB and use it. When I turn the switch off and on from both the HTTP page and android device, It works just fine. But when I tried to manual override using a push button on an Arduino. It didn't update the state of the switch in both of them. I'm using windows with OpenHAB version 1.71
The Openhab server notices that there is an update of the state from the push button, but the button in the HTTP page and android device didn't change at all.
I have tested the connection using MQTTlens and it works just fine.
Below is my code
items configuration
Group All
Switch mqttsw1 "Switch 1" (all) {mqtt=">[mymosquitto:/arduino/l1/com:command:off:0],>[mymosquitto:/arduino/l1/com:command:on:1],<[mymosquitto:/arduino/l1/state:state:default]"}
Switch mqttsw2 "Switch 2" (all) {mqtt=">[mymosquitto:/arduino/l2/com:command:off:0],>[mymosquitto:/arduino/l2/com:command:on:1],<[mymosquitto:/arduino/l2/state:state:default]"}
Number temp "Temperature [%.1f °C]" <temperature> {mqtt="<[mymosquitto:/arduino/temp/state:state:default]"}
Number hum "Humidity [%.1f &#37]" <temperature> {mqtt="<[mymosquitto:/arduino/hum/state:state:default]"}
Sitemap configuration
sitemap dolphin label="Main Menu"
{
Frame label="Switch" {
Switch item=mqttsw1 label="Switch 1"
Switch item=mqttsw2 label="Switch 2"
}
Frame label="Weather" {
Text item=temp
Text item=hum
}
The Arduino Code
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
#include <DHT.h>
const int butt1 = 3;// the pin that the pushbutton is attached to
const int butt2 = 2;
const int ledPin1 = 5;
const int ledPin2 = 4;
int ledState1 = HIGH;
int buttonState1;
int lastButtonState1 = LOW;
int ledState2 = HIGH;
int buttonState2;
int lastButtonState2 = LOW;
long previousMillis = 0;
unsigned long currentMillis = 0;
long interval = 60000; // READING INTERVAL
int t = 0; // TEMPERATURE VAR
int h = 0; // HUMIDITY VAR
#define DHTPIN 24 // SENSOR PIN
#define DHTTYPE DHT11 // SENSOR TYPE - THE ADAFRUIT LIBRARY OFFERS SUPPORT FOR MORE MODELS
DHT dht(DHTPIN, DHTTYPE);
// Update these with values suitable for your network.
byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xEF };
IPAddress ip(192, 168, 1, 103);
IPAddress server(192, 168, 1, 100);
void callback(char* topic, byte* payload, unsigned int length);
EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);
void callback(char* topic, byte* payload, unsigned int length) {
Serial.println();
Serial.println("Callback");
Serial.print("Topic = ");
Serial.println(topic);
Serial.print("Payload = ");
for (int i=0;i<length;i++){
Serial.print((char)payload[i]);
}
Serial.println();
if (strcmp(topic,"/esp1/l1/com")==0) {
if (payload[0] == '0')
{
digitalWrite(ledPin1, LOW);
delay(100);
client.publish("/esp1/l1/state","0");
}
else if (payload[0] == '1')
{
digitalWrite(ledPin1, HIGH);
delay(100);
client.publish("/esp1/l1/state","1");
}
}
if (strcmp(topic,"/esp1/l2/com")==0) {
if (payload[0] == '0')
{
digitalWrite(ledPin2, LOW);
delay(100);
client.publish("/esp1/l2/state","0");
}
else if (payload[0] == '1')
{
digitalWrite(ledPin2, HIGH);
delay(100);
client.publish("/esp1/l2/state","1");
}
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("arduinoClient")) {
Serial.println("connected");
client.subscribe("/esp1/#");
client.publish("conn","Connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void push1() {
int reading1 = digitalRead(butt1);
buttonState1 = reading1;
if (buttonState1 == HIGH) {
ledState1 = !ledState1;
if (ledState1 < 1)
{
digitalWrite(ledPin1, LOW);
delay(100);
client.publish("/esp1/l1/com","0");
client.publish("/esp1/l1/state","0");
}
else
{
digitalWrite(ledPin1, HIGH);
delay(100);
client.publish("/esp1/l1/com","1");
client.publish("/esp1/l1/state","1");
}
}
}
void push2() {
int reading2 = digitalRead(butt2);
buttonState2 = reading2;
if (buttonState2 == HIGH) {
ledState2 = !ledState2;
if (ledState2 < 1)
{
digitalWrite(ledPin2, LOW);
delay(100);
client.publish("/esp1/l2/com","0");
client.publish("/esp1/l2/state","0");
}
else
{
digitalWrite(ledPin2, HIGH);
delay(100);
client.publish("/esp1/l2/com","1");
client.publish("/esp1/l2/state","1");
}
}
}
void temp() {
h = (int)dht.readHumidity();
t = (int)dht.readTemperature();
char temp[2];
char hum[3];
sprintf(hum, "%d", h);
sprintf(temp, "%d", t);
client.publish("/esp1/temp/state", temp);
client.publish("/esp1/hum/state", hum);
}
void setup() {
// put your setup code here, to run once:
pinMode(butt1, INPUT);
pinMode(butt2, INPUT);
// initialize the LED as an output:
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
Serial.begin(9600);
Ethernet.begin(mac, ip);
digitalWrite(ledPin1, LOW);
digitalWrite(ledPin2, LOW);
pinMode(26, OUTPUT); // sets the digital pin as output
pinMode(22, OUTPUT); // sets the digital pin as output
digitalWrite(26, HIGH); // sets +5v for the sensor
digitalWrite(22, LOW); // sets gnd for the sensor
h = (int)dht.readHumidity();
t = (int) dht.readTemperature();
if (client.connect("arduinoClient")) {
client.publish("conn","Connected");
client.subscribe("/esp1/#");
}
}
void loop() {
// put your main code here, to run repeatedly:
if (!client.connected()) {
reconnect();
}
currentMillis = millis();
if (currentMillis - previousMillis > interval) { // READ ONLY ONCE PER INTERVAL
previousMillis = currentMillis;
temp();
}
int reading1 = digitalRead(butt1);
int reading2 = digitalRead(butt2);
if (reading1 != buttonState1) {
push1();
}
if (reading2 != buttonState2){
push2();
}
client.loop();
}
If there are anybody who can help me I would be very grateful. Thank you for your attention !
Best Regards,
Aldi
If I remember correctly you should post back a status of ON or OFF instead of 1 or 0.
Could you change your arduino code to publish back ON and OFF and test that?
e.g.
client.publish("/esp1/l1/state","ON");

Serial.Available not working on Arduino nano

I have a serial application that runs from a nano into a current loop driver.
Now if I connect the Tx straight to the Rx the led is set to HIGH but if I link the Tx/Rx to the current loop board the LED isnt set at all. I have even added a serial to usb monitor to confirm that the current loop board is returning the same hex as is being passed. Any suggestions?
int timeout = 0;
void setup() {
// put your setup code here, to run once:
pinMode(13, OUTPUT);
Serial.begin(4800,SERIAL_8E1);
//Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
//delay(10000);
byte inByte1 = 0xF1;
byte inByte2 = 0x10;
byte inByte3 = 0xB0;
//if(timeout == 0)
//{
Serial.write(inByte1);
Serial.write(inByte2);
Serial.write(inByte3);
//}
//timeout = timeout+1;
//if(timeout == 50)
//{
// timeout=0;
//}
//delay(80);
byte inByte4 = 0xE1;
//Serial.println(Serial.available());
while (!Serial.available()) {
//timeout =0;
//byte inChar = Serial.read();
//Serial.println(inChar);
//digitalWrite(13, HIGH);
//if(inChar == inByte4)
//{
// digitalWrite(13, HIGH);
//}
Serial.write(inByte1);
Serial.write(inByte2);
Serial.write(inByte3);
delay(80);
}
while (Serial.available()) {
//timeout =0;
//byte inChar = Serial.read();
//Serial.println(inChar);
digitalWrite(13, HIGH);
//if(inChar == inByte4)
//{
// digitalWrite(13, HIGH);
//}
}
}
String ReadResult(Stream &serial)
{
int serialState = 0;
String content = "";
char character;
long interval = 10000;
//unsigned int timeout = 0;
unsigned long currentMillis = millis();
long previousMillis = millis();
while ( !serial.available() && serialState != 1) {
currentMillis = millis();
if(currentMillis - previousMillis > interval){
serialState = 1;
}
}
//timeout = 0;
//while (serial.available()) {
// character = serial.read();
// content += character;
//}
return content;
};
The driver that I was feeding to was not returning thecorrect voltage

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

Arduino Wifi Shield connections die after a few seconds of inactivity

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

Resources