GSM MQTT+CMT(SMS Reading) - c++
I'm working a code to pubsub over GSM SIM800L and ARDUINO MEGA.
I'm able to workout MQTT fine, using ElementzOnline / SIM800_MQTT code.
I'm now having trouble to use MQTT alongside SMSReading (+CMT) and Call Receiving. I've made a RecSMS() to receive incoming messages, and it works fine as long as TCP Connection is not true, The problem is: Once TCP/MQTT is connected, my RecSMS Function displays no more sms to Serial and calls can not be received
This is Call Receiving, which is handled via RingPing....
void GSM_MQTT::receivecall(){
HangUp=1;
if(MQTT.TCP_Flag==true){disconnect();}
delay(1000);
SIMSerial.write("AT+CGATT=0\n");
delay(1000);
//SIMSerial.write("AT+CIPSHUT\n");
modemStatus=0;
SIMSerial.write("ATA\n");SIMSerial.write(26);Monitor("Incomig Call");
}
void GSM_MQTT::endcall(){if(HangUp==1){HangUp=0;SIMSerial.write("ATH\n");SIMSerial.write(26);Monitor("Call Ended");}}
This is RecSMS():
char inchar4;char inchar3;char inchar2;char inchar1;int times=0;
void RecSMS(char data){
if(times==3){inchar4=data;times++;}
if(times==2){inchar3=data;times++;}
if(times==1){inchar2=data;times++;}
if(times==0){inchar1=data;times++;}
if(times>=4){
inchar1=inchar2;inchar2=inchar3;inchar3=inchar4;inchar4=data;
if((inchar1== '+') && (inchar2== 'C')&&(inchar3== 'M')&&(inchar4== 'T')){RcvdConf = 1;}
if(RcvdConf == 1){
if(data == '\n'){RcvdEnd++;}
if(RcvdEnd == 3){RcvdEnd = 0;}
RcvdMsg[count] = data;
count++;
if(RcvdEnd == 2){RcvdConf = 0;MsgLength = count-2;count= 0;}
if(RcvdConf == 0){
Serial.print("Mobile Number is: ");
for(int x = 4;x < 18;x++){MsgMob[x-4] = RcvdMsg[x];Serial.print(MsgMob[x-4]);}
Serial.println();
Serial.print("Message Text: ");
for(int x = 47; x < MsgLength; x++){MsgTxt[x-47] = RcvdMsg[x];Serial.print(MsgTxt[x-47]);}
Serial.println();
char RcvdMsg[200] = "";int RcvdConf = 0;int count = 0;int RcvdEnd = 0;char MsgMob[15];char MsgTxt[50];int MsgLength = 0;
}
}
}
}
SerialEvent() is called every second...
void serialEvent(){
while(Serial3.available()){
char inChar=(char)Serial3.read();
RecSMS(inChar);//<////////////////////////sms reading
if(MQTT.TCP_Flag==false){
if(MQTT.index<200){MQTT.inputString[MQTT.index++]=inChar;}
if(inChar=='\n'){
MQTT.inputString[MQTT.index]=0;stringComplete=true;Serial.print(MQTT.inputString);
if(strstr(MQTT.inputString,MQTT.reply)!=NULL){
MQTT.GSM_ReplyFlag=1;
if(strstr(MQTT.inputString," INITIAL")!=0){MQTT.GSM_ReplyFlag=2;}
else if(strstr(MQTT.inputString," START")!=0){MQTT.GSM_ReplyFlag=3;}
else if(strstr(MQTT.inputString," IP CONFIG")!=0){_delay_us(10);MQTT.GSM_ReplyFlag=4;}
else if(strstr(MQTT.inputString," GPRSACT")!=0){MQTT.GSM_ReplyFlag=4;}
else if((strstr(MQTT.inputString," STATUS")!=0)||(strstr(MQTT.inputString,"TCP CLOSED")!=0)){MQTT.GSM_ReplyFlag=5;}
else if(strstr(MQTT.inputString," TCP CONNECTING")!=0){MQTT.GSM_ReplyFlag=6;}
else if((strstr(MQTT.inputString," CONNECT OK")!=0)||(strstr(MQTT.inputString,"CONNECT FAIL")!=NULL)||(strstr(MQTT.inputString,"PDP DEACT")!=0)){MQTT.GSM_ReplyFlag=7;}}
else if(strstr(MQTT.inputString,"OK")!=NULL){GSM_Response=1;}
else if(strstr(MQTT.inputString,"ERROR")!=NULL){GSM_Response=2;}
else if(strstr(MQTT.inputString,".")!= NULL){GSM_Response=3;}
else if(strstr(MQTT.inputString,"CONNECT FAIL")!=NULL){GSM_Response=5;}
else if(strstr(MQTT.inputString,"CONNECT")!=NULL){GSM_Response=4;MQTT.TCP_Flag=true;MQTT.AutoConnect();MQTT.pingFlag=true;MQTT.tcpATerrorcount=0;Serial.println("MQTT.TCP_Flag=True");}
else if(strstr(MQTT.inputString,"CLOSED")!=NULL){GSM_Response=4;MQTT.TCP_Flag=false;MQTT.MQTT_Flag=false;Serial.println("TCP_Flag=False");}
MQTT.index=0;MQTT.inputString[0]=0;
}
}else{
uint8_t ReceivedMessageType=(inChar/16) & 0x0F;uint8_t DUP=(inChar & DUP_Mask)/DUP_Mask;
uint8_t QoS=(inChar & QoS_Mask)/QoS_Scale;uint8_t RETAIN=(inChar & RETAIN_Mask);
if((ReceivedMessageType>=CONNECT)&&(ReceivedMessageType<=DISCONNECT)){
bool NextLengthByte=true;MQTT.length=0;MQTT.lengthLocal=0;uint32_t multiplier=1;delay(2);char Cchar=inChar;
while((NextLengthByte==true)&&(MQTT.TCP_Flag==true)){
if(Serial3.available()){
inChar=(char)Serial3.read();/*Serial.println(inChar, DEC);*/
if(((((Cchar & 0xFF)=='C')&&((inChar & 0xFF)=='L'))||(((Cchar & 0xFF)=='+')&&((inChar & 0xFF)=='P')))&&(MQTT.length==0)){
MQTT.index=0;MQTT.inputString[MQTT.index++]=Cchar;MQTT.inputString[MQTT.index++]=inChar;
MQTT.TCP_Flag=false;MQTT.MQTT_Flag=false;MQTT.pingFlag=false;Serial.println("Disconnecting");
Serial.println("MQTT.TCP_Flag=False (ln223)");
}else{
if((inChar&128)==128){MQTT.length+=(inChar&127)*multiplier;multiplier*=128;Serial.println("More");}
else{NextLengthByte=false;MQTT.length+=(inChar&127)*multiplier;multiplier*=128;}
}
}
}
MQTT.lengthLocal=MQTT.length;/*Serial.println(MQTT.length);*/
if(MQTT.TCP_Flag==true){
MQTT.printMessageType(ReceivedMessageType);MQTT.index=0L;uint32_t a=0;
while((MQTT.length-- > 0)&&(Serial3.available())){MQTT.inputString[uint32_t(MQTT.index++)]=(char)Serial3.read();delay(1);}
/*Serial.println(" ");*/
if (ReceivedMessageType==CONNACK){
MQTT.ConnectionAcknowledgement=MQTT.inputString[0]*256+MQTT.inputString[1];
if(MQTT.ConnectionAcknowledgement==0){MQTT.MQTT_Flag=true;MQTT.OnConnect();}
MQTT.printConnectAck(MQTT.ConnectionAcknowledgement); /*MQTT.OnConnect();*/
}else if(ReceivedMessageType==PUBLISH){
uint32_t TopicLength=(MQTT.inputString[0])*256+(MQTT.inputString[1]);Serial.print("Topic: '");MQTT.PublishIndex = 0;
for(uint32_t iter=2;iter<TopicLength+2;iter++){Serial.print(MQTT.inputString[iter]);MQTT.Topic[MQTT.PublishIndex++]=MQTT.inputString[iter];}
MQTT.Topic[MQTT.PublishIndex]=0;Serial.print("' Message: '");
MQTT.TopicLength=MQTT.PublishIndex;MQTT.PublishIndex=0;uint32_t MessageSTART=TopicLength+2UL;int MessageID=0;
if(QoS!=0){MessageSTART+=2;MessageID=MQTT.inputString[TopicLength+2UL]*256+MQTT.inputString[TopicLength+3UL];}
for(uint32_t iter=(MessageSTART);iter<(MQTT.lengthLocal);iter++){Serial.print(MQTT.inputString[iter]);MQTT.Message[MQTT.PublishIndex++]=MQTT.inputString[iter];}
MQTT.Message[MQTT.PublishIndex]=0;Serial.println("'");MQTT.MessageLength=MQTT.PublishIndex;
if(QoS==1){MQTT.publishACK(MessageID);}else if(QoS==2){MQTT.publishREC(MessageID);}
MQTT.OnMessage(MQTT.Topic,MQTT.TopicLength,MQTT.Message,MQTT.MessageLength);MQTT.MessageFlag=true;
}else if(ReceivedMessageType==PUBREC){MQTT.publishREL(0,MQTT.inputString[0]*256+MQTT.inputString[1]);
int MessageID=MQTT.inputString[0]*256+MQTT.inputString[1];
}else if(ReceivedMessageType==PUBREL){MQTT.publishCOMP(MQTT.inputString[0]*256+MQTT.inputString[1]);
int MessageID=MQTT.inputString[0]*256+MQTT.inputString[1];
}else if((ReceivedMessageType==PUBACK)||(ReceivedMessageType==PUBCOMP)||(ReceivedMessageType==SUBACK)||(ReceivedMessageType==UNSUBACK)){
int MessageID=MQTT.inputString[0]*256+MQTT.inputString[1];
}else if(ReceivedMessageType==PINGREQ){
MQTT.TCP_Flag=false;MQTT.pingFlag=false;MQTT.sendATreply("AT+CIPSHUT\r\n",".",4000);MQTT.modemStatus=0;
Serial.println("Disconnecting");Serial.println("MQTT.TCP_Flag=False (ln261)");
}
}
}else if((inChar==13)||(inChar==10)){Serial.print("inChar=13||10");}else{Serial.print("Received: Unknown Message Type: ");Serial.println(inChar);}
}
}
}
My Code is published at pedromancuso/GSM_MQTT.
Suggestions?
Related
3x Arduino + ESP32 with ESP-NOW
The configuration on "machine" looks like this: Computer with custom app WPF C#, have connected ESP32-sender. On other side of room there is ESP32 as recaiver that have connected to it 3 arduino due, that controls a lot of stepper motors. My problem is, that if I send a single command all works great. Directly on other side it executes. The problem starts when there is a lot of commands to send. ESP32 starts to makes Delivery fail status and after that moment all further commands are lost. That's the code of Master-ESP connected to PC. Which arduino to send is decide by one of the symbols on begin of message "!,#,#" #include <esp_now.h> #include <WiFi.h> #include <Wire.h> uint8_t broadcastAddress[] = {0x94, 0xB9, 0x7E, 0xD0, 0x93, 0x64}; String inMess; typedef struct Message { char a[100]; } Message; // Variable to store if sending data was successful String success; Message message; Message send_message; esp_now_peer_info_t peerInfo; char incoming; String full = ""; bool text_done = false; bool sended = false; // Callback when data is sent void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) { //Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success*" : "Delivery Fail*"); if (status ==0){ success = "Delivery Success :)"; text_done = false; full = ""; sended = false; } else{ success = "Delivery Fail :("; delay(10); sended = false; Serial.println(success); } } // Callback when data is received void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) { memcpy(&message, incomingData, sizeof(message)); Serial.println(message.a); } void setup() { // Init Serial Monitor Serial.begin(115200); // Set device as a Wi-Fi Station WiFi.mode(WIFI_STA); Serial.println(WiFi.macAddress()); // Init ESP-NOW if (esp_now_init() != ESP_OK) { Serial.println("Error initializing ESP-NOW"); return; } esp_now_register_send_cb(OnDataSent); // Register peer memcpy(peerInfo.peer_addr, broadcastAddress, 6); peerInfo.channel = 0; peerInfo.encrypt = false; // Add peer if (esp_now_add_peer(&peerInfo) != ESP_OK){ Serial.println("Failed to add peer"); return; } esp_now_register_recv_cb(OnDataRecv); } void loop() { if(Serial.available() > 0 && !text_done){ incoming = Serial.read(); if(incoming == '\n'){ text_done = true; full.trim(); full.toUpperCase(); } if(text_done == false){ full += incoming; } } if(text_done){ if(full[0] != '!' && full[0] != '#' && full[0] != '#'){ //check if text is worth sending to other esp text_done = false; full = ""; } } if(text_done){ if(!sended){ full.toCharArray(send_message.a,sizeof(send_message)); esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &send_message, sizeof(send_message)); if (result == ESP_OK) { //Serial.println("Sent success*"); sended = true; } else { Serial.println("Error sending*"); delay(10); } } } } That's the code of recaiver ESP #include <esp_now.h> #include <WiFi.h> #include <SoftwareSerial.h> #include <Wire.h> SoftwareSerial worker; SoftwareSerial tool; //Serial2 is Table, software serials are others uint8_t broadcastAddress[] = {0x7C, 0x9E, 0xBD, 0x4B, 0x47, 0xA4}; String outMess; String outMessTable; String outMessTool; String inMess; typedef struct Message { char a[100]; } Message; String success; Message message; Message send_message; bool sended = true; String again_message = ""; esp_now_peer_info_t peerInfo; void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) { //Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success" : "Delivery Fail"); if (status == 0) { success = "Delivery Success :)"; sended = true; again_message = ""; } else { success = "Delivery Fail :("; sended = false; delay(5); } } void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) { memcpy(&message, incomingData, sizeof(message)); Serial.println(message.a); sendTo((String)message.a); } void setup() { // Init Serial Monitor Serial.begin(115200); Serial2.begin(115200, SERIAL_8N1, 16, 17); //rx tx worker.begin(57600, SWSERIAL_8N1, 25, 26, false); if (!worker) { Serial.println("Invalid SoftwareSerial pin configuration, check config"); while (1) { delay (1000); } } //rx tx tool.begin(57600, SWSERIAL_8N1, 32, 33, false); if (!tool) { Serial.println("Invalid SoftwareSerial pin configuration, check config"); while (1) { delay (1000); } } // Set device as a Wi-Fi Station WiFi.mode(WIFI_STA); Serial.println(WiFi.macAddress()); // Init ESP-NOW if (esp_now_init() != ESP_OK) { Serial.println("Error initializing ESP-NOW"); return; } // Once ESPNow is successfully Init, we will register for Send CB to // get the status of Trasnmitted packet esp_now_register_send_cb(OnDataSent); // Register peer memcpy(peerInfo.peer_addr, broadcastAddress, 6); peerInfo.channel = 0; peerInfo.encrypt = false; // Add peer if (esp_now_add_peer(&peerInfo) != ESP_OK) { Serial.println("Failed to add peer"); return; } // Register for a callback function that will be called when data is received esp_now_register_recv_cb(OnDataRecv); } void loop() { // Set values to send if(sended){ if (worker.available() > 0) {//! char t = worker.read(); if(t == '\n'){ outMess.trim(); sendToEsp(outMess,"!"); outMess = ""; } else{ outMess += t; } } }else{ if(again_message.length()>0){ delay(10); sendToEsp(again_message.substring(1),again_message.substring(0,1)); }else{ sended = true; } } if(sended){ if (tool.available() > 0) {//# char t = tool.read(); if(t == '\n'){ outMessTool.trim(); sendToEsp(outMessTool,"#"); outMessTool = ""; } else{ outMessTool += t; } } }else{ if(again_message.length()>0){ delay(10); sendToEsp(again_message.substring(1),again_message.substring(0,1)); }else{ sended = true; } } if(sended){ if (Serial2.available() > 0) { //# char t = Serial2.read(); if(t == '\n'){ outMessTable.trim(); sendToEsp(outMessTable,"#"); outMessTable = ""; }else{ outMessTable += t; } } }else{ if(again_message.length()>0){ delay(10); sendToEsp(again_message.substring(1),again_message.substring(0,1)); }else{ sended = true; } } if(Serial.available() > 0){ outMess = Serial.readStringUntil('\n'); //read command from pc outMess.trim(); // remove uneccesery spaces sendTo(outMess); } } void sendToEsp(String text, String which){ String mess = which + text; again_message = mess; mess.toCharArray(send_message.a,sizeof(send_message)); esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &send_message, sizeof(send_message)); if (result == ESP_OK) { // Serial.println("Sent with success"); } else { Serial.println("Error sending the data"); sended = true; again_message = ""; } } void sendTo(String outMess){ Serial.print("="); Serial.print(outMess); if(outMess[0] == '!'){ //worker worker.enableTx(true); worker.println(outMess.substring(1)); worker.enableTx(false); Serial.println("send to worker"); } if(outMess[0] == '#') {//table Serial2.println(outMess.substring(1)); Serial.println("send to table"); } if(outMess[0] == '#'){ //tool tool.enableTx(true); tool.println(outMess.substring(1)); tool.enableTx(false); Serial.println("send to tool"); } } If I send one message with a delay of writing next one by hand it works great. If the message is sended via c# very fast, esp32 is handling first few of them then losing on sending or recaiving, sometimes both of esp32 sometimes only one. How could I prevent that to make stable connection ?
PubSubClient ESP32 disconnected while receive message
I create a project to receive message from MQTT. My full code is here https://github.com/kamshory/OTP-Mini/blob/main/Server/Server.ino WiFiClient espClient; PubSubClient client(espClient); void setup() { char * mqttServer = "192.168.1.3"; client.setServer(mqttServer, 1883); client.setCallback(mqttCallback); } void mqttCallback(const char* topic, byte* payload, unsigned int length) { Serial.print("Message arrived on topic: "); Serial.print(topic); Serial.print("Message: "); char * mqttTopic = "sms"; String messageTemp; for (int i = 0; i < length; i++) { Serial.print((char)payload[i]); messageTemp += (char)payload[i]; } Serial.println(); // Feel free to add more if statements to control more GPIOs with MQTT // If a message is received on the topic esp32/output, you check if the message is either "on" or "off". // Changes the output state according to the message if (String(topic) == String(mqttTopic)) { } } void mqttReconnect() { Serial.print("WiFi status = "); Serial.println(WiFi.status()); char * clientId = "php"; char * mqttUsername = "user"; char * mqttPassword = "pass"; char * mqttTopic = "sms"; // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection "); // Attempt to connect if (client.connect(clientId, mqttUsername, mqttPassword)) { Serial.println("connected"); // Subscribe boolean sub = client.subscribe("sms"); Serial.println(sub); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } } When ESP32 publish a message in a topic, the message is received by subscriber (I create the subscriber with Java). But when it try to receive the message with callback, the client is disconnected. I try to debug with edit library on file PubSubClient.cpp boolean PubSubClient::loop() { if (connected()) { unsigned long t = millis(); if ((t - lastInActivity > MQTT_KEEPALIVE*1000UL) || (t - lastOutActivity > MQTT_KEEPALIVE*1000UL)) { if (pingOutstanding) { this->_state = MQTT_CONNECTION_TIMEOUT; _client->stop(); return false; } else { buffer[0] = MQTTPINGREQ; buffer[1] = 0; _client->write(buffer,2); lastOutActivity = t; lastInActivity = t; pingOutstanding = true; } } if (_client->available()) { uint8_t llen; uint16_t len = readPacket(&llen); uint16_t msgId = 0; uint8_t *payload; if (len > 0) { lastInActivity = t; uint8_t type = buffer[0]&0xF0; if (type == MQTTPUBLISH) { if (callback) { uint16_t tl = (buffer[llen+1]<<8)+buffer[llen+2]; /* topic length in bytes */ memmove(buffer+llen+2,buffer+llen+3,tl); /* move topic inside buffer 1 byte to front */ buffer[llen+2+tl] = 0; /* end the topic as a 'C' string with \x00 */ char *topic = (char*) buffer+llen+2; // msgId only present for QOS>0 if ((buffer[0]&0x06) == MQTTQOS1) { msgId = (buffer[llen+3+tl]<<8)+buffer[llen+3+tl+1]; payload = buffer+llen+3+tl+2; callback(topic,payload,len-llen-3-tl-2); buffer[0] = MQTTPUBACK; buffer[1] = 2; buffer[2] = (msgId >> 8); buffer[3] = (msgId & 0xFF); _client->write(buffer,4); lastOutActivity = t; } else { payload = buffer+llen+3+tl; callback(topic,payload,len-llen-3-tl); } } } else if (type == MQTTPINGREQ) { buffer[0] = MQTTPINGRESP; buffer[1] = 0; _client->write(buffer,2); } else if (type == MQTTPINGRESP) { pingOutstanding = false; } } else if (!connected()) { // readPacket has closed the connection return false; } } return true; } return false; } The type value is 208 which is MQTTPINGRESP not 48 which is MQTTPUBLISH. So, where is the problem? Is my library or my code? I download library from https://www.arduino.cc/reference/en/libraries/pubsubclient/
Arduino compiler failing with error code - invalid types 'int[int]' for array subscript
Quite a bit of untested code but the only thing really concerning me at the moment is my DISPLAY variable. I don't see how it is much different than my FONT array (which works fine) yet DISPLAY is the one that gets 'invalid types 'int[int]' for array subscript' I should be able to index an array of integers with integers (at least I have been with FONT). #include <WiFiNINA.h> #include <NTPClient.h> #include <WiFiUdp.h> #include "font.h" const int PIXEL_WIDTH = 30; const int PIXEL_HEIGHT = 5; int DISPLAY[PIXEL_HEIGHT][PIXEL_WIDTH] = {}; bool MILI_TIME = false; String FORMATTING[2] = {"LONGS","SHORTH:LONGM"}; char ssid[] = "REMOVED"; // your network SSID (name) between the " " char pass[] = "REMOVED"; // your network password between the " " int keyIndex = 0; // your network key Index number (needed only for WEP) int status = WL_IDLE_STATUS; // connection status WiFiServer server(80); // server socket WiFiClient client = server.available(); WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP); int ledPin = LED_BUILTIN; void setup() { Serial.begin(9600); pinMode(ledPin, OUTPUT); while (!Serial); // dont do anything until there is a serial connection enable_WiFi(); connect_WiFi(); server.begin(); printWifiStatus(); timeClient.begin(); timeClient.setTimeOffset(-14400); } void loop() { timeClient.update(); client = server.available(); if (client) { printWEB(); } preRender(); } void preRender(){ String FILLED_FORMATTING[2] = FORMATTING; for(int i=0;i<2;i++){ FILLED_FORMATTING[i].replace("LONGH",leadWithZero(timeHours())); FILLED_FORMATTING[i].replace("LONGM",leadWithZero(timeMinutes())); FILLED_FORMATTING[i].replace("LONGS",leadWithZero(timeSeconds())); FILLED_FORMATTING[i].replace("SHORTH",timeHours()); FILLED_FORMATTING[i].replace("SHORTM",timeMinutes()); FILLED_FORMATTING[i].replace("SHORTS",timeSeconds()); } int x = 0; for(int i=0;i<FILLED_FORMATTING[0].length();i++){ int c_ID = charID(FILLED_FORMATTING[0][i]); if(c_ID < 38){ for(int j=0;j<5;j++){ DISPLAY[j][x] = FONT[c_ID][j][0]; x += 1; DISPLAY[j][x] = FONT[c_ID][j][1]; x += 1; DISPLAY[j][x] = FONT[c_ID][j][2]; x += 1; if(i != FILLED_FORMATTING[0].length()){ DISPLAY[j][x] = 0; x += 1; } } } } x = PIXEL_WIDTH-1; for(int i=FILLED_FORMATTING[1].length()-1;i>=0;i--){ int c_ID = charID(FILLED_FORMATTING[1][i]); if(c_ID < 38){ for(int j=0;j<5;j++){ DISPLAY[j][x] = FONT[c_ID][j][0]; x -= 1; DISPLAY[j][x] = FONT[c_ID][j][1]; x -= 1; DISPLAY[j][x] = FONT[c_ID][j][2]; x -= 1; if(i != 0){ DISPLAY[j][x] = 0; //<----------- compiler error here, and ofc all instances above x -= 1; } } } } } int charID(char c){ for(int i=0;i<FONT_ID.length();i++){ if(FONT_ID[i] == c){ return i; } } return 40; } String timeHours(){ if(MILI_TIME){ return String(timeClient.getHours()); } else{ return convFromMili(timeClient.getHours()); } } String timeMinutes(){ return String(timeClient.getMinutes()); } String timeSeconds(){ return String(timeClient.getSeconds()); } String leadWithZero(String t){ if(t.length() < 2){ t = "0"+t; return t; } } String convFromMili(int t){ if(t > 12){ t -= 12; }else if(t == 0){ t += 12; } String ts = String(t); return ts; } void printWifiStatus() { // print the SSID of the network you're attached to: Serial.print("SSID: "); Serial.println(WiFi.SSID()); // print your board's IP address: IPAddress ip = WiFi.localIP(); Serial.print("IP Address: "); Serial.println(ip); // print the received signal strength: long rssi = WiFi.RSSI(); Serial.print("signal strength (RSSI):"); Serial.print(rssi); Serial.println(" dBm"); Serial.print("To see this page in action, open a browser to http://"); Serial.println(ip); } void enable_WiFi() { // check for the WiFi module: if (WiFi.status() == WL_NO_MODULE) { Serial.println("Communication with WiFi module failed!"); // don't continue while (true); } String fv = WiFi.firmwareVersion(); if (fv < "1.0.0") { Serial.println("Please upgrade the firmware"); } } void connect_WiFi() { while (status != WL_CONNECTED) { Serial.print("Attempting to connect to SSID: "); Serial.println(ssid); status = WiFi.begin(ssid, pass); delay(10000); } } void printWEB() { if (client) { // if you get a client, Serial.println("new client"); // print a message out the serial port String currentLine = ""; // make a String to hold incoming data from the client while (client.connected()) { // loop while the client's connected if (client.available()) { // if there's bytes to read from the client, char c = client.read(); // read a byte, then Serial.write(c); // print it out the serial monitor if (c == '\n') { // if the byte is a newline character // if the current line is blank, you got two newline characters in a row. // that's the end of the client HTTP request, so send a response: if (currentLine.length() == 0) { // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) // and a content-type so the client knows what's coming, then a blank line: client.println("HTTP/1.1 200 OK"); client.println("Content-type:text/html"); client.println(); //create the buttons client.print(WiFi.getTime()); client.print("<br>"); client.print(timeClient.getEpochTime()); client.print("<br>"); client.print(timeClient.getFormattedTime()); client.print("<br>"); client.print(timeClient.getDay()); client.print("<br>"); client.print(timeClient.getHours()); client.print("<br>"); client.print(timeClient.getMinutes()); client.print("<br>"); client.print(timeClient.getSeconds()); client.print("<br>"); client.print("<div style=\"display:block;padding-left:calc(50% - 150px);margin-bottom:50px\"><div style=\"background-color:#e3e3e3;width:300px;height:120px;font-size:50px;text-align:center;padding-top:50px\">ON</div></div>"); client.print("<div style=\"display:block;padding-left:calc(50% - 150px)\"><div style=\"background-color:#e3e3e3;width:300px;height:120px;font-size:50px;text-align:center;padding-top:50px\">OFF</div></div>"); // The HTTP response ends with another blank line: client.println(); // break out of the while loop: break; } else { // if you got a newline, then clear currentLine: currentLine = ""; } } else if (c != '\r') { // if you got anything else but a carriage return character, currentLine += c; // add it to the end of the currentLine } if (currentLine.endsWith("GET /H")) { digitalWrite(ledPin, HIGH); } if (currentLine.endsWith("GET /L")) { digitalWrite(ledPin, LOW); } if (currentLine.endsWith("%VAL")) { // Trim 'GET /' and '%VAL' currentLine.remove(0,5); currentLine.remove(currentLine.indexOf("%"),4); Serial.println(currentLine); Serial.println(); } } } // close the connection: client.stop(); Serial.println("client disconnected"); } } font.h: int FONT[37][5][3] = {{{1,1,1},{1,0,1},{1,0,1},{1,0,1},{1,1,1},},{{1,1,0},{0,1,0},{0,1,0},{0,1,0},{1,1,1},},{{1,1,1},{0,0,1},{1,1,1},{1,0,0},{1,1,1},},{{1,1,1},{0,0,1},{1,1,1},{0,0,1},{1,1,1},},{{1,0,1},{1,0,1},{1,1,1},{0,0,1},{0,0,1},},{{1,1,1},{1,0,0},{1,1,1},{0,0,1},{1,1,1},},{{1,1,1},{1,0,0},{1,1,1},{1,0,1},{1,1,1},},{{1,1,1},{0,0,1},{0,0,1},{0,0,1},{0,0,1},},{{1,1,1},{1,0,1},{1,1,1},{1,0,1},{1,1,1},},{{1,1,1},{1,0,1},{1,1,1},{0,0,1},{1,1,1},},{{1,1,1},{1,0,1},{1,1,1},{1,0,1},{1,0,1},},{{1,1,0},{1,0,1},{1,1,0},{1,0,1},{1,1,0},},{{1,1,1},{1,0,0},{1,0,0},{1,0,0},{1,1,1},},{{1,1,0},{1,0,1},{1,0,1},{1,0,1},{1,1,0},},{{1,1,1},{1,0,0},{1,1,1},{1,0,0},{1,1,1},},{{1,1,1},{1,0,0},{1,1,1},{1,0,0},{1,0,0},},{{1,1,1},{1,0,0},{1,0,1},{1,0,1},{1,1,1},},{{1,0,1},{1,0,1},{1,1,1},{1,0,1},{1,0,1},},{{1,1,1},{0,1,0},{0,1,0},{0,1,0},{1,1,1},},{{0,0,1},{0,0,1},{0,0,1},{1,0,1},{1,1,1},},{{1,0,1},{1,0,1},{1,1,0},{1,0,1},{1,0,1},},{{1,0,0},{1,0,0},{1,0,0},{1,0,0},{1,1,1},},{{1,1,1},{1,1,1},{1,0,1},{1,0,1},{1,0,1},},{{1,1,0},{1,0,1},{1,0,1},{1,0,1},{1,0,1},},{{1,1,1},{1,0,1},{1,0,1},{1,0,1},{1,1,1},},{{1,1,1},{1,0,1},{1,1,1},{1,0,0},{1,0,0},},{{1,1,1},{1,0,1},{1,0,1},{1,1,0},{0,0,1},},{{1,1,1},{1,0,1},{1,1,0},{1,0,1},{1,0,1},},{{0,1,1},{1,0,0},{0,1,0},{0,0,1},{1,1,0},},{{1,1,1},{0,1,0},{0,1,0},{0,1,0},{0,1,0},},{{1,0,1},{1,0,1},{1,0,1},{1,0,1},{1,1,1},},{{1,0,1},{1,0,1},{1,0,1},{0,1,0},{0,1,0},},{{1,0,1},{1,0,1},{1,0,1},{1,1,1},{1,1,1},},{{1,0,1},{1,0,1},{0,1,0},{1,0,1},{1,0,1},},{{1,0,1},{1,0,1},{1,1,1},{0,0,1},{1,1,1},},{{1,1,1},{0,0,1},{0,1,0},{1,0,0},{1,1,1},},{{0,0,0},{0,1,0},{0,0,0},{0,1,0},{0,0,0}}}; String FONT_ID = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ:"; did check - int D[5][30]; void setup() { } void loop() { D[0][0] = 0; } and of course its fine, so I'm just wondering where I went wrong in the mess above? and yes there's a good bit of mess/debugging stuff
Simple solution... don't use DISPLAY as a variable it seems. Changing to DISPLAY_ fixed it, figured the variable was defined as a normal integer somewhere... just not in my code.
SIM800L + Arduino TCP disconnect issue
Okay so I am currently using an arduino-uno to send AT commands to a SIM800l module. I am running a basic TCP socket server on my computer and the SIM800L is initially able to connect to it fine and send a message. After a seemingly random period of time on my serial monitor "NUL" is then displayed at which I am unable to send messages. (So it is working initially however it seems to suddenly just stop mid process) bool connectionProcedure() { bool result = false; if(sendATcommand("AT+CIPSHUT", "SHUT OK", 200) == 1) { Serial.println("Proceed: AT+CIPMUX=0"); if(sendATcommand("AT+CIPMUX=0", "OK", 1000) == 1 ) { Serial.println("Proceed: AT+CGATT=1"); if(sendATcommand("AT+CGATT=1", "OK", 1000) == 1 ) { Serial.println("Proceed: AT+CSTT=\"gifgaff.com\",\"gifgaff\""); if(sendATcommand("AT+CSTT=\"gifgaff.com\",\"gifgaff\"", "OK", 1000) == 1 ) { Serial.println("Proceed: AT+CIICR"); if(sendATcommand("AT+CIICR", "OK", 60000) == 1 ) { Serial.println("Proceed: AT+CIFSR"); if(sendATcommand("AT+CIFSR", ".", 5000) == 1 ) { Serial.println("Process Success!"); result = true; } else { Serial.println("Error: AT+CIFSR"); } } else { Serial.println("Error: AT+CIICR"); } } else { Serial.println("Error: AT+CSTT=\"gifgaff.com\",\"gifgaff\""); } } else { Serial.println("Error: AT+CGATT=1"); } } else { Serial.println("Error: AT+CIPMUX=0"); } } else { Serial.println("Error: CIPSHUT"); } return result; } void awaitGSMConnection() { while( sendATcommand2("AT+CREG?", "+CREG: 0,1", "+CREG: 0,5", 1000) == 0 ); } void initTCPConnection() { unsigned long previous; unsigned int timeout = 10000; Serial.println("Starting TCP Connection!"); if(sendATcommand("AT+CIPSTART=\"TCP\"," + tcpIp + "," + tcpPort, "OK", 10000) == 1) { Serial.println("Connection Success: Checking for stable connection before handshake!"); String expected = "CLOSED"; uint8_t x=0, answer=0; char response[100]; memset(response, '\0', 100); while( mySerial.available() > 0) mySerial.read(); x = 0; previous = millis(); // Loop waits for the response from SIM800L do { if(mySerial.available() != 0) { response[x] = mySerial.read(); x++; // check if the desired answer 1 is in the response of the module if (strstr(response, expected.c_str()) != NULL) { answer = 1; } } } while((answer == 0) && ((millis() - previous) < timeout)); if(answer == 0) { Serial.println("No Apparent ISSUE sending handshake!"); if(sendATcommand("AT+CIPSEND", ">", 4000) == 1) { Serial.println("SEND-HANDSHAKE"); sendMessage("Handshake"); //sendATcommand("AT+CIPCLOSE","OK",2000); } else { Serial.println("Error: AT+CIPSEND"); } } else { Serial.println("Connection test failed: Attempting to RECONNECT!"); } } else { Serial.println("Connection Error!"); } } Serial Monitor - Output Here is the "NUL" I am talking about, this seems to appear completely randomly sometime during the connection. Random messages being sent from me from the server and being received. No Apparent ISSUE sending handshake! AT+CIPSEND > SEND-HANDSHAKE Handshake␚ SEND OK HELLO AWESOME COOL INSANE STILL WORKING!!!! ␀ Thanks in advance!
Verification code doesn't work in Arduino
I am new to Arduino and I'm trying to make a program that receives IR codes from a TV remote, uses them as a 4 number pass code lighting up a LED as you press each button. And then comparing the code to a hard-coded one. In this case 1234. I made a function to verify that the value entered is equal to the pass. If so, light up a green LED and else, light up a red one. However, even if I input the correct code, only the red led lights up. Here is my whole code as I'm not sure which part of it is the one causing problems: const int pass[4] = {1, 2, 3, 4}; int value[4] = {}; int digitNum = 0; int input; void loop() { value[digitNum] = input; //where input is a number between 0 and 9 digitNum++; if(digitNum == 1){ lightFirstLed(); } else if(digitNum == 2){ lightSecondLed(); } else if(digitNum == 3){ lightThirdLed(); } else if(digitNum == 4){ lightFourthLed(); verify(); } } void verify() { bool falseCharacter = false; for(int i = 0; i <= 4; i++){ if(value[i] != pass[i]){ falseCharacter = true; } } if(!falseCharacter){ lightGreenLed(); } else{ lightRedLed(); } } Functions in the form of light*Led actually do what they're supposed to do. I tried changing the verify function around, that ended up making the green LED the one that always shone. I've been doing this for hours and I'm starting to feel disparate. I would really appreciate any help. And please tell me if anything I'm doing does not comply with best practices even if it's out of the scope of this question. For full code and design, here's a link to autodesk's simulator: https://www.tinkercad.com/things/0keqmlhVqNp-mighty-leelo/editel?tenant=circuits?sharecode=vVUD2_4774Lj4PYXh6doFcOqWUMY2URIfW8VXGxutRE= EDIT: Now reset doesn't work
Your for loop in verify is accessing outside the array: const int pass[4] = {1, 2, 3, 4}; int value[4] = {}; for(int i = 0; i <= 4; i++){ if(value[i] != pass[i]){ falseCharacter = true; } } Change i <= 4 to i < 4. Also, when falseCharacter is set to true, break from the loop: for(int i = 0; i < 4; i++) { if(value[i] != pass[i]) { falseCharacter = true; break; } } Update You need an else statement in loop: void loop(void) { if(irrecv.decode(&results)) { if (results.value == powBtn) { reset(); } else if (results.value == zeroBtn) { input = 0; } else if (results.value == oneBtn) { input = 1; } else if (results.value == twoBtn) { input = 2; } else if (results.value == threeBtn) { input = 3; } else if (results.value == fourBtn) { input = 4; } else if (results.value == fiveBtn) { input = 5; } else if (results.value == sixBtn) { input = 6; } else if (results.value == sevenBtn) { input = 7; } else if (results.value == eightBtn) { input = 8; } else if (results.value == nineBtn) { input = 9; } else { return; /*** !!! Unrecognized Value !!! ***/ } value[digitNum] = input; digitNum++; if(digitNum == 1) { digitalWrite(LED1, HIGH); } else if(digitNum == 2) { digitalWrite(LED2, HIGH); } else if(digitNum == 3) { digitalWrite(LED3, HIGH); } else if(digitNum == 4) { digitalWrite(LED4, HIGH); verify(); } else { if (results.value == powBtn) { reset(); } } // Receive the next value irrecv.resume(); } }