MQTT slow to subscribe and debounce problems - arduino

I'm after some desperately needed help please.
My setup consists of two arduinos (EtherTens) and a Raspberry Pi (running Mosquitto MQTT broker and Home Assistant). On one Arduino I have a security sensor shield with two PIRs attached and publishing states to the broker (this works 100% how it should).
On my other arduino, I have a couple of relay 8 driver shields (they use I2C) connected to two 8 channel relay boards (total of 16 relays connected).
I have toggle switches connected to switch a few lights in the house for hardware activation plus I have it setup to be activated through Home Assistant with MQTT topics.
The issues I've come across is random relay activation from turning other lights on in the house. I think there's some line interference somewhere and am hoping that a software debounce might solve the issue but I am lost in the code (I already have 10k pulldown resistors on my toggle switch setup).
The other issue is the the Arduino running the relay shields is really (and I mean really) slow to subscribe to the broker...I'm talking anywhere up to 10 seconds at times.
Would anyone be able to suggest the best way to fix my code please?
// This subscribes to MQTT IOT get the PIR sensor states //
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
#include <Wire.h>
#define SHIELD_1_I2C_ADDRESS 0x20 // 0x20 is the address with all jumpers removed
#define SHIELD_2_I2C_ADDRESS 0x21 // 0x21 is the address with a jumper on position A0
#define MAC_I2C_ADDRESS 0x50 // Microchip 24AA125E48 I2C ROM address
// Update these with values suitable for your network.
byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
IPAddress ip(192, 168, 2, 110);
IPAddress server(192, 168, 2, 149);
byte shield1BankA = 0; // Current status of all outputs on first shield, one bit per output
byte shield2BankA = 0; // Current status of all outputs on second shield, one bit per output
const int buttonPin2 = 2;
const int buttonPin3 = 3;
const int buttonPin4 = 4;
const int buttonPin5 = 5;
const int buttonPin6 = 6;
int buttonState2;
int buttonState3;
int buttonState4;
int buttonState5;
int buttonState6;
int lastButtonState2 = LOW;
int lastButtonState3 = LOW;
int lastButtonState4 = LOW;
int lastButtonState5 = LOW;
int lastButtonState6 = LOW;
unsigned long lastDebounceTime2 = 0;
unsigned long lastDebounceTime3 = 0;
unsigned long lastDebounceTime4 = 0;
unsigned long lastDebounceTime5 = 0;
unsigned long lastDebounceTime6 = 0;
unsigned long debounceDelay2 = 50;
unsigned long debounceDelay3 = 50;
unsigned long debounceDelay4 = 50;
unsigned long debounceDelay5 = 50;
unsigned long debounceDelay6 = 50;
EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);
void callback(char* topic, byte* payload, unsigned int length) {
// handle message arrived
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
// Switch on the Hallway Light
if (strcmp(topic, "left/hallwaylight") == 0) {
if ((char)payload[0] == '1')
{
setLatchChannelOn(1);
client.publish("left/hallwaylight/state", "1");
delay(500);
}
else if ((char)payload[0] == '0') //Controlled from Home Assistant
{
setLatchChannelOff(1);
delay(500);
client.publish("left/hallwaylight/state", "0");
}
}
// Switch on the Workshop Light - Sensor 2
if (strcmp(topic, "left/workshoplight") == 0) {
if ((char)payload[0] == '1')
{
setLatchChannelOn(2);
client.publish("left/workshoplight/state", "1");
delay(500);
}
else if ((char)payload[0] == '0') //Controlled from Home Assistant
{
setLatchChannelOff(2);
delay(500);
client.publish("left/workshoplight/state", "0");
}
}
/*
// Switch on the #############
if (strcmp(topic, "left/sensor2") == 0) {
if ((char)payload[0] == '1')
{
setLatchChannelOn(2);
client.publish("left/workshoplight/state", "1");
Serial.println("Workshop Light On");
delay(500);
}
else if ((char)payload[0] == '0') //Controlled from Home Assistant
{
setLatchChannelOff(2);
delay(500);
client.publish("left/workshoplight/*&^*&^&*", "0");
}
}
// Switch on the ####################
if (strcmp(topic, "left/sensor2") == 0) {
if ((char)payload[0] == '1')
{
setLatchChannelOn(2);
client.publish("left/workshoplight/state", "1");
Serial.println("Workshop Light On");
delay(500);
}
else if ((char)payload[0] == '0') //Controlled from Home Assistant
{
setLatchChannelOff(2);
delay(500);
client.publish("left/workshoplight/khebfjseghf", "0");
}
} */
// Switch on the Fountain
if (strcmp(topic, "left/fountain") == 0) {
if ((char)payload[0] == '1')
{
setLatchChannelOn(8);
client.publish("left/fountain/state", "1");
delay(500);
}
else if ((char)payload[0] == '0') //Controlled from Home Assistant
{
setLatchChannelOff(8);
delay(500);
client.publish("left/fountain/state", "0");
}
}
// Switch on the Entrance Lights
if (strcmp(topic, "left/entrancelights") == 0) {
if ((char)payload[0] == '1')
{
setLatchChannelOn(7);
client.publish("left/entrancelights/state", "1");
delay(500);
}
else if ((char)payload[0] == '0') //Controlled from Home Assistant
{
setLatchChannelOff(7);
delay(500);
client.publish("left/entrancelights/state", "0");
}
}
// Switch on the Foyer Lights
if (strcmp(topic, "left/foyerlights") == 0) {
if ((char)payload[0] == '1')
{
setLatchChannelOn(6);
client.publish("left/foyerlights/state", "1");
delay(500);
}
else if ((char)payload[0] == '0') //Controlled from Home Assistant
{
setLatchChannelOff(6);
delay(500);
client.publish("left/foyerlights/state", "0");
}
}
// Switch on the Driveway Lights - Sensor 1
if (strcmp(topic, "left/drivewaylights") == 0) {
if ((char)payload[0] == '1')
{
setLatchChannelOn(9);
client.publish("left/drivewaylights/state", "1");
delay(500);
}
else if ((char)payload[0] == '0') //Controlled from Home Assistant
{
setLatchChannelOff(9);
delay(500);
client.publish("left/drivewaylights/state", "0");
}
}
// Switch on the Spa Light
if (strcmp(topic, "left/spalight") == 0) {
if ((char)payload[0] == '1')
{
setLatchChannelOn(10);
client.publish("left/spalight/state", "1");
delay(500);
}
else if ((char)payload[0] == '0') //Controlled from Home Assistant
{
setLatchChannelOff(10);
delay(500);
client.publish("left/spalight/state", "0");
}
}
// Switch on the Pool Light
if (strcmp(topic, "left/poollight") == 0) {
if ((char)payload[0] == '1')
{
setLatchChannelOn(11);
client.publish("left/poollight/state", "1");
delay(500);
}
else if ((char)payload[0] == '0') //Controlled from Home Assistant
{
setLatchChannelOff(11);
delay(500);
client.publish("left/poollight/state", "0");
}
}
// Switch on the Tree Light
if (strcmp(topic, "left/treelight") == 0) {
if ((char)payload[0] == '1')
{
setLatchChannelOn(12);
client.publish("left/treelight/state", "1");
delay(500);
}
else if ((char)payload[0] == '0') //Controlled from Home Assistant
{
setLatchChannelOff(12);
delay(500);
client.publish("left/treelight/state", "0");
}
}
// Switch on the Fountains
if (strcmp(topic, "left/fountains") == 0) {
if ((char)payload[0] == '1')
{
setLatchChannelOn(13);
client.publish("left/fountains/state", "1");
delay(500);
}
else if ((char)payload[0] == '0') //Controlled from Home Assistant
{
setLatchChannelOff(13);
delay(500);
client.publish("left/fountains/state", "0");
}
}
// Switch on the Spa
if (strcmp(topic, "left/spa") == 0) {
if ((char)payload[0] == '1')
{
setLatchChannelOn(16);
client.publish("left/spa/state", "1");
delay(500);
}
else if ((char)payload[0] == '0') //Controlled from Home Assistant
{
setLatchChannelOff(16);
delay(500);
client.publish("left/spa/state", "0");
}
}
}
void setup()
{
Wire.begin(); // Wake up I2C bus
Serial.begin(38400);
Ethernet.begin(mac, ip);
// Note - the default maximum packet size is 128 bytes. If the
// combined length of clientId, username and password exceed this,
// you will need to increase the value of MQTT_MAX_PACKET_SIZE in
// PubSubClient.h
/* Set up the Relay8 shields */
initialiseShield(SHIELD_1_I2C_ADDRESS);
sendRawValueToLatch1(0); // If we don't do this, channel 6 turns on! I don't know why
initialiseShield(SHIELD_2_I2C_ADDRESS);
sendRawValueToLatch2(0); // If we don't do this, channel 6 turns on! I don't know why
pinMode(buttonPin2, INPUT);
pinMode(buttonPin3, INPUT);
pinMode(buttonPin4, INPUT);
pinMode(buttonPin5, INPUT);
pinMode(buttonPin6, INPUT);
}
void loop()
{
if (!client.connected()) {
reconnect();
}
int reading2 = digitalRead(buttonPin2);
int reading3 = digitalRead(buttonPin3);
int reading4 = digitalRead(buttonPin4);
int reading5 = digitalRead(buttonPin5);
int reading6 = digitalRead(buttonPin6);
if (reading2 != lastButtonState2) {
lastDebounceTime2 = millis();
}
if ((millis() - lastDebounceTime2) > debounceDelay2) {
if (reading2 != buttonState2) {
buttonState2 = reading2;
if ((buttonPin2 == HIGH) && What to put here????) {
toggleLatchChannel(1);
client.publish("left/hallwaylight/state", "1");
}
/*if (digitalRead(2) == HIGH) //Digital pin for Hall Light
{
toggleLatchChannel(1);
delay(1000);
}*/
}
}
lastButtonState2 = reading2;
if (digitalRead(3) == HIGH) //Digital pin for Fountain
{
toggleLatchChannel(6);
delay(1000);
}
if (digitalRead(4) == HIGH) //Digital pin for Entrance Lights
{
toggleLatchChannel(7);
delay(1000);
}
if (digitalRead(5) == HIGH) //Digital pin for Foyer Lights
{
toggleLatchChannel(8);
delay(1000);
}
if (digitalRead(6) == HIGH) //Digital pin for Driveway Lights - to be removed
{
toggleLatchChannel(9);
delay(1000);
}
client.loop();
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("leftArduinoClient")) {
Serial.println("connected");
client.subscribe("left/#");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void initialiseShield(int shieldAddress)
{
// Set addressing style
Wire.beginTransmission(shieldAddress);
Wire.write(0x12);
Wire.write(0x20); // use table 1.4 addressing
Wire.endTransmission();
// Set I/O bank A to outputs
Wire.beginTransmission(shieldAddress);
Wire.write(0x00); // IODIRA register
Wire.write(0x00); // Set all of bank A to outputs
Wire.endTransmission();
}
void toggleLatchChannel(byte channelId)
{
if ( channelId >= 1 && channelId <= 8 )
{
byte shieldOutput = channelId;
byte channelMask = 1 << (shieldOutput - 1);
shield1BankA = shield1BankA ^ channelMask;
sendRawValueToLatch1(shield1BankA);
}
else if ( channelId >= 9 && channelId <= 16 )
{
byte shieldOutput = channelId - 8;
byte channelMask = 1 << (shieldOutput - 1);
shield2BankA = shield2BankA ^ channelMask;
sendRawValueToLatch2(shield2BankA);
}
}
void setLatchChannelOn (byte channelId)
{
if ( channelId >= 1 && channelId <= 8 )
{
byte shieldOutput = channelId;
byte channelMask = 1 << (shieldOutput - 1);
shield1BankA = shield1BankA | channelMask;
sendRawValueToLatch1(shield1BankA);
}
else if ( channelId >= 9 && channelId <= 16 )
{
byte shieldOutput = channelId - 8;
byte channelMask = 1 << (shieldOutput - 1);
shield2BankA = shield2BankA | channelMask;
sendRawValueToLatch2(shield2BankA);
}
}
void setLatchChannelOff (byte channelId)
{
if ( channelId >= 1 && channelId <= 8 )
{
byte shieldOutput = channelId;
byte channelMask = 255 - ( 1 << (shieldOutput - 1));
shield1BankA = shield1BankA & channelMask;
sendRawValueToLatch1(shield1BankA);
}
else if ( channelId >= 9 && channelId <= 16 )
{
byte shieldOutput = channelId - 8;
byte channelMask = 255 - ( 1 << (shieldOutput - 1));
shield2BankA = shield2BankA & channelMask;
sendRawValueToLatch2(shield2BankA);
}
}
void sendRawValueToLatch1(byte rawValue)
{
Wire.beginTransmission(SHIELD_1_I2C_ADDRESS);
Wire.write(0x12); // Select GPIOA
Wire.write(rawValue); // Send value to bank A
shield1BankA = rawValue;
Wire.endTransmission();
}
void sendRawValueToLatch2(byte rawValue)
{
Wire.beginTransmission(SHIELD_2_I2C_ADDRESS);
Wire.write(0x12); // Select GPIOA
Wire.write(rawValue); // Send value to bank A
shield2BankA = rawValue;
Wire.endTransmission();
}
/** Required to read the MAC address ROM */
byte readRegister(byte r)
{
unsigned char v;
Wire.beginTransmission(MAC_I2C_ADDRESS);
Wire.write(r); // Register to read
Wire.endTransmission();
Wire.requestFrom(MAC_I2C_ADDRESS, 1); // Read a byte
while (!Wire.available())
{
// Wait
}
v = Wire.read();
return v;
}

Subscribing to the broker may take long because of the delay in this function:
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("leftArduinoClient")) {
Serial.println("connected");
client.subscribe("left/#");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
If you fail to connect on the first attempt, the program will wait for 5 seconds. Have you checked with serial monitor if this is the case? You should see two "failed..." messages.
As for relays: debouncing is only for hardware switches - when you press a button there is a short period when electrcal contacts in it bounce back and forth connecting and disconnecting several times. When you connect a switch to a microcontroller, it will read several transitions of digital pin connected to a button. Debouncing is a way to ignore these short pulses.
That being said, there is no need to debounce a signal that comes from another microcontroller, or a PC - there are no mechanical parts that can oscillate generating "fake" pulses. Try to write a short test program that will just activate all relays in a sequence, one at a time, without reading any external inputs. That way you will know, if the problem comes from a bug in your code, or is it a hardware problem.

Related

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

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.

Guru Meditation Error: Core 1 panic'ed (Cache disabled but cached memory region accessed) error shows when i use ESP now protocol

This error shows in my serial monitor see the code below for ESP32
and please help me to solve
Guru Meditation Error: Core 1 panic'ed (Cache disabled but cached
memory region accessed) Core 1 register dump: PC : 0x400d1580 PS
: 0x00060034 A0 : 0x400847fc A1 : 0x3ffbe7b0 A2 :
0x00000001 A3 : 0x00000002 A4 : 0x000000ff A5 :
0x4008b368 A6 : 0x00000000 A7 : 0x00000001 A8 :
0x80081348 A9 : 0x3ff5f024 A10 : 0x3ffbebfc A11 :
0x20000000 A12 : 0x00000400 A13 : 0x3ffb1b10 A14 :
0x00000026 A15 : 0x3ffc4598 SAR : 0x00000020 EXCCAUSE:
0x00000007 EXCVADDR: 0x00000000 LBEG : 0x40001609 LEND :
0x4000160d LCOUNT : 0x00000000 Core 1 was running in ISR context:
EPC1 : 0x40087157 EPC2 : 0x00000000 EPC3 : 0x00000000 EPC4
: 0x400d1580
Backtrace: 0x400d1580:0x3ffbe7b0 0x400847f9:0x3ffbe7d0
0x40087154:0x3ffb1b50 0x400e2aa9:0x3ffb1bc0 0x400e1379:0x3ffb1be0
0x400e17c7:0x3ffb1c00 0x400e015d:0x3ffb1c70 0x400e0c5f:0x3ffb1cc0
0x400df715:0x3ffb1d20 0x400dfc8d:0x3ffb1d60 0x4012d7e6:0x3ffb1d80
0x4012d9da:0x3ffb1dd0 0x4012da2d:0x3ffb1e00 0x400e2f57:0x3ffb1e20
0x400e30aa:0x3ffb1e40 0x400d70dd:0x3ffb1e60 0x400d2da9:0x3ffb1e80
0x400d1392:0x3ffb1f80 0x400d468b:0x3ffb1fb0 0x40088c05:0x3ffb1fd0
#include <esp_now.h>
#include <WiFi.h>
#include <IRremote.h>
int IR_Recv = 4;
#define CHANNEL 3
#define NUM_SLAVES 20 // ESP-Now can handle a maximum of 20 slaves
#define PRINTSCANRESULTS 0
IRrecv irrecv(IR_Recv);
decode_results results;
int slaveCount = 0; // Keeps count of no. of slaves with the defined prefix
esp_now_peer_info_t slaves[NUM_SLAVES]; // Stores the information of each of the slave that is added as a peer
void initESPNow();
void manageSlaves();
void scanForSlaves();
void onDataSent(const uint8_t *mac_addr, esp_now_send_status_t status);
void onDataRecv(const uint8_t *mac_add, const uint8_t *data, int data_len);
void sendData(uint8_t data);
void setup()
{
Serial.begin(115200);
irrecv.enableIRIn();
WiFi.mode(WIFI_MODE_STA);
initESPNow();
esp_now_register_send_cb(onDataSent);
esp_now_register_recv_cb(onDataRecv);
scanForSlaves();
manageSlaves();
}
void loop()
{
//Serial.println("Digital Read: " + String(digitalRead(IR_PIN)));
if(slaveCount > 0)
{
if (irrecv.decode(&results)){
long int decCode = results.value;
Serial.println(results.value);
switch (results.value){
case 2921: //when you press the 1 button
sendData(0);
break;
case 873: //when you press the 4 button
sendData(512);
break;
case 874: //when you press the 2 button
sendData(100);
break;
case 2922: //when you press the 5 button
sendData(300);
break;
default:
Serial.println('nothing to send');
break;
}
irrecv.resume(); // Receives the next value from the button you press
}
}
delay(3000);
}
// Init ESP Now with fallback
void initESPNow()
{
WiFi.disconnect();
if (esp_now_init() == ESP_OK)
{
Serial.println("ESPNow Init Success");
}
else
{
Serial.println("ESPNow Init Failed");
ESP.restart();
}
}
// Scan for slaves in AP mode
void scanForSlaves()
{
int8_t scanResults = WiFi.scanNetworks();
//reset slaves
memset(slaves, 0, sizeof(slaves));
slaveCount = 0;
Serial.println("");
if (scanResults == 0)
{
Serial.println("No WiFi devices in AP Mode found");
}
else
{
Serial.print("Found ");
Serial.print(scanResults);
Serial.println(" devices ");
for (int i = 0; i < scanResults; i++)
{
// Print SSID and RSSI for each device found
String SSID = WiFi.SSID(i);
int32_t RSSI = WiFi.RSSI(i);
String BSSIDstr = WiFi.BSSIDstr(i);
if (PRINTSCANRESULTS)
{
Serial.print(i + 1);
Serial.print(": ");
Serial.print(SSID);
Serial.print(" [");
Serial.print(BSSIDstr);
Serial.print("]");
Serial.print(" (");
Serial.print(RSSI);
Serial.print(")");
Serial.println("");
}
delay(10);
// Check if the current device starts with `Slave`
if (SSID.indexOf("Slave") == 0)
{
// SSID of interest
Serial.print(i + 1);
Serial.print(": ");
Serial.print(SSID);
Serial.print(" [");
Serial.print(BSSIDstr);
Serial.print("]");
Serial.print(" (");
Serial.print(RSSI);
Serial.print(")");
Serial.println("");
// Get BSSID => Mac Address of the Slave
int mac[6];
if(6 == sscanf(BSSIDstr.c_str(), "%x:%x:%x:%x:%x:%x%c", &mac[0], &mac[1], &mac[2], &mac[3], &mac[4], &mac[5]))
{
for(int j = 0; j < 6; j++)
{
slaves[slaveCount].peer_addr[j] = (uint8_t)mac[j];
}
}
slaves[slaveCount].channel = CHANNEL; // pick a channel
slaves[slaveCount].encrypt = 0; // no encryption
slaveCount++;
}
}
}
if(slaveCount > 0)
{
Serial.print(slaveCount); Serial.println(" Slave(s) found, processing..");
}
else
{
Serial.println("No Slave Found, trying again.");
}
// clean up ram
WiFi.scanDelete();
}
// Check if the slave is already paired with the master.
// If not, pair the slave with master
void manageSlaves()
{
if(slaveCount > 0)
{
for(int i = 0; i < slaveCount; i++)
{
const esp_now_peer_info_t *peer = &slaves[i];
const uint8_t *peer_addr = slaves[i].peer_addr;
Serial.print("Processing: ");
for(int j = 0; j < 6; j++)
{
Serial.print((uint8_t) slaves[i].peer_addr[j], HEX);
if (j != 5)
{
Serial.print(":");
}
}
Serial.print(" Status: ");
// check if the peer exists
bool exists = esp_now_is_peer_exist(peer_addr);
if(exists)
{
// Slave already paired.
Serial.println("Already Paired");
}
else
{
// Slave not paired, attempt pair
esp_err_t addStatus = esp_now_add_peer(peer);
if(addStatus == ESP_OK)
{
// Pair success
Serial.println("Pair success");
}
else if (addStatus == ESP_ERR_ESPNOW_NOT_INIT)
{
// How did we get so far!!
Serial.println("ESPNOW Not Init");
}
else if (addStatus == ESP_ERR_ESPNOW_ARG)
{
Serial.println("Add Peer - Invalid Argument");
}
else if (addStatus == ESP_ERR_ESPNOW_FULL)
{
Serial.println("Peer list full");
}
else if (addStatus == ESP_ERR_ESPNOW_NO_MEM)
{
Serial.println("Out of memory");
}
else if (addStatus == ESP_ERR_ESPNOW_EXIST)
{
Serial.println("Peer Exists");
}
else
{
Serial.println("Not sure what happened");
}
delay(1000);
}
}
}
else
{
// No slave found to process
Serial.println("No Slave found to process");
}
}
// send data
void sendData(uint8_t data)
{
for(int i = 0; i < slaveCount; i++)
{
const uint8_t *peer_addr = slaves[i].peer_addr;
if (i == 0)
{
// print only for first slave
Serial.print("Sending: ");
Serial.println(data);
}
esp_err_t result = esp_now_send(peer_addr, &data, sizeof(data));
Serial.print("Send Status: ");
if (result == ESP_OK) {
Serial.println("Success");
} else if (result == ESP_ERR_ESPNOW_NOT_INIT) {
// How did we get so far!!
Serial.println("ESPNOW not Init.");
} else if (result == ESP_ERR_ESPNOW_ARG) {
Serial.println("Invalid Argument");
} else if (result == ESP_ERR_ESPNOW_INTERNAL) {
Serial.println("Internal Error");
} else if (result == ESP_ERR_ESPNOW_NO_MEM) {
Serial.println("ESP_ERR_ESPNOW_NO_MEM");
} else if (result == ESP_ERR_ESPNOW_NOT_FOUND) {
Serial.println("Peer not found.");
} else {
Serial.println("Not sure what happened");
}
delay(100);
}
}
// callback when data is sent from Master to Slave
void onDataSent(const uint8_t *mac_addr, esp_now_send_status_t status)
{
char macStr[18];
// sendTime = millis();
snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x",
mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]);
Serial.print("Last Packet Sent to: ");
Serial.println(macStr);
Serial.print("Last Packet Send Status: ");
Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail");
}
// callback when data is received from Slave to Master
void onDataRecv(const uint8_t *mac_add, const uint8_t *data, int data_len)
{
char macStr[18];
snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x",
mac_add[0], mac_add[1], mac_add[2], mac_add[3], mac_add[4], mac_add[5]);
Serial.print("Last Packet Recv from: ");
Serial.println(macStr);
Serial.print("Last Packet Recv Data: ");
Serial.println(*data);
Serial.println("");
}```
Out of curiosity I tried your code and I can reproduced what you are facing. But I noticed that if I swap the line irrecv.enableIRIn(); with WiFi.mode(WIFI_MODE_STA); in setup(), the crash stop.
This will cause the sketch to crash
#include <WiFi.h>
#include <IRremote.h>
int IR_Recv = 4;
IRrecv irRecv(IR_Recv);
decode_results results;
void setup()
{
Serial.begin(115200);
irRecv.enableIRIn();
WiFi.mode(WIFI_MODE_STA);
}
void loop() {
}
This will work perfectly without crash
#include <WiFi.h>
#include <IRremote.h>
int IR_Recv = 4;
IRrecv irRecv(IR_Recv);
decode_results results;
void setup()
{
Serial.begin(115200);
WiFi.mode(WIFI_MODE_STA);
irRecv.enableIRIn();
}
void loop() {
}
I couldn't explain why, what irrecv.enableIRIn() does is to setup the interrupt and reset the timer2, but I couldn't see how this affect the WiFi.mode(WIFI_MODE_STA), maybe others could explain why this happen.

Arduino Ethernet Client Server communication problem

This is my code:
#include <Keypad.h>
#include <LiquidCrystal.h>
#include <Ethernet.h>
#include <SPI.h>
bool hands = false;
bool result = true;
char Key;
unsigned int Number=0;
String weight;
String path;
bool alreadyConnected = false; // whether or not the client was connected previously
int cnt=0;
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address
byte ip[] = { 192, 168, 1, 2 }; // ip in lan
byte gateway[] = { 192, 168, 1, 1 }; // internet access via router
byte subnet[] = { 255, 255, 255, 0 }; //subnet mask
LiquidCrystal lcd(35, 34, 33, 32, 31, 30);
EthernetServer server(9639); //server port
EthernetClient client;
char keys[4][4] = {
{'1', '2', '3','A'},
{'4', '5', '6','B'},
{'7', '8', '9','C'},
{'*', '0', '#','D'},
};
byte rowpins[4] = {22, 23, 24, 25};
byte colpins[4] = {26, 27, 28, 29};
Keypad mykeypad = Keypad(makeKeymap(keys), rowpins, colpins, 4, 4);
String readString;
void setup()
{
lcd.begin(20, 4);
Ethernet.begin(mac, ip, gateway, subnet);
if (Ethernet.linkStatus() == LinkOFF) {
lcd.setCursor(0, 0);
lcd.print(" :Error: ");
lcd.setCursor(0, 1);
lcd.print("Ethernet Cable");
lcd.setCursor(0, 2);
lcd.print("Not Connected!");
Serial.println("Ethernet cable is not connected.");
while(true);
}
Serial.begin(19200);
Serial1.begin(19200);
EthernetClient client = server.available();
lcd.setCursor(0, 1);
lcd.print(" Connecting... ");
delay(5000);
if (client.connect(gateway, 9639))
{
client.print("A");
Serial.println("Connecting MilkyWeigh Server...");
}
else
{ lcd.clear();
lcd.setCursor(0, 1);
lcd.print("1.Check LAN Cable");
lcd.setCursor(0, 2);
lcd.print(" --Reset MilkoSol-- ");
while (true);
}
server.begin();
while (true) {
client = server.available(); // wait for a new client:
if (client)
{
while (client.connected())
{
if (client.available())
{
char b = client.read();
if (b == 'B')
{
lcd.setCursor(0, 2);
lcd.print(" Connected! ");
Serial.println("Successfully Connected!");
delay(1500);
hands = true;
b = "";
} //if B comes, handshaking done
} // if client available
} //while client connected
} //if (client)
if (hands == true)
{
lcd.clear();
client.stop();
break;
}
} //while true
lcd.setCursor(0, 0);
lcd.print ("Input Code: ");
lcd.print (Number);
} // void setup
void loop()
{
while (Key == NO_KEY){
Key = mykeypad.getKey();
}
DetectButtons();
if (Key == '4')
{
SaveToServer();
delay(200);
SaveToServer();
}
if (Key == '#')
{
if (Number > 0)
{
GetName();
}
Getweight();
}
Key=NO_KEY;
}
void Getweight(){
while (Serial1.available()>0)
{
weight = Serial1.readStringUntil('\r');
Serial1.flush();
}
Serial.print(weight);
}
void SaveToServer()
{
if (client.connect(gateway, 9639))
{
client.print('#'+String(Number)+','+weight);
//client.stop();
}
else
{ lcd.clear();
lcd.setCursor(0, 2);
lcd.print(" Save Error ");
Serial.println("Try again!");
Number=0;
readString="";
// weight="";
alreadyConnected=false;
return 0;
}
server.begin();
EthernetClient client = server.available(); // Listening for client (i.e. server) response
if (client)
{
if (!alreadyConnected)
{
// clear out the input buffer:
client.flush();
alreadyConnected = true;
}
while (client.connected())
{
if (client.available())
{
if (client.available()>0)
{
char z = client.read();
if (z == 'K')
{
Serial.print("Success: Data Saved!");
lcd.clear();
lcd.setCursor(6, 2);
lcd.print("Success!");
delay(1500);
Number=0;
weight="";
readString="";
DisplayResult();
}
client.flush();
client.stop();
}
}
}
} // if client
}// SaveToServer
void GetName()
{
if (client.connect(gateway, 9639))
{
client.print(Number);
//client.stop();
}
else
{ lcd.clear();
lcd.setCursor(0, 2);
lcd.print(" Connection Failed! ");
Serial.println("Connection Failed!");
Number=0;
readString="";
// weight="";
alreadyConnected=false;
return 0;
}
server.begin();
EthernetClient client = server.available(); // Listening for client (i.e. server) response
if (client)
{
if (!alreadyConnected)
{
// clear out the input buffer:
client.flush();
alreadyConnected = true;
}
while (client.connected())
{
if (client.available())
{
readString="";
while (client.available()>0)
{
//client.readStringUntil('?');
readString = client.readStringUntil('?');
client.flush();
client.stop();
}
}
}
if (readString == "err")
{
lcd.clear();
lcd.setCursor(0, 2);
lcd.print("Not found,Try again!");
Serial.println("Not found,Try again!");
delay(1500);
Number=0;
readString="";
hands = true;
DisplayResult();
}
else
{
lcd.clear();
DisplayResult();
Serial.println(readString);
hands = true;
}
} // if client
}// GetName
void DetectButtons()
{
// path = path + "DetectButtons";
//Serial.println(path);
if (Key == '*') //If cancel Button is pressed
{
Serial.println ("Button Cancel");
Number = 0;
weight = "";
readString="";
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Input Code: ");
lcd.setCursor(0, 1);
lcd.print(" ");
lcd.setCursor(0, 2);
lcd.print(" ");
lcd.setCursor(0, 3);
lcd.print(" ");
}
if (Key == '1') //If Button 1 is pressed
{ Serial.println ("Button 1");
if (Number == 0)
Number = 1;
else
Number = (Number * 10) + 1; //Pressed twice
}
/*
if (Key == '4') //If Button 4 is pressed
{ Serial.println ("Button 4");
if (Number == 0)
Number = 4;
else
Number = (Number * 10) + 4; //Pressed twice
}
*/
if (Key == '7') //If Button 7 is pressed
{ Serial.println ("Button 7");
if (Number == 0)
Number = 7;
else
Number = (Number * 10) + 7; //Pressed twice
}
if (Key == '0')
{ Serial.println ("Button 0"); //Button 0 is Pressed
if (Number == 0)
Number = 0;
else
Number = (Number * 10) + 0; //Pressed twice
}
if (Key == '2') //Button 2 is Pressed
{ Serial.println ("Button 2");
if (Number == 0)
Number = 2;
else
Number = (Number * 10) + 2; //Pressed twice
}
if (Key == '5')
{ Serial.println ("Button 5");
if (Number == 0)
Number = 5;
else
Number = (Number * 10) + 5; //Pressed twice
}
if (Key == '8')
{ Serial.println ("Button 8");
if (Number == 0)
Number = 8;
else
Number = (Number * 10) + 8; //Pressed twice
}
if (Key == '3')
{ Serial.println ("Button 3");
if (Number == 0)
Number = 3;
else
Number = (Number * 10) + 3; //Pressed twice
}
if (Key == '6')
{ Serial.println ("Button 6");
if (Number == 0)
Number = 6;
else
Number = (Number * 10) + 6; //Pressed twice
}
if (Key == '9')
{ Serial.println ("Button 9");
if (Number == 0)
Number = 9;
else
Number = (Number * 10) + 9; //Pressed twice
}
DisplayResult();
} // end of detect buttons function
void DisplayResult()
{
lcd.clear();
lcd.setCursor(0, 0);
lcd.print ("Input Code: ");
lcd.print (Number);
lcd.setCursor(0, 1);
lcd.print (readString);
lcd.setCursor(0, 2);
lcd.print ("Weight :");
lcd.print (weight);
lcd.setCursor(0, 3);
lcd.print ("*=Cncl,#=Wght,A=Save");
}
The problem is when '#' key is pressed first time with input_code =111, client.read somehow miss or skip the response (name) from server and shows blank. But when i press '#' key second time with input_code = 222, it shows previous response (name) from server.
The EthernetClient can be used to connect to remote server as in WebClient example or it is used by the EthernetServer as a peer for remote client as in ChatServer example.
If you use both, use different names. Now your client 'client' is global and clients returned from server are local but with the same name. And you can make the global client variable local too.
The variable alreadyConnected is used with local client and with server's client.
You don't stop the local client.
You have redundant while/if (client.available()) to test the request (server's client).
Why while (client.available() > 0) around readStringUntil('?')?
EthernetServer should by started with begin only once in setup().

arduino gsm shield error 0

I have been trying to send a simple message using an arduino microcontroller and a gsm shield but it keeps getting an error 0.
Here is the code:
int8_t answer;
int onModulePin= 2;
char aux_string[20];
char phone_number[]="*********";
void setup(){
pinMode(onModulePin, OUTPUT);
Serial.begin(115200);
Serial.println("Starting...");
power_on();
delay(3000);
// sets the PIN code
sendATcommand("AT+CPIN=****", "OK", 2000);
delay(3000);
Serial.println("Connecting to the network...");
while( (sendATcommand("AT+CREG?", "+CREG: 0,1", 500) || sendATcommand("AT+CREG?", "+CREG: 0,5", 500)) == 0 );
Serial.print("Setting SMS mode...");
sendATcommand("AT+CMGF=1", "OK", 1000); // sets the SMS mode to text
Serial.println("Sending SMS");
sprintf(aux_string,"AT+CMGS=\"%s\"", phone_number);
answer = sendATcommand(aux_string, ">", 2000); // send the SMS number
if (answer == 1)
{
Serial.println("Test-Arduino-Hello World");
Serial.write(0x1A);
answer = sendATcommand("", "OK", 20000);
if (answer == 1)
{
Serial.print("Sent ");
}
else
{
Serial.print("error ");
}
}
else
{
Serial.print("error ");
Serial.println(answer, DEC);
}
}
void loop(){
}
void power_on(){
uint8_t answer=0;
// checks if the module is started
answer = sendATcommand("AT", "OK", 2000);
if (answer == 0)
{
// power on pulse
digitalWrite(onModulePin,HIGH);
delay(3000);
digitalWrite(onModulePin,LOW);
// waits for an answer from the module
while(answer == 0){ // Send AT every two seconds and wait for the answer
answer = sendATcommand("AT", "OK", 2000);
}
}
}
int8_t sendATcommand(char* ATcommand, char* expected_answer, unsigned int timeout){
uint8_t x=0, answer=0;
char response[100];
unsigned long previous;
memset(response, '\0', 100); // Initialice the string
delay(100);
while( Serial.available() > 0) Serial.read(); // Clean the input buffer
Serial.println(ATcommand); // Send the AT command
x = 0;
previous = millis();
// this loop waits for the answer
do{
if(Serial.available() != 0){ // if there are data in the UART input buffer, reads it and checks for the asnwer
response[x] = Serial.read();
x++;
if (strstr(response, expected_answer) != NULL) // check if the desired answer is in the response of the module
{
answer = 1;
}
}
}while((answer == 0) && ((millis() - previous) < timeout)); // Waits for the asnwer with time out
return answer;
}
char phone_number[]="*********";
In the above code, replace ********* with 9xxxxyyyyy (Sim Number/ Mobile Number)
char phone_number[]="*********";
Then start the Serial Monitor with the mentioned baud rate (115200 as in the above code)

processing arduino connection difficulty

i am trying to send char's from processing to arduino, but arduino only recognizes 2 of them,
the problem is with the '2' char
when i press the 's' key the processing code is sending the '2' char because i can see the arduino rx led lighting but the motor does nothing,
with the '1' or '0' chars i have no problem,
i switched the '2' in the arduino code to correspond to drive_forward and then to drive_reverse, but the one that had '2' char assigned to it did not work in both cases,
as i said the '1'and '0' char are sent and received well
i guess it is something in the arduino code, but i don't know what
arduino code:
int motor1 = 4;
int motor2 = 5;
char val;
// --------------------------------------------------------------- Setup
void setup() {
Serial.begin(9600);
// Setup motors
pinMode(motor1, OUTPUT);
pinMode(motor2, OUTPUT);
}
// ---------------------------------------------------------------- Loop
void loop() {
if (Serial.available()>0)
{ // If data is available to read,
val = Serial.read(); // read it and store it in val
}
if (val == '2'){
drive_forward();
}
if (val == '1'){
drive_reverse();
}
if (val == '0'){
motor_stop();
}
}
// --------------------------------------------------------------------------- Drive
void motor_stop(){
digitalWrite(motor1, LOW);
digitalWrite(motor2, LOW);
}
void drive_forward(){
digitalWrite(motor1, HIGH);
digitalWrite(motor2, LOW);
delay(15);
digitalWrite(motor1, LOW);
digitalWrite(motor2, LOW);
delay(15);
}
void drive_reverse(){
digitalWrite(motor2, HIGH);
digitalWrite(motor1, LOW);
delay(15);
digitalWrite(motor2, LOW);
digitalWrite(motor1, LOW);
delay(15);
}
processing code:
import processing.serial.*;
Serial myPort;
void setup()
{
size(200,200);
myPort = new Serial(this, Serial.list()[2], 9600);
}
void draw() {
}
void keyPressed() {
if (key == 'w' || key == 'W')
{
myPort.write('1');
println("1");}
if (key == 's' || key == 'S')
{
myPort.write('2');
println("2");}
}
void keyReleased() {
myPort.write('0');
println("0");
}
As #tailedmouse said, send data as integer.
Processing code:
//skipped some code
void keyPressed() {
if (key == 'w' || key == 'W') {
myPort.write(1);
}
if (key == 's' || key == 'S') {
myPort.write(2);
println("2");
}
}
void keyReleased() {
myPort.write(0);
println("0");
}
Arduino code:
//skipped some code.
void loop() {
if (Serial.available()>0) {
// If data is available to
read, val = Serial.read();
// read it and store it in val
}
if (val == 2) {
drive_forward();
}
if (val == '1') {
drive_reverse();
}
if (val == '0') {
motor_stop();
}
}

Resources