Arduino connection failed loop after random period of time
up vote
3
down vote
favorite
I have recently started working with arduino and coding in C and have stumbled upon an issue.
Everything is working as it should be :
Read NFC tag > send POST to Laravel API > Recieve body response to
display on LCD
However the program is very inconsistent meaning that after an unknown period of time (this is a random period of time) the program returns a connection failed as shown in the monitor returns.
After this connection failed the program will not return back to it's connection and will keep returning connection failed until you restart the program.
I myself am not able to solve this after hours of googling, and therefor I am asking assistance from you guys.
(Do not give me plain code as an answer, but give me explanation on the side as I am learning and want to learn from this.)
Hardware:
Arduino MKR1000
Adafruit PN532 NFC/RFID Controller Shield (SPI)
Monitor returns:
Found chip PN532
Firmware ver. 1.6
Waiting for an ISO14443A card/n
Attempting to connect to SSID: ****
Connected to wifi
SSID: ****
IP Address: ****
signal strength (RSSI):-66 dBm
Starting connection to server...
================= START PROGRAM =======================
Found a card!
UID Length: 4 bytes
UID Value HEX: 67D667E
UID Value Decimal: 6125102126
{"Druppel": "6125102126"}
Connected!
Response:
Tom
Welcome
Succesfull sign in
Found a card!
UID Length: 4 bytes
UID Value HEX: C9DDCA35
UID Value Decimal: 20122120253
{"Druppel": "20122120253"}
Connection failed
Code
#include <SPI.h>
#include <WiFi101.h>
#include <Wire.h>
#include <LiquidCrystal.h>
#include <ArduinoJson.h>
#include <Adafruit_PN532.h>
#define PN532_SCK (9)
#define PN532_MOSI (8)
#define PN532_SS (6)
#define PN532_MISO (10)
#define PN532_IRQ (2)
#define PN532_RESET (7)
#define TIMEOUT 500
Adafruit_PN532 nfc(PN532_SCK, PN532_MISO, PN532_MOSI, PN532_SS);
const int rs = 12, en = 11, d4 = 2, d5 = 3, d6 = 4, d7 = 5;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
const int ledPin = 1;
const int errorLedPin = 13;
const int buzzerPin = 0;
int sensorPin = 0;
char SSID_NAME = "****";
char SSID_PASS = "****";
WiFiClient client;
int status = WL_IDLE_STATUS;
int keyIndex = 0;
char SERVER = "****.*****.nl";
char TOKEN = "******************";
char API = "********";
void printWiFiStatus() {
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
lcd.setCursor(0, 0);
lcd.print("SSID: ");
lcd.print(WiFi.SSID());
lcd.setCursor(0, 2);
lcd.print("IP: ");
lcd.print(WiFi.localIP());
}
void setup() {
Serial.begin(9600);
Serial.println("Serial ready");
analogWrite(A3, 0);
lcd.begin(16, 2);
pinMode(ledPin, OUTPUT);
pinMode(errorLedPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
tone(buzzerPin, 60);
nfc.begin();
uint32_t versiondata = nfc.getFirmwareVersion();
if (! versiondata) {
Serial.print("Didn't find PN53x board");
while (1);
}
Serial.print("Found chip PN5");Serial.println((versiondata>>24) & 0xFF, HEX);
Serial.print("Firmware ver. ");Serial.print((versiondata>>16) & 0xFF, DEC);Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);
nfc.setPassiveActivationRetries(0xFF);
nfc.SAMConfig();
Serial.print("Waiting for an ISO14443A card"); Serial.println("/n");
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
while (true);
}
noTone(buzzerPin);
tone(buzzerPin, 50);
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(SSID_NAME);
status = WiFi.begin(SSID_NAME, SSID_PASS);
delay(100);
}
Serial.println("Connected to wifi");
printWiFiStatus();
Serial.println("nStarting connection to server...");
Serial.println("n================= START PROGRAM =======================");
noTone(buzzerPin);
}
void loop() {
digitalWrite(errorLedPin, LOW);
boolean success;
uint8_t uid = { 0, 0, 0, 0, 0, 0, 0 };
uint8_t uidLength;
success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, &uid[0], &uidLength);
if (success) {
lcd.clear();
Serial.println("");
Serial.print("Found a card!");
Serial.println("");
Serial.print("UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
Serial.print("UID Value HEX: ");
String data;
for (uint8_t i=0; i < uidLength; i++)
{
Serial.print(uid[i], HEX);
data = String(data + uid[i]);
}
Serial.println("");
Serial.print("UID Value Decimal: ");
Serial.print(data);
Serial.println("");
lcd.print(data);
delay(100);
digitalWrite(ledPin, HIGH);
tone(buzzerPin, 50);
String PostData = "{"Druppel": "";
PostData = String(PostData + data);
PostData = String(PostData + ""}");
int PostDataLength = PostData.length() + 1;
delay(100);
noTone(buzzerPin);
char char_array[PostDataLength];
PostData.toCharArray(char_array, PostDataLength);
Serial.println(PostData);
delay(500);
if(!client.connect(SERVER, 80)) {
Serial.println(F("Connection failed"));
digitalWrite(errorLedPin, HIGH);
return;
}
Serial.println(F("Connected!"));
client.println("POST /api/******?api_token=****************** HTTP/1.1");
client.println("Host: ****.*****.nl");
client.println("Cache-Control: no-cache");
client.println("Content-Type: application/json");
client.print("Content-Length: ");
client.println(PostDataLength);
client.println();
client.println(PostData);
client.println(F("Connection: close"));
if (client.println() == 0) {
Serial.println(F("Failed to send request"));
return;
}
char status[32] = {0};
client.readBytesUntil('r', status, sizeof(status));
if (strcmp(status, "HTTP/1.1 200 OK") != 0) {
Serial.print(F("Unexpected response: "));
Serial.println(status);
return;
}
char endOfHeaders = "rnrn";
if (!client.find(endOfHeaders)) {
Serial.println(F("Invalid response"));
return;
}
const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_ARRAY_SIZE(2) + 60;
DynamicJsonBuffer jsonBuffer(capacity);
JsonObject& root = jsonBuffer.parseObject(client);
if (!root.success()) {
Serial.println(F("Parsing failed!"));
return;
}
Serial.println(F("Response:"));
Serial.println(root["User"].as<char*>());
Serial.println(root["Status"].as<char*>());
lcd.setCursor(0, 2);
lcd.print(root["User"].as<char*>());
lcd.setCursor(0, 0);
lcd.print(root["Status"].as<char*>());
client.stop();
digitalWrite(ledPin, LOW);
digitalWrite(errorLedPin, HIGH);
Serial.println("");
Serial.println("Succesfull sign in");
delay(3000);
lcd.clear();
} else
{
Serial.println("Timed out waiting for a card");
}
}
c arduino
add a comment |
up vote
3
down vote
favorite
I have recently started working with arduino and coding in C and have stumbled upon an issue.
Everything is working as it should be :
Read NFC tag > send POST to Laravel API > Recieve body response to
display on LCD
However the program is very inconsistent meaning that after an unknown period of time (this is a random period of time) the program returns a connection failed as shown in the monitor returns.
After this connection failed the program will not return back to it's connection and will keep returning connection failed until you restart the program.
I myself am not able to solve this after hours of googling, and therefor I am asking assistance from you guys.
(Do not give me plain code as an answer, but give me explanation on the side as I am learning and want to learn from this.)
Hardware:
Arduino MKR1000
Adafruit PN532 NFC/RFID Controller Shield (SPI)
Monitor returns:
Found chip PN532
Firmware ver. 1.6
Waiting for an ISO14443A card/n
Attempting to connect to SSID: ****
Connected to wifi
SSID: ****
IP Address: ****
signal strength (RSSI):-66 dBm
Starting connection to server...
================= START PROGRAM =======================
Found a card!
UID Length: 4 bytes
UID Value HEX: 67D667E
UID Value Decimal: 6125102126
{"Druppel": "6125102126"}
Connected!
Response:
Tom
Welcome
Succesfull sign in
Found a card!
UID Length: 4 bytes
UID Value HEX: C9DDCA35
UID Value Decimal: 20122120253
{"Druppel": "20122120253"}
Connection failed
Code
#include <SPI.h>
#include <WiFi101.h>
#include <Wire.h>
#include <LiquidCrystal.h>
#include <ArduinoJson.h>
#include <Adafruit_PN532.h>
#define PN532_SCK (9)
#define PN532_MOSI (8)
#define PN532_SS (6)
#define PN532_MISO (10)
#define PN532_IRQ (2)
#define PN532_RESET (7)
#define TIMEOUT 500
Adafruit_PN532 nfc(PN532_SCK, PN532_MISO, PN532_MOSI, PN532_SS);
const int rs = 12, en = 11, d4 = 2, d5 = 3, d6 = 4, d7 = 5;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
const int ledPin = 1;
const int errorLedPin = 13;
const int buzzerPin = 0;
int sensorPin = 0;
char SSID_NAME = "****";
char SSID_PASS = "****";
WiFiClient client;
int status = WL_IDLE_STATUS;
int keyIndex = 0;
char SERVER = "****.*****.nl";
char TOKEN = "******************";
char API = "********";
void printWiFiStatus() {
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
lcd.setCursor(0, 0);
lcd.print("SSID: ");
lcd.print(WiFi.SSID());
lcd.setCursor(0, 2);
lcd.print("IP: ");
lcd.print(WiFi.localIP());
}
void setup() {
Serial.begin(9600);
Serial.println("Serial ready");
analogWrite(A3, 0);
lcd.begin(16, 2);
pinMode(ledPin, OUTPUT);
pinMode(errorLedPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
tone(buzzerPin, 60);
nfc.begin();
uint32_t versiondata = nfc.getFirmwareVersion();
if (! versiondata) {
Serial.print("Didn't find PN53x board");
while (1);
}
Serial.print("Found chip PN5");Serial.println((versiondata>>24) & 0xFF, HEX);
Serial.print("Firmware ver. ");Serial.print((versiondata>>16) & 0xFF, DEC);Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);
nfc.setPassiveActivationRetries(0xFF);
nfc.SAMConfig();
Serial.print("Waiting for an ISO14443A card"); Serial.println("/n");
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
while (true);
}
noTone(buzzerPin);
tone(buzzerPin, 50);
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(SSID_NAME);
status = WiFi.begin(SSID_NAME, SSID_PASS);
delay(100);
}
Serial.println("Connected to wifi");
printWiFiStatus();
Serial.println("nStarting connection to server...");
Serial.println("n================= START PROGRAM =======================");
noTone(buzzerPin);
}
void loop() {
digitalWrite(errorLedPin, LOW);
boolean success;
uint8_t uid = { 0, 0, 0, 0, 0, 0, 0 };
uint8_t uidLength;
success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, &uid[0], &uidLength);
if (success) {
lcd.clear();
Serial.println("");
Serial.print("Found a card!");
Serial.println("");
Serial.print("UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
Serial.print("UID Value HEX: ");
String data;
for (uint8_t i=0; i < uidLength; i++)
{
Serial.print(uid[i], HEX);
data = String(data + uid[i]);
}
Serial.println("");
Serial.print("UID Value Decimal: ");
Serial.print(data);
Serial.println("");
lcd.print(data);
delay(100);
digitalWrite(ledPin, HIGH);
tone(buzzerPin, 50);
String PostData = "{"Druppel": "";
PostData = String(PostData + data);
PostData = String(PostData + ""}");
int PostDataLength = PostData.length() + 1;
delay(100);
noTone(buzzerPin);
char char_array[PostDataLength];
PostData.toCharArray(char_array, PostDataLength);
Serial.println(PostData);
delay(500);
if(!client.connect(SERVER, 80)) {
Serial.println(F("Connection failed"));
digitalWrite(errorLedPin, HIGH);
return;
}
Serial.println(F("Connected!"));
client.println("POST /api/******?api_token=****************** HTTP/1.1");
client.println("Host: ****.*****.nl");
client.println("Cache-Control: no-cache");
client.println("Content-Type: application/json");
client.print("Content-Length: ");
client.println(PostDataLength);
client.println();
client.println(PostData);
client.println(F("Connection: close"));
if (client.println() == 0) {
Serial.println(F("Failed to send request"));
return;
}
char status[32] = {0};
client.readBytesUntil('r', status, sizeof(status));
if (strcmp(status, "HTTP/1.1 200 OK") != 0) {
Serial.print(F("Unexpected response: "));
Serial.println(status);
return;
}
char endOfHeaders = "rnrn";
if (!client.find(endOfHeaders)) {
Serial.println(F("Invalid response"));
return;
}
const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_ARRAY_SIZE(2) + 60;
DynamicJsonBuffer jsonBuffer(capacity);
JsonObject& root = jsonBuffer.parseObject(client);
if (!root.success()) {
Serial.println(F("Parsing failed!"));
return;
}
Serial.println(F("Response:"));
Serial.println(root["User"].as<char*>());
Serial.println(root["Status"].as<char*>());
lcd.setCursor(0, 2);
lcd.print(root["User"].as<char*>());
lcd.setCursor(0, 0);
lcd.print(root["Status"].as<char*>());
client.stop();
digitalWrite(ledPin, LOW);
digitalWrite(errorLedPin, HIGH);
Serial.println("");
Serial.println("Succesfull sign in");
delay(3000);
lcd.clear();
} else
{
Serial.println("Timed out waiting for a card");
}
}
c arduino
don't use String class. use C strings - zero terminated char arrays
– Juraj
Nov 10 at 11:14
you send the "Connection: close" header after the body of the request
– Juraj
Nov 10 at 11:18
Hi @Juraj would you mind giving me an example suiting your 1st comment?
– Tomm
Nov 10 at 11:19
add a comment |
up vote
3
down vote
favorite
up vote
3
down vote
favorite
I have recently started working with arduino and coding in C and have stumbled upon an issue.
Everything is working as it should be :
Read NFC tag > send POST to Laravel API > Recieve body response to
display on LCD
However the program is very inconsistent meaning that after an unknown period of time (this is a random period of time) the program returns a connection failed as shown in the monitor returns.
After this connection failed the program will not return back to it's connection and will keep returning connection failed until you restart the program.
I myself am not able to solve this after hours of googling, and therefor I am asking assistance from you guys.
(Do not give me plain code as an answer, but give me explanation on the side as I am learning and want to learn from this.)
Hardware:
Arduino MKR1000
Adafruit PN532 NFC/RFID Controller Shield (SPI)
Monitor returns:
Found chip PN532
Firmware ver. 1.6
Waiting for an ISO14443A card/n
Attempting to connect to SSID: ****
Connected to wifi
SSID: ****
IP Address: ****
signal strength (RSSI):-66 dBm
Starting connection to server...
================= START PROGRAM =======================
Found a card!
UID Length: 4 bytes
UID Value HEX: 67D667E
UID Value Decimal: 6125102126
{"Druppel": "6125102126"}
Connected!
Response:
Tom
Welcome
Succesfull sign in
Found a card!
UID Length: 4 bytes
UID Value HEX: C9DDCA35
UID Value Decimal: 20122120253
{"Druppel": "20122120253"}
Connection failed
Code
#include <SPI.h>
#include <WiFi101.h>
#include <Wire.h>
#include <LiquidCrystal.h>
#include <ArduinoJson.h>
#include <Adafruit_PN532.h>
#define PN532_SCK (9)
#define PN532_MOSI (8)
#define PN532_SS (6)
#define PN532_MISO (10)
#define PN532_IRQ (2)
#define PN532_RESET (7)
#define TIMEOUT 500
Adafruit_PN532 nfc(PN532_SCK, PN532_MISO, PN532_MOSI, PN532_SS);
const int rs = 12, en = 11, d4 = 2, d5 = 3, d6 = 4, d7 = 5;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
const int ledPin = 1;
const int errorLedPin = 13;
const int buzzerPin = 0;
int sensorPin = 0;
char SSID_NAME = "****";
char SSID_PASS = "****";
WiFiClient client;
int status = WL_IDLE_STATUS;
int keyIndex = 0;
char SERVER = "****.*****.nl";
char TOKEN = "******************";
char API = "********";
void printWiFiStatus() {
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
lcd.setCursor(0, 0);
lcd.print("SSID: ");
lcd.print(WiFi.SSID());
lcd.setCursor(0, 2);
lcd.print("IP: ");
lcd.print(WiFi.localIP());
}
void setup() {
Serial.begin(9600);
Serial.println("Serial ready");
analogWrite(A3, 0);
lcd.begin(16, 2);
pinMode(ledPin, OUTPUT);
pinMode(errorLedPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
tone(buzzerPin, 60);
nfc.begin();
uint32_t versiondata = nfc.getFirmwareVersion();
if (! versiondata) {
Serial.print("Didn't find PN53x board");
while (1);
}
Serial.print("Found chip PN5");Serial.println((versiondata>>24) & 0xFF, HEX);
Serial.print("Firmware ver. ");Serial.print((versiondata>>16) & 0xFF, DEC);Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);
nfc.setPassiveActivationRetries(0xFF);
nfc.SAMConfig();
Serial.print("Waiting for an ISO14443A card"); Serial.println("/n");
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
while (true);
}
noTone(buzzerPin);
tone(buzzerPin, 50);
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(SSID_NAME);
status = WiFi.begin(SSID_NAME, SSID_PASS);
delay(100);
}
Serial.println("Connected to wifi");
printWiFiStatus();
Serial.println("nStarting connection to server...");
Serial.println("n================= START PROGRAM =======================");
noTone(buzzerPin);
}
void loop() {
digitalWrite(errorLedPin, LOW);
boolean success;
uint8_t uid = { 0, 0, 0, 0, 0, 0, 0 };
uint8_t uidLength;
success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, &uid[0], &uidLength);
if (success) {
lcd.clear();
Serial.println("");
Serial.print("Found a card!");
Serial.println("");
Serial.print("UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
Serial.print("UID Value HEX: ");
String data;
for (uint8_t i=0; i < uidLength; i++)
{
Serial.print(uid[i], HEX);
data = String(data + uid[i]);
}
Serial.println("");
Serial.print("UID Value Decimal: ");
Serial.print(data);
Serial.println("");
lcd.print(data);
delay(100);
digitalWrite(ledPin, HIGH);
tone(buzzerPin, 50);
String PostData = "{"Druppel": "";
PostData = String(PostData + data);
PostData = String(PostData + ""}");
int PostDataLength = PostData.length() + 1;
delay(100);
noTone(buzzerPin);
char char_array[PostDataLength];
PostData.toCharArray(char_array, PostDataLength);
Serial.println(PostData);
delay(500);
if(!client.connect(SERVER, 80)) {
Serial.println(F("Connection failed"));
digitalWrite(errorLedPin, HIGH);
return;
}
Serial.println(F("Connected!"));
client.println("POST /api/******?api_token=****************** HTTP/1.1");
client.println("Host: ****.*****.nl");
client.println("Cache-Control: no-cache");
client.println("Content-Type: application/json");
client.print("Content-Length: ");
client.println(PostDataLength);
client.println();
client.println(PostData);
client.println(F("Connection: close"));
if (client.println() == 0) {
Serial.println(F("Failed to send request"));
return;
}
char status[32] = {0};
client.readBytesUntil('r', status, sizeof(status));
if (strcmp(status, "HTTP/1.1 200 OK") != 0) {
Serial.print(F("Unexpected response: "));
Serial.println(status);
return;
}
char endOfHeaders = "rnrn";
if (!client.find(endOfHeaders)) {
Serial.println(F("Invalid response"));
return;
}
const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_ARRAY_SIZE(2) + 60;
DynamicJsonBuffer jsonBuffer(capacity);
JsonObject& root = jsonBuffer.parseObject(client);
if (!root.success()) {
Serial.println(F("Parsing failed!"));
return;
}
Serial.println(F("Response:"));
Serial.println(root["User"].as<char*>());
Serial.println(root["Status"].as<char*>());
lcd.setCursor(0, 2);
lcd.print(root["User"].as<char*>());
lcd.setCursor(0, 0);
lcd.print(root["Status"].as<char*>());
client.stop();
digitalWrite(ledPin, LOW);
digitalWrite(errorLedPin, HIGH);
Serial.println("");
Serial.println("Succesfull sign in");
delay(3000);
lcd.clear();
} else
{
Serial.println("Timed out waiting for a card");
}
}
c arduino
I have recently started working with arduino and coding in C and have stumbled upon an issue.
Everything is working as it should be :
Read NFC tag > send POST to Laravel API > Recieve body response to
display on LCD
However the program is very inconsistent meaning that after an unknown period of time (this is a random period of time) the program returns a connection failed as shown in the monitor returns.
After this connection failed the program will not return back to it's connection and will keep returning connection failed until you restart the program.
I myself am not able to solve this after hours of googling, and therefor I am asking assistance from you guys.
(Do not give me plain code as an answer, but give me explanation on the side as I am learning and want to learn from this.)
Hardware:
Arduino MKR1000
Adafruit PN532 NFC/RFID Controller Shield (SPI)
Monitor returns:
Found chip PN532
Firmware ver. 1.6
Waiting for an ISO14443A card/n
Attempting to connect to SSID: ****
Connected to wifi
SSID: ****
IP Address: ****
signal strength (RSSI):-66 dBm
Starting connection to server...
================= START PROGRAM =======================
Found a card!
UID Length: 4 bytes
UID Value HEX: 67D667E
UID Value Decimal: 6125102126
{"Druppel": "6125102126"}
Connected!
Response:
Tom
Welcome
Succesfull sign in
Found a card!
UID Length: 4 bytes
UID Value HEX: C9DDCA35
UID Value Decimal: 20122120253
{"Druppel": "20122120253"}
Connection failed
Code
#include <SPI.h>
#include <WiFi101.h>
#include <Wire.h>
#include <LiquidCrystal.h>
#include <ArduinoJson.h>
#include <Adafruit_PN532.h>
#define PN532_SCK (9)
#define PN532_MOSI (8)
#define PN532_SS (6)
#define PN532_MISO (10)
#define PN532_IRQ (2)
#define PN532_RESET (7)
#define TIMEOUT 500
Adafruit_PN532 nfc(PN532_SCK, PN532_MISO, PN532_MOSI, PN532_SS);
const int rs = 12, en = 11, d4 = 2, d5 = 3, d6 = 4, d7 = 5;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
const int ledPin = 1;
const int errorLedPin = 13;
const int buzzerPin = 0;
int sensorPin = 0;
char SSID_NAME = "****";
char SSID_PASS = "****";
WiFiClient client;
int status = WL_IDLE_STATUS;
int keyIndex = 0;
char SERVER = "****.*****.nl";
char TOKEN = "******************";
char API = "********";
void printWiFiStatus() {
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
lcd.setCursor(0, 0);
lcd.print("SSID: ");
lcd.print(WiFi.SSID());
lcd.setCursor(0, 2);
lcd.print("IP: ");
lcd.print(WiFi.localIP());
}
void setup() {
Serial.begin(9600);
Serial.println("Serial ready");
analogWrite(A3, 0);
lcd.begin(16, 2);
pinMode(ledPin, OUTPUT);
pinMode(errorLedPin, OUTPUT);
pinMode(buzzerPin, OUTPUT);
tone(buzzerPin, 60);
nfc.begin();
uint32_t versiondata = nfc.getFirmwareVersion();
if (! versiondata) {
Serial.print("Didn't find PN53x board");
while (1);
}
Serial.print("Found chip PN5");Serial.println((versiondata>>24) & 0xFF, HEX);
Serial.print("Firmware ver. ");Serial.print((versiondata>>16) & 0xFF, DEC);Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);
nfc.setPassiveActivationRetries(0xFF);
nfc.SAMConfig();
Serial.print("Waiting for an ISO14443A card"); Serial.println("/n");
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
while (true);
}
noTone(buzzerPin);
tone(buzzerPin, 50);
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(SSID_NAME);
status = WiFi.begin(SSID_NAME, SSID_PASS);
delay(100);
}
Serial.println("Connected to wifi");
printWiFiStatus();
Serial.println("nStarting connection to server...");
Serial.println("n================= START PROGRAM =======================");
noTone(buzzerPin);
}
void loop() {
digitalWrite(errorLedPin, LOW);
boolean success;
uint8_t uid = { 0, 0, 0, 0, 0, 0, 0 };
uint8_t uidLength;
success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, &uid[0], &uidLength);
if (success) {
lcd.clear();
Serial.println("");
Serial.print("Found a card!");
Serial.println("");
Serial.print("UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
Serial.print("UID Value HEX: ");
String data;
for (uint8_t i=0; i < uidLength; i++)
{
Serial.print(uid[i], HEX);
data = String(data + uid[i]);
}
Serial.println("");
Serial.print("UID Value Decimal: ");
Serial.print(data);
Serial.println("");
lcd.print(data);
delay(100);
digitalWrite(ledPin, HIGH);
tone(buzzerPin, 50);
String PostData = "{"Druppel": "";
PostData = String(PostData + data);
PostData = String(PostData + ""}");
int PostDataLength = PostData.length() + 1;
delay(100);
noTone(buzzerPin);
char char_array[PostDataLength];
PostData.toCharArray(char_array, PostDataLength);
Serial.println(PostData);
delay(500);
if(!client.connect(SERVER, 80)) {
Serial.println(F("Connection failed"));
digitalWrite(errorLedPin, HIGH);
return;
}
Serial.println(F("Connected!"));
client.println("POST /api/******?api_token=****************** HTTP/1.1");
client.println("Host: ****.*****.nl");
client.println("Cache-Control: no-cache");
client.println("Content-Type: application/json");
client.print("Content-Length: ");
client.println(PostDataLength);
client.println();
client.println(PostData);
client.println(F("Connection: close"));
if (client.println() == 0) {
Serial.println(F("Failed to send request"));
return;
}
char status[32] = {0};
client.readBytesUntil('r', status, sizeof(status));
if (strcmp(status, "HTTP/1.1 200 OK") != 0) {
Serial.print(F("Unexpected response: "));
Serial.println(status);
return;
}
char endOfHeaders = "rnrn";
if (!client.find(endOfHeaders)) {
Serial.println(F("Invalid response"));
return;
}
const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_ARRAY_SIZE(2) + 60;
DynamicJsonBuffer jsonBuffer(capacity);
JsonObject& root = jsonBuffer.parseObject(client);
if (!root.success()) {
Serial.println(F("Parsing failed!"));
return;
}
Serial.println(F("Response:"));
Serial.println(root["User"].as<char*>());
Serial.println(root["Status"].as<char*>());
lcd.setCursor(0, 2);
lcd.print(root["User"].as<char*>());
lcd.setCursor(0, 0);
lcd.print(root["Status"].as<char*>());
client.stop();
digitalWrite(ledPin, LOW);
digitalWrite(errorLedPin, HIGH);
Serial.println("");
Serial.println("Succesfull sign in");
delay(3000);
lcd.clear();
} else
{
Serial.println("Timed out waiting for a card");
}
}
c arduino
c arduino
edited Nov 10 at 12:59
asked Nov 10 at 9:32
Tomm
7391726
7391726
don't use String class. use C strings - zero terminated char arrays
– Juraj
Nov 10 at 11:14
you send the "Connection: close" header after the body of the request
– Juraj
Nov 10 at 11:18
Hi @Juraj would you mind giving me an example suiting your 1st comment?
– Tomm
Nov 10 at 11:19
add a comment |
don't use String class. use C strings - zero terminated char arrays
– Juraj
Nov 10 at 11:14
you send the "Connection: close" header after the body of the request
– Juraj
Nov 10 at 11:18
Hi @Juraj would you mind giving me an example suiting your 1st comment?
– Tomm
Nov 10 at 11:19
don't use String class. use C strings - zero terminated char arrays
– Juraj
Nov 10 at 11:14
don't use String class. use C strings - zero terminated char arrays
– Juraj
Nov 10 at 11:14
you send the "Connection: close" header after the body of the request
– Juraj
Nov 10 at 11:18
you send the "Connection: close" header after the body of the request
– Juraj
Nov 10 at 11:18
Hi @Juraj would you mind giving me an example suiting your 1st comment?
– Tomm
Nov 10 at 11:19
Hi @Juraj would you mind giving me an example suiting your 1st comment?
– Tomm
Nov 10 at 11:19
add a comment |
1 Answer
1
active
oldest
votes
up vote
1
down vote
Don't use the String class. It fragments the memory heap, which leads to crash. Use C strings (zero terminated char array). If you are not experienced with strcat
and sprintf
functions, you can use CStringBuilder from my StreamLib library. The library is available in Library Manager in Arduino IDE.
char PostData[200];
CStringBuilder sb(PostData, sizeof(PostData));
sb.print("{"Druppel": "");
for (uint8_t i=0; i < uidLength; i++)
{
sb.print(uid[i]);
//sb.printf("%02x", uid[i]); // for hex aligned with 0
}
sb.print(""}");
Serial.println(sb.length());
Serial.println(PostData);
Hey, as far as testing goes now this is working flawless, I am not recieving any connection errors. However I can not force my program to have repeated connection errors so time will say. Thanks alot Juraj (good looking library).
– Tomm
Nov 10 at 12:52
in your code in Question you print decimal number one after another. did you want to print hex numbers aligned with 0?
– Juraj
Nov 10 at 12:55
I am honestly not sure what that does, atm this code reads the nfc tags number (auto assigned ID) so that we can use this in our POST. What would having a hex aligned with 0 do for us and what does it do in general. I am very new to this.
– Tomm
Nov 10 at 13:04
if the numbers are 2 and 165 then the concatenation is 2165. You don't now how to split it. It could be 21 and 65, But a byte fits into two hex digits. so 02 and A5 is 02A5 and it can be split back to 02 and A5.
– Juraj
Nov 10 at 13:09
As of right now I think having just the ID of the nfc is enough since this gets linked server side on the api.
– Tomm
Nov 10 at 13:12
|
show 6 more comments
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53237642%2farduino-connection-failed-loop-after-random-period-of-time%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
1
down vote
Don't use the String class. It fragments the memory heap, which leads to crash. Use C strings (zero terminated char array). If you are not experienced with strcat
and sprintf
functions, you can use CStringBuilder from my StreamLib library. The library is available in Library Manager in Arduino IDE.
char PostData[200];
CStringBuilder sb(PostData, sizeof(PostData));
sb.print("{"Druppel": "");
for (uint8_t i=0; i < uidLength; i++)
{
sb.print(uid[i]);
//sb.printf("%02x", uid[i]); // for hex aligned with 0
}
sb.print(""}");
Serial.println(sb.length());
Serial.println(PostData);
Hey, as far as testing goes now this is working flawless, I am not recieving any connection errors. However I can not force my program to have repeated connection errors so time will say. Thanks alot Juraj (good looking library).
– Tomm
Nov 10 at 12:52
in your code in Question you print decimal number one after another. did you want to print hex numbers aligned with 0?
– Juraj
Nov 10 at 12:55
I am honestly not sure what that does, atm this code reads the nfc tags number (auto assigned ID) so that we can use this in our POST. What would having a hex aligned with 0 do for us and what does it do in general. I am very new to this.
– Tomm
Nov 10 at 13:04
if the numbers are 2 and 165 then the concatenation is 2165. You don't now how to split it. It could be 21 and 65, But a byte fits into two hex digits. so 02 and A5 is 02A5 and it can be split back to 02 and A5.
– Juraj
Nov 10 at 13:09
As of right now I think having just the ID of the nfc is enough since this gets linked server side on the api.
– Tomm
Nov 10 at 13:12
|
show 6 more comments
up vote
1
down vote
Don't use the String class. It fragments the memory heap, which leads to crash. Use C strings (zero terminated char array). If you are not experienced with strcat
and sprintf
functions, you can use CStringBuilder from my StreamLib library. The library is available in Library Manager in Arduino IDE.
char PostData[200];
CStringBuilder sb(PostData, sizeof(PostData));
sb.print("{"Druppel": "");
for (uint8_t i=0; i < uidLength; i++)
{
sb.print(uid[i]);
//sb.printf("%02x", uid[i]); // for hex aligned with 0
}
sb.print(""}");
Serial.println(sb.length());
Serial.println(PostData);
Hey, as far as testing goes now this is working flawless, I am not recieving any connection errors. However I can not force my program to have repeated connection errors so time will say. Thanks alot Juraj (good looking library).
– Tomm
Nov 10 at 12:52
in your code in Question you print decimal number one after another. did you want to print hex numbers aligned with 0?
– Juraj
Nov 10 at 12:55
I am honestly not sure what that does, atm this code reads the nfc tags number (auto assigned ID) so that we can use this in our POST. What would having a hex aligned with 0 do for us and what does it do in general. I am very new to this.
– Tomm
Nov 10 at 13:04
if the numbers are 2 and 165 then the concatenation is 2165. You don't now how to split it. It could be 21 and 65, But a byte fits into two hex digits. so 02 and A5 is 02A5 and it can be split back to 02 and A5.
– Juraj
Nov 10 at 13:09
As of right now I think having just the ID of the nfc is enough since this gets linked server side on the api.
– Tomm
Nov 10 at 13:12
|
show 6 more comments
up vote
1
down vote
up vote
1
down vote
Don't use the String class. It fragments the memory heap, which leads to crash. Use C strings (zero terminated char array). If you are not experienced with strcat
and sprintf
functions, you can use CStringBuilder from my StreamLib library. The library is available in Library Manager in Arduino IDE.
char PostData[200];
CStringBuilder sb(PostData, sizeof(PostData));
sb.print("{"Druppel": "");
for (uint8_t i=0; i < uidLength; i++)
{
sb.print(uid[i]);
//sb.printf("%02x", uid[i]); // for hex aligned with 0
}
sb.print(""}");
Serial.println(sb.length());
Serial.println(PostData);
Don't use the String class. It fragments the memory heap, which leads to crash. Use C strings (zero terminated char array). If you are not experienced with strcat
and sprintf
functions, you can use CStringBuilder from my StreamLib library. The library is available in Library Manager in Arduino IDE.
char PostData[200];
CStringBuilder sb(PostData, sizeof(PostData));
sb.print("{"Druppel": "");
for (uint8_t i=0; i < uidLength; i++)
{
sb.print(uid[i]);
//sb.printf("%02x", uid[i]); // for hex aligned with 0
}
sb.print(""}");
Serial.println(sb.length());
Serial.println(PostData);
edited Nov 10 at 12:41
answered Nov 10 at 12:08
Juraj
345310
345310
Hey, as far as testing goes now this is working flawless, I am not recieving any connection errors. However I can not force my program to have repeated connection errors so time will say. Thanks alot Juraj (good looking library).
– Tomm
Nov 10 at 12:52
in your code in Question you print decimal number one after another. did you want to print hex numbers aligned with 0?
– Juraj
Nov 10 at 12:55
I am honestly not sure what that does, atm this code reads the nfc tags number (auto assigned ID) so that we can use this in our POST. What would having a hex aligned with 0 do for us and what does it do in general. I am very new to this.
– Tomm
Nov 10 at 13:04
if the numbers are 2 and 165 then the concatenation is 2165. You don't now how to split it. It could be 21 and 65, But a byte fits into two hex digits. so 02 and A5 is 02A5 and it can be split back to 02 and A5.
– Juraj
Nov 10 at 13:09
As of right now I think having just the ID of the nfc is enough since this gets linked server side on the api.
– Tomm
Nov 10 at 13:12
|
show 6 more comments
Hey, as far as testing goes now this is working flawless, I am not recieving any connection errors. However I can not force my program to have repeated connection errors so time will say. Thanks alot Juraj (good looking library).
– Tomm
Nov 10 at 12:52
in your code in Question you print decimal number one after another. did you want to print hex numbers aligned with 0?
– Juraj
Nov 10 at 12:55
I am honestly not sure what that does, atm this code reads the nfc tags number (auto assigned ID) so that we can use this in our POST. What would having a hex aligned with 0 do for us and what does it do in general. I am very new to this.
– Tomm
Nov 10 at 13:04
if the numbers are 2 and 165 then the concatenation is 2165. You don't now how to split it. It could be 21 and 65, But a byte fits into two hex digits. so 02 and A5 is 02A5 and it can be split back to 02 and A5.
– Juraj
Nov 10 at 13:09
As of right now I think having just the ID of the nfc is enough since this gets linked server side on the api.
– Tomm
Nov 10 at 13:12
Hey, as far as testing goes now this is working flawless, I am not recieving any connection errors. However I can not force my program to have repeated connection errors so time will say. Thanks alot Juraj (good looking library).
– Tomm
Nov 10 at 12:52
Hey, as far as testing goes now this is working flawless, I am not recieving any connection errors. However I can not force my program to have repeated connection errors so time will say. Thanks alot Juraj (good looking library).
– Tomm
Nov 10 at 12:52
in your code in Question you print decimal number one after another. did you want to print hex numbers aligned with 0?
– Juraj
Nov 10 at 12:55
in your code in Question you print decimal number one after another. did you want to print hex numbers aligned with 0?
– Juraj
Nov 10 at 12:55
I am honestly not sure what that does, atm this code reads the nfc tags number (auto assigned ID) so that we can use this in our POST. What would having a hex aligned with 0 do for us and what does it do in general. I am very new to this.
– Tomm
Nov 10 at 13:04
I am honestly not sure what that does, atm this code reads the nfc tags number (auto assigned ID) so that we can use this in our POST. What would having a hex aligned with 0 do for us and what does it do in general. I am very new to this.
– Tomm
Nov 10 at 13:04
if the numbers are 2 and 165 then the concatenation is 2165. You don't now how to split it. It could be 21 and 65, But a byte fits into two hex digits. so 02 and A5 is 02A5 and it can be split back to 02 and A5.
– Juraj
Nov 10 at 13:09
if the numbers are 2 and 165 then the concatenation is 2165. You don't now how to split it. It could be 21 and 65, But a byte fits into two hex digits. so 02 and A5 is 02A5 and it can be split back to 02 and A5.
– Juraj
Nov 10 at 13:09
As of right now I think having just the ID of the nfc is enough since this gets linked server side on the api.
– Tomm
Nov 10 at 13:12
As of right now I think having just the ID of the nfc is enough since this gets linked server side on the api.
– Tomm
Nov 10 at 13:12
|
show 6 more comments
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53237642%2farduino-connection-failed-loop-after-random-period-of-time%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
don't use String class. use C strings - zero terminated char arrays
– Juraj
Nov 10 at 11:14
you send the "Connection: close" header after the body of the request
– Juraj
Nov 10 at 11:18
Hi @Juraj would you mind giving me an example suiting your 1st comment?
– Tomm
Nov 10 at 11:19