I am trying to make an rfid attendance system with NodeMCU8266.
I have gotten some code online and modified it with the help of a friend since I have zero experience with coding.
The code below scans an rfid card for data, and will then connect to a google sheet with google apps script. The code will show the web app url in the serial monitor that will send the data to google sheets automatically. However, I keep getting HTTPS GET: code 400 error and the data is not being sent to google sheets. But the web app url that shows up in serial monitor works when manually pasted into the address bar.
I have tried using the url fingerprint and the client.SetInsecure but it has not worked regardless of what i used. Any ideas what might be wrong? Your help is highly appreciated!
#include <SPI.h>
#include <MFRC522.h>
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <WiFiClientSecureBearSSL.h>
//-----------------------------------------------------------
const String web_app_url = "ENTER WEB APP URL HERE";
//-----------------------------------------------------------
#define WIFI_SSID "SSID"
#define WIFI_PASSWORD "PASSWORD"
//-----------------------------------------------------------
int blocks[] = {4,5,6,8,9,10,12,13,14,18};
#define blocks_len (sizeof(blocks) / sizeof(blocks[0]))
//-----------------------------------------------------------
//GPIO 0 --> D3
//GPIO 2 --> D4
//GPIO 4 --> D2
#define RST_PIN D3
#define SS_PIN D4
#define BUZZER D0
#define GreenLed D1 //When WIFI is connected, LED ON.
#define YellowLed D8 // When CARD is scanned, LED ON.
#define RedLed D2 //When NODEMCU is not connected to WIFI, LED ON
//-----------------------------------------
MFRC522 mfrc522(SS_PIN, RST_PIN);
MFRC522::MIFARE_Key key;
MFRC522::StatusCode status;
//-----------------------------------------
/* Be aware of Sector Trailer Blocks */
int blockNum = 2;
/* Create another array to read data from Block */
/* Legthn of buffer should be 2 Bytes more than the size of Block (16 Bytes) */
byte bufferLen = 18;
byte readBlockData[18];
//-----------------------------------------
// Fingerprint for demo URL, expires on Monday, May 2, 2022 7:20:58 AM, needs to be updated well before this date
//const uint8_t fingerprint[20] = {0xb3 0x3f 0xf3 0xe4 0x5f 0x76 0x59 0x2e 0xf9 0xa2 0x0b 0xf7 0x99 0x5e 0x44 0x89 0x21 0x4d 0x2e 0x22};
//const uint8_t fingerprint[20] = {0xb3, 0x3f, 0xf3, 0xe4, 0x5f, 0x76, 0x59, 0x2e, 0xf9, 0xa2, 0x0b, 0xf7, 0x99, 0x5e, 0x44, 0x89, 0x21, 0x4d, 0x2e, 0x22};
//0x9a 0x71 0xde 0xe7 0x1a 0xb2 0x2c 0xab 0x4f 0x23 0x64 0x9a 0xbc 0xef 0x62 0x56 0x20 0x4e 0x43 c
//0x9a, 0x71, 0xde,0xe7, 0x1a, 0xb2, 0x25, 0xca, 0xb4, 0xf2, 0x36, 0x49, 0xab, 0xce, 0xf6, 0x25, 0x62, 0x04, 0xe4, 0x3c
//0xb3 0x3f 0xf3 0xe4 0x5f 0x76 0x59 0x2e 0xf9 0xa2 0x0b 0xf7 0x99 0x5e 0x44 0x89 0x21 0x4d 0x2e 0x22 -LATEST
//b33ff3e45f76592ef9a20bf7995e4489214d2e22
//-----------------------------------------
/****************************************************************************************************
* setup() function
****************************************************************************************************/
void setup()
{
Serial.begin(9600);
WiFi.mode(WIFI_OFF); //Prevents reconnection issue (taking too long to connect)
delay(1000);
WiFi.mode(WIFI_STA); //This line hides the viewing of ESP as wifi hotspot
WiFi.begin(WIFI_SSID, WIFI_PASSWORD); //Connect to your WiFi router
Serial.println("");
Serial.print("Connecting to ");
Serial.print(WIFI_SSID);
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
//If connection successful show IP address in serial monitor
Serial.println("");
Serial.println("Connected");
digitalWrite(GreenLed, HIGH);
Serial.print("IP address: ");
Serial.println(WiFi.localIP()); //IP address assigned to your ESP
//--------------------------------------------------
/* pin outputs */
pinMode(BUZZER, OUTPUT);
pinMode(GreenLed, OUTPUT);
pinMode(YellowLed, OUTPUT);
pinMode(RedLed, OUTPUT);
//--------------------------------------------------
/* Initialize SPI bus */
SPI.begin();
//--------------------------------------------------
}
/****************************************************************************************************
* loop() function
****************************************************************************************************/
void loop()
{
if(WiFi.status() != WL_CONNECTED){
WiFi.disconnect();
WiFi.mode(WIFI_STA);
Serial.print("Reconnecting to ");
digitalWrite(RedLed, HIGH);
digitalWrite(GreenLed,LOW);
Serial.println(WIFI_SSID);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected");
digitalWrite(RedLed, LOW);
digitalWrite(GreenLed, HIGH);
Serial.print("IP address: ");
Serial.println(WiFi.localIP()); //IP address assigned to your ESP
}
//------------------------------------------------------------------------
/* Initialize MFRC522 Module */
mfrc522.PCD_Init();
/* Look for new cards */
/* Reset the loop if no new card is present on RC522 Reader */
if ( ! mfrc522.PICC_IsNewCardPresent()) {return;}
/* Select one of the cards */
if ( ! mfrc522.PICC_ReadCardSerial()) {return;}
/* Read data from the same block */
Serial.println();
Serial.println(F("Reading last data from RFID..."));
//------------------------------------------------------------------------
String fullURL = "", temp;
for (byte i = 0; i < blocks_len; i++) {
ReadDataFromBlock(blocks[i], readBlockData);
if(i == 0){
temp = String((char*)readBlockData);
temp.trim();
fullURL = "data" + String(i) + "=" + temp;
}
else{
temp = String((char*)readBlockData);
temp.trim();
fullURL += "&data" + String(i) + "=" + temp;
}
}
//Serial.println(fullURL);
fullURL.trim();
fullURL = web_app_url + "?" + fullURL;
fullURL.trim();
Serial.println(fullURL);
//------------------------------------------------------------------------
digitalWrite(BUZZER, HIGH);
digitalWrite(YellowLed,HIGH);
delay(100);
digitalWrite(BUZZER, LOW);
delay(100);
digitalWrite(BUZZER, HIGH);
delay(100);
digitalWrite(BUZZER, LOW);
delay(100);
digitalWrite(BUZZER, HIGH);
delay(100);
digitalWrite(YellowLed, LOW);
digitalWrite(BUZZER, LOW);
delay(100);
//------------------------------------------------------------------------
//MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
if (WiFi.status() == WL_CONNECTED) {
//-------------------------------------------------------------------------------
std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
//-------------------------------------------------------------------------------
//uncomment following line, if you want to use the SSL certificate
//client->setFingerprint(fingerprint);
//or uncomment following line, if you want to ignore the SSL certificate
client->setInsecure();
//-------------------------------------------------------------------------------
HTTPClient https;
Serial.print(F("[HTTPS] begin...\n"));
//-------------------------------------------------------------------------------
//NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
if (https.begin(*client, (String)fullURL)){
//-----------------------------------------------------------------
// HTTP
Serial.print(F("[HTTPS] GET...\n"));
// start connection and send HTTP header
int httpCode = https.GET();
//-----------------------------------------------------------------
// httpCode will be negative on error
if (httpCode > 0) {
// HTTP header has been send and Server response header has been handled
Serial.printf("[HTTPS] GET... code: %d\n", httpCode);
// file found at server
}
//-----------------------------------------------------------------
else
{Serial.printf("[HTTPS] GET... failed, error: %s\n", https.errorToString(httpCode).c_str());}
//-----------------------------------------------------------------
https.end();
delay(1000);
}
//NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
else {
Serial.printf("[HTTPS} Unable to connect\n");
}
//NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
}
//MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
}
/****************************************************************************************************
* ReadDataFromBlock() function
****************************************************************************************************/
void ReadDataFromBlock(int blockNum, byte readBlockData[])
{
//----------------------------------------------------------------------------
/* Prepare the ksy for authentication */
/* All keys are set to FFFFFFFFFFFFh at chip delivery from the factory */
for (byte i = 0; i < 6; i++) {
key.keyByte[i] = 0xFF;
}
//----------------------------------------------------------------------------
/* Authenticating the desired data block for Read access using Key A */
status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, blockNum, &key, &(mfrc522.uid));
//----------------------------------------------------------------------------s
if (status != MFRC522::STATUS_OK){
Serial.print("Authentication failed for Read: ");
Serial.println(mfrc522.GetStatusCodeName(status));
return;
}
//----------------------------------------------------------------------------
else {
Serial.println("Authentication success");
}
//----------------------------------------------------------------------------
/* Reading data from the Block */
status = mfrc522.MIFARE_Read(blockNum, readBlockData, &bufferLen);
if (status != MFRC522::STATUS_OK) {
Serial.print("Reading failed: ");
Serial.println(mfrc522.GetStatusCodeName(status));
return;
}
//----------------------------------------------------------------------------
else {
readBlockData[16] = ' ';
readBlockData[17] = ' ';
Serial.println("Block was read successfully");
}
//----------------------------------------------------------------------------
}
Related
I am currently trying to make an NFC Door Lock and I am trying to make it so when the door is locked it knows and will unlock the door with the right NFC card and vice versa. I have created the bool locked and made it = false. When I unlocked the door I have made it so that it will change bool locked from false to true although that doesn't work and the NFC card continues to lock the door every time.
NFC Card Read Area:
if ( ! mfrc522.PICC_IsNewCardPresent())
return;
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial())
return;
// Show some details of the PICC (that is: the tag/card)
bool locked = false;
if(locked == false)
{
Serial.print(F("Card UID:"));
dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
byte valid[4] = { 0xEB, 0xA6, 0xE9, 0x21 };
if (memcmp(valid, mfrc522.uid.uidByte, mfrc522.uid.size) == 0) {
Serial.print("Door Locked");
int motorPin = 3;
digitalWrite(motorPin, HIGH); // turns the motor ON
delay(5000);
digitalWrite(motorPin, LOW); // turns the motor OFF
bool locked = true;
}}
if(locked == true)
{
Serial.print(F("Card UID:"));
dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
byte valid[4] = { 0xEB, 0xA6, 0xE9, 0x21 };
if (memcmp(valid, mfrc522.uid.uidByte, mfrc522.uid.size) == 0) {
Serial.print("Door Unlocked");
int motorPin = 3;
digitalWrite(motorPin, HIGH); // turns the motor ON
delay(5000);
digitalWrite(motorPin, LOW); // turns the motor OFF
bool locked = false;
}}
Serial.println();
Serial.print(F("PICC type: "));
MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
Serial.println(mfrc522.PICC_GetTypeName(piccType));
Full Code:
#include <SoftwareSerial.h>
#include <ArduinoBlue.h>
#include <SPI.h>
#include <MFRC522.h>
#define RST_PIN 9 // Configurable, see typical pin layout above
#define SS_PIN 10 // Configurable, see typical pin layout above
const unsigned long BAUD_RATE = 9600;
// The bluetooth tx and rx pins must be supported by software serial.
// Visit https://www.arduino.cc/en/Reference/SoftwareSerial for unsupported pins.
// Bluetooth TX -> Arduino D8
const int BLUETOOTH_TX = 8;
// Bluetooth RX -> Arduino D7
const int BLUETOOTH_RX = 7;
int prevThrottle = 49;
int prevSteering = 49;
int throttle, steering, sliderVal, button, sliderId;
SoftwareSerial bluetooth(BLUETOOTH_TX, BLUETOOTH_RX);
ArduinoBlue phone(bluetooth); // pass reference of bluetooth object to ArduinoBlue constructor
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
// Number of known default keys (hard-coded)
// NOTE: Synchronize the NR_KNOWN_KEYS define with the defaultKeys[] array
#define NR_KNOWN_KEYS 8
// Known keys, see: https://code.google.com/p/mfcuk/wiki/MifareClassicDefaultKeys
byte knownKeys[NR_KNOWN_KEYS][MFRC522::MF_KEY_SIZE] = {
{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, // FF FF FF FF FF FF = factory default
{0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5}, // A0 A1 A2 A3 A4 A5
{0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5}, // B0 B1 B2 B3 B4 B5
{0x4d, 0x3a, 0x99, 0xc3, 0x51, 0xdd}, // 4D 3A 99 C3 51 DD
{0x1a, 0x98, 0x2c, 0x7e, 0x45, 0x9a}, // 1A 98 2C 7E 45 9A
{0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7}, // D3 F7 D3 F7 D3 F7
{0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}, // AA BB CC DD EE FF
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00} // 00 00 00 00 00 00
};
// Setup code runs once after program starts.
void setup() {
// Start serial communications.
// The baud rate must be the same for both the serial and the bluetooth.
SPI.begin();
Serial.begin(BAUD_RATE);
while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
mfrc522.PCD_Init(); // Init MFRC522 card
Serial.println(F("Try the most used default keys to print block 0 of a MIFARE PICC."));
bluetooth.begin(BAUD_RATE);
delay(100);
Serial.println("setup complete");
}
void dump_byte_array(byte *buffer, byte bufferSize) {
for (byte i = 0; i < bufferSize; i++) {
Serial.print(buffer[i] < 0x10 ? " 0" : " ");
Serial.print(buffer[i], HEX);
}
}
bool try_key(MFRC522::MIFARE_Key *key)
{
bool result = false;
byte buffer[18];
byte block = 0;
MFRC522::StatusCode status;
// Serial.println(F("Authenticating using key A..."));
status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, key, &(mfrc522.uid));
if (status != MFRC522::STATUS_OK) {
// Serial.print(F("PCD_Authenticate() failed: "));
// Serial.println(mfrc522.GetStatusCodeName(status));
return false;
}
// Read block
byte byteCount = sizeof(buffer);
status = mfrc522.MIFARE_Read(block, buffer, &byteCount);
if (status != MFRC522::STATUS_OK) {
// Serial.print(F("MIFARE_Read() failed: "));
// Serial.println(mfrc522.GetStatusCodeName(status));
}
else {
// Successful read
result = true;
Serial.print(F("Success with key:"));
dump_byte_array((*key).keyByte, MFRC522::MF_KEY_SIZE);
Serial.println();
// Dump block data
Serial.print(F("Block ")); Serial.print(block); Serial.print(F(":"));
dump_byte_array(buffer, 16);
Serial.println();
}
Serial.println();
mfrc522.PICC_HaltA(); // Halt PICC
mfrc522.PCD_StopCrypto1(); // Stop encryption on PCD
return result;
}
void loop() {
button = phone.getButton();
// Returns the text data sent from the phone.
// After it returns the latest data, empty string "" is sent in subsequent.
// calls until text data is sent again.
String str = phone.getText();
// Display button data whenever its pressed.
if (button == 1) {
Serial.print("Door Locked");
}
// Display button data whenever its pressed.
if (button == 0) {
Serial.print("Door Unlocked");
int motorPin = 3;
digitalWrite(motorPin, HIGH); // turns the motor ON
delay(5000);
digitalWrite(motorPin, LOW); // turns the motor OFF
}
// Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
if ( ! mfrc522.PICC_IsNewCardPresent())
return;
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial())
return;
// Show some details of the PICC (that is: the tag/card)
bool locked = false;
if(locked == false)
{
Serial.print(F("Card UID:"));
dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
byte valid[4] = { 0xEB, 0xA6, 0xE9, 0x21 };
if (memcmp(valid, mfrc522.uid.uidByte, mfrc522.uid.size) == 0) {
Serial.print("Door Locked");
int motorPin = 3;
digitalWrite(motorPin, HIGH); // turns the motor ON
delay(5000);
digitalWrite(motorPin, LOW); // turns the motor OFF
bool locked = true;
}}
if(locked == true)
{
Serial.print(F("Card UID:"));
dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
byte valid[4] = { 0xEB, 0xA6, 0xE9, 0x21 };
if (memcmp(valid, mfrc522.uid.uidByte, mfrc522.uid.size) == 0) {
Serial.print("Door Unlocked");
int motorPin = 3;
digitalWrite(motorPin, HIGH); // turns the motor ON
delay(5000);
digitalWrite(motorPin, LOW); // turns the motor OFF
bool locked = false;
}}
Serial.println();
Serial.print(F("PICC type: "));
MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
Serial.println(mfrc522.PICC_GetTypeName(piccType));
// Try the known default keys
MFRC522::MIFARE_Key key;
for (byte k = 0; k < NR_KNOWN_KEYS; k++) {
// Copy the known key into the MIFARE_Key structure
for (byte i = 0; i < MFRC522::MF_KEY_SIZE; i++) {
key.keyByte[i] = knownKeys[k][i];
}
// Try the key
if (try_key(&key)) {
// Found and reported on the key and block,
// no need to try other keys for this PICC
break;
}
// http://arduino.stackexchange.com/a/14316
if ( ! mfrc522.PICC_IsNewCardPresent())
break;
if ( ! mfrc522.PICC_ReadCardSerial())
break;
}
}
Within the scope of your if-statements you create another local variable bool locked
and you do not reassign the one which is used for checking the current state.
So without deeper looking on the rest of the code you need to assign locked with the proper value instead of defining another locked-variable:
locked = false;
instead of
bool locked = false;
Clarification:
int a = 0;
if (1)
{
int a = 42; // this is not 'a' from above
std::cout << "value of a: " << a << "\n";
} // here ends the lifetime of the inner 'a'
std::cout << "value of a: " << a << "\n";
Output:
value of a: 42
value of a: 0
I would like to merge two pieces of code and I'm not sure how I should go about it. The first code is for Bluetooth and the second is for an NFC reader. By simply just adding the script the bottom of the other it gives me the error 'Serial' does not name a type. Although it runs perfectly fine on its own. They both need to be running at the same time as well. Any thoughts?
Bluetooth
#include <SoftwareSerial.h>
#include <ArduinoBlue.h>
const unsigned long BAUD_RATE = 9600;
// The bluetooth tx and rx pins must be supported by software serial.
// Visit https://www.arduino.cc/en/Reference/SoftwareSerial for unsupported pins.
// Bluetooth TX -> Arduino D8
const int BLUETOOTH_TX = 8;
// Bluetooth RX -> Arduino D7
const int BLUETOOTH_RX = 7;
int prevThrottle = 49;
int prevSteering = 49;
int throttle, steering, sliderVal, button, sliderId;
SoftwareSerial bluetooth(BLUETOOTH_TX, BLUETOOTH_RX);
ArduinoBlue phone(bluetooth); // pass reference of bluetooth object to ArduinoBlue constructor
// Setup code runs once after program starts.
void setup() {
// Start serial communications.
// The baud rate must be the same for both the serial and the bluetooth.
Serial.begin(BAUD_RATE);
bluetooth.begin(BAUD_RATE);
delay(100);
Serial.println("setup complete");
}
// Put your main code here, to run repeatedly:
void loop() {
// ID of the button pressed pressed.
button = phone.getButton();
// Returns the text data sent from the phone.
// After it returns the latest data, empty string "" is sent in subsequent.
// calls until text data is sent again.
String str = phone.getText();
// Display button data whenever its pressed.
if (button == 1) {
Serial.print("Door Locked");
}
// Display button data whenever its pressed.
if (button == 0) {
Serial.print("Door Unlocked");
}
}
NFC
#include <SPI.h>
#include <MFRC522.h>
#define RST_PIN 9 // Configurable, see typical pin layout above
#define SS_PIN 10 // Configurable, see typical pin layout above
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
// Number of known default keys (hard-coded)
// NOTE: Synchronize the NR_KNOWN_KEYS define with the defaultKeys[] array
#define NR_KNOWN_KEYS 8
// Known keys, see: https://code.google.com/p/mfcuk/wiki/MifareClassicDefaultKeys
byte knownKeys[NR_KNOWN_KEYS][MFRC522::MF_KEY_SIZE] = {
{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, // FF FF FF FF FF FF = factory default
{0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5}, // A0 A1 A2 A3 A4 A5
{0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5}, // B0 B1 B2 B3 B4 B5
{0x4d, 0x3a, 0x99, 0xc3, 0x51, 0xdd}, // 4D 3A 99 C3 51 DD
{0x1a, 0x98, 0x2c, 0x7e, 0x45, 0x9a}, // 1A 98 2C 7E 45 9A
{0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7}, // D3 F7 D3 F7 D3 F7
{0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}, // AA BB CC DD EE FF
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00} // 00 00 00 00 00 00
};
/*
* Initialize.
*/
void setup() {
Serial.begin(9600); // Initialize serial communications with the PC
while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522 card
Serial.println(F("Try the most used default keys to print block 0 of a MIFARE PICC."));
}
/*
* Helper routine to dump a byte array as hex values to Serial.
*/
void dump_byte_array(byte *buffer, byte bufferSize) {
for (byte i = 0; i < bufferSize; i++) {
Serial.print(buffer[i] < 0x10 ? " 0" : " ");
Serial.print(buffer[i], HEX);
}
}
/*
* Try using the PICC (the tag/card) with the given key to access block 0.
* On success, it will show the key details, and dump the block data on Serial.
*
* #return true when the given key worked, false otherwise.
*/
bool try_key(MFRC522::MIFARE_Key *key)
{
bool result = false;
byte buffer[18];
byte block = 0;
MFRC522::StatusCode status;
// Serial.println(F("Authenticating using key A..."));
status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, key, &(mfrc522.uid));
if (status != MFRC522::STATUS_OK) {
// Serial.print(F("PCD_Authenticate() failed: "));
// Serial.println(mfrc522.GetStatusCodeName(status));
return false;
}
// Read block
byte byteCount = sizeof(buffer);
status = mfrc522.MIFARE_Read(block, buffer, &byteCount);
if (status != MFRC522::STATUS_OK) {
// Serial.print(F("MIFARE_Read() failed: "));
// Serial.println(mfrc522.GetStatusCodeName(status));
}
else {
// Successful read
result = true;
Serial.print(F("Success with key:"));
dump_byte_array((*key).keyByte, MFRC522::MF_KEY_SIZE);
Serial.println();
// Dump block data
Serial.print(F("Block ")); Serial.print(block); Serial.print(F(":"));
dump_byte_array(buffer, 16);
Serial.println();
}
Serial.println();
mfrc522.PICC_HaltA(); // Halt PICC
mfrc522.PCD_StopCrypto1(); // Stop encryption on PCD
return result;
}
/*
* Main loop.
*/
void loop() {
// Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
if ( ! mfrc522.PICC_IsNewCardPresent())
return;
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial())
return;
// Show some details of the PICC (that is: the tag/card)
Serial.print(F("Card UID:"));
dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
Serial.println();
Serial.print(F("PICC type: "));
MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
Serial.println(mfrc522.PICC_GetTypeName(piccType));
// Try the known default keys
MFRC522::MIFARE_Key key;
for (byte k = 0; k < NR_KNOWN_KEYS; k++) {
// Copy the known key into the MIFARE_Key structure
for (byte i = 0; i < MFRC522::MF_KEY_SIZE; i++) {
key.keyByte[i] = knownKeys[k][i];
}
// Try the key
if (try_key(&key)) {
// Found and reported on the key and block,
// no need to try other keys for this PICC
break;
}
// http://arduino.stackexchange.com/a/14316
if ( ! mfrc522.PICC_IsNewCardPresent())
break;
if ( ! mfrc522.PICC_ReadCardSerial())
break;
}
}
Merged Code (with error 'Serial' does not name a type.)
#include <SoftwareSerial.h>
#include <ArduinoBlue.h>
#include <SPI.h>
#include <MFRC522.h>
const unsigned long BAUD_RATE = 9600;
// The bluetooth tx and rx pins must be supported by software serial.
// Visit https://www.arduino.cc/en/Reference/SoftwareSerial for unsupported pins.
// Bluetooth TX -> Arduino D8
const int BLUETOOTH_TX = 8;
// Bluetooth RX -> Arduino D7
const int BLUETOOTH_RX = 7;
int prevThrottle = 49;
int prevSteering = 49;
int throttle, steering, sliderVal, button, sliderId;
SoftwareSerial bluetooth(BLUETOOTH_TX, BLUETOOTH_RX);
ArduinoBlue phone(bluetooth); // pass reference of bluetooth object to ArduinoBlue constructor
// Setup code runs once after program starts.
void setup() {
// Start serial communications.
// The baud rate must be the same for both the serial and the bluetooth.
Serial.begin(BAUD_RATE);
bluetooth.begin(BAUD_RATE);
delay(100);
Serial.println("setup complete");
}
// Put your main code here, to run repeatedly:
void loop() {
// ID of the button pressed pressed.
button = phone.getButton();
// Returns the text data sent from the phone.
// After it returns the latest data, empty string "" is sent in subsequent.
// calls until text data is sent again.
String str = phone.getText();
// Display button data whenever its pressed.
if (button == 1) {
Serial.print("Door Locked");
}
// Display button data whenever its pressed.
if (button == 0) {
Serial.print("Door Unlocked");
}
}
#define RST_PIN 9 // Configurable, see typical pin layout above
#define SS_PIN 10 // Configurable, see typical pin layout above
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.
// Number of known default keys (hard-coded)
// NOTE: Synchronize the NR_KNOWN_KEYS define with the defaultKeys[] array
#define NR_KNOWN_KEYS 8
// Known keys, see: https://code.google.com/p/mfcuk/wiki/MifareClassicDefaultKeys
byte knownKeys[NR_KNOWN_KEYS][MFRC522::MF_KEY_SIZE] = {
{0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, // FF FF FF FF FF FF = factory default
{0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5}, // A0 A1 A2 A3 A4 A5
{0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5}, // B0 B1 B2 B3 B4 B5
{0x4d, 0x3a, 0x99, 0xc3, 0x51, 0xdd}, // 4D 3A 99 C3 51 DD
{0x1a, 0x98, 0x2c, 0x7e, 0x45, 0x9a}, // 1A 98 2C 7E 45 9A
{0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7}, // D3 F7 D3 F7 D3 F7
{0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}, // AA BB CC DD EE FF
{0x00, 0x00, 0x00, 0x00, 0x00, 0x00} // 00 00 00 00 00 00
};
/*
* Initialize.
*/
Serial.begin(9600); // Initialize serial communications with the PC
while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522 card
Serial.println(F("Try the most used default keys to print block 0 of a MIFARE PICC."));
}
/*
* Helper routine to dump a byte array as hex values to Serial.
*/
void dump_byte_array(byte *buffer, byte bufferSize) {
for (byte i = 0; i < bufferSize; i++) {
Serial.print(buffer[i] < 0x10 ? " 0" : " ");
Serial.print(buffer[i], HEX);
}
}
/*
* Try using the PICC (the tag/card) with the given key to access block 0.
* On success, it will show the key details, and dump the block data on Serial.
*
* #return true when the given key worked, false otherwise.
*/
bool try_key(MFRC522::MIFARE_Key *key)
{
bool result = false;
byte buffer[18];
byte block = 0;
MFRC522::StatusCode status;
// Serial.println(F("Authenticating using key A..."));
status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, key, &(mfrc522.uid));
if (status != MFRC522::STATUS_OK) {
// Serial.print(F("PCD_Authenticate() failed: "));
// Serial.println(mfrc522.GetStatusCodeName(status));
return false;
}
// Read block
byte byteCount = sizeof(buffer);
status = mfrc522.MIFARE_Read(block, buffer, &byteCount);
if (status != MFRC522::STATUS_OK) {
// Serial.print(F("MIFARE_Read() failed: "));
// Serial.println(mfrc522.GetStatusCodeName(status));
}
else {
// Successful read
result = true;
Serial.print(F("Success with key:"));
dump_byte_array((*key).keyByte, MFRC522::MF_KEY_SIZE);
Serial.println();
// Dump block data
Serial.print(F("Block ")); Serial.print(block); Serial.print(F(":"));
dump_byte_array(buffer, 16);
Serial.println();
}
Serial.println();
mfrc522.PICC_HaltA(); // Halt PICC
mfrc522.PCD_StopCrypto1(); // Stop encryption on PCD
return result;
}
void loop() {
// Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
if ( ! mfrc522.PICC_IsNewCardPresent())
return;
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial())
return;
// Show some details of the PICC (that is: the tag/card)
Serial.print(F("Card UID:"));
dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
Serial.println();
Serial.print(F("PICC type: "));
MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
Serial.println(mfrc522.PICC_GetTypeName(piccType));
// Try the known default keys
MFRC522::MIFARE_Key key;
for (byte k = 0; k < NR_KNOWN_KEYS; k++) {
// Copy the known key into the MIFARE_Key structure
for (byte i = 0; i < MFRC522::MF_KEY_SIZE; i++) {
key.keyByte[i] = knownKeys[k][i];
}
// Try the key
if (try_key(&key)) {
// Found and reported on the key and block,
// no need to try other keys for this PICC
break;
}
// http://arduino.stackexchange.com/a/14316
if ( ! mfrc522.PICC_IsNewCardPresent())
break;
if ( ! mfrc522.PICC_ReadCardSerial())
break;
}
}
The error appears because the following lines are not inside a function declaration. The compiler is expecting a variable declaration and instead sees the call to Serial.begin(). To fix that problem, move these lines into the setup() function from where they currently are:
Serial.begin(9600); // Initialize serial communications with the PC
while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
SPI.begin(); // Init SPI bus
mfrc522.PCD_Init(); // Init MFRC522 card
Serial.println(F("Try the most used default keys to print block 0 of a MIFARE PICC."));
Of course, there should be only one Serial.begin() call in your setup() function, not two, and, as a commenter pointed out, you should merge the code from your two loop() functions into a single loop() function.
we're making keyboard with five sensor and we have problem with mojibake
if we click sensor 'a' five time, there should be five 'ㄱ'
but there are mojibake like attached picture.
we think this problem is related with unicode but can't find what the exact probelm is
please answer what is problem. thank you
#include <SoftwareSerial.h>
#include<Wire.h>
#define BT_RXD 8
#define BT_TXD 7
SoftwareSerial bluetooth(BT_RXD, BT_TXD);
int SensorPin1 = A0;
int SensorPin2 = A1;
int SensorPin3 = A2;
int SensorPin4 = A3;
int SensorPin5 = A4;
const int MPU_addr=0x68;
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;
void setup()
{
Wire.begin();
Wire.beginTransmission(MPU_addr);
Wire.write(0x6B);
Wire.write(0);
Wire.endTransmission(true);
Serial.begin(9600);
bluetooth.begin(9600);
}
void loop()
{
int SensorReading1 = analogRead(SensorPin1);
int SensorReading2 = analogRead(SensorPin2);
int SensorReading3 = analogRead(SensorPin3);
int SensorReading4 = analogRead(SensorPin4);
int SensorReading5 = analogRead(SensorPin5);
int FSR1 = map(SensorReading1, 0, 1024, 0, 255);
int FSR2 = map(SensorReading2, 0, 1024, 0, 255);
int FSR3 = map(SensorReading3, 0, 1024, 0, 255);
int FSR4 = map(SensorReading4, 0, 1024, 0, 255);
int FSR5 = map(SensorReading5, 0, 1024, 0, 255);
Wire.beginTransmission(MPU_addr); //-32768~32767
Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H)
Wire.endTransmission(false);
Wire.requestFrom(MPU_addr,14,true); // request a total of 14 registers
AcX=Wire.read() << 8|Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
AcY=Wire.read() << 8|Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
AcZ=Wire.read() << 8|Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
Tmp=Wire.read() << 8|Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
GyX=Wire.read() << 8|Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
GyY=Wire.read() << 8|Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
GyZ=Wire.read() << 8|Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
Serial.print("AcX = "); Serial.print(AcX);
Serial.print(" | AcY = "); Serial.print(AcY);
Serial.print(" | AcZ = "); Serial.println(AcZ);
//Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53); //equation for temperature in degrees C from datasheet
//Serial.print(" | GyX = "); Serial.print(GyX);
//Serial.print(" | GyY = "); Serial.print(GyY);
//Serial.print(" | GyZ = "); Serial.println(GyZ);
if(FSR1 > 100)
{
//Serial.println("ㄱ");
bluetooth.write("ㄱ");
}
if(FSR2 > 100)
{
//Serial.println("ㄱ");
bluetooth.write(FSR2);
}
if(FSR3 > 100)
{
//Serial.println("ㄱ");
}
if(FSR4 > 100)
{
//Serial.println("2");
}
if(FSR5 > 100)
{
//Serial.println("ㄱ");
bluetooth.write("ㄱ");
}
if (bluetooth.available())
{
//Serial.write(bluetooth.read());
}
if (Serial.available())
{
//bluetooth.write(FSR);
}
delay(333);
}
What you are sending is bytes, and the exact bytes you are sending depends on the encoding of your editor. When your capston application receives those bytes, it tries to interpret them according to the encoding of capston. No idea what it might be. In any case, what you need to do is to send utf-8 data from the arduino, and ensure that the capston application decodes utf-8 data.
I have been trying to send messages via MQTT from my Arduino to my amazon web server. The following code connects the ethernet client but not the MQTT client. Why would my MQTT client not be connecting?
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
byte mac[] = { 0x12, 0x42, 0x98, 0x85, 0x49, 0x3A }; //MAC address of server
char server[] = "http://52.1.29.117/"; //web address of server
IPAddress ip(172, 31, 51, 13); //IP address of server
void callback(char* topic, byte* payload, unsigned int length) {
// handle message arrived
}
EthernetClient ethClient;
PubSubClient client(server, 80, callback, ethClient);
void setup()
{
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// start the Ethernet connection:
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
Ethernet.begin(mac, ip);
}
delay(1000);
Serial.println("connecting...");
if (ethClient.connect(server, 80)) {
Serial.println("connected");
// Make a HTTP request:
ethClient.println("GET /search?q=arduino HTTP/1.1");
ethClient.println("Host: www.google.com");
ethClient.println("Connection: close");
ethClient.println();
}
else {
Serial.println("connection failed");
}
// if (client.connect(server)) {
if (client.connect(server, "ubuntu", "")) {
Serial.print("Data sent/n");
client.publish("hello/world","hello world");
client.subscribe("hiWorld");
}
else {
Serial.print("nope");
}
}
void loop()
{
client.loop();
}
IIRC AWS only opens a couple of specific ports, this may help you open up some more:
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/authorizing-access-to-an-instance.html
I'm trying to send some http requests from Arduino to my server.
My code can upload once, but is disconnecting after uploading first time.
Any idea how I can modify my code so the Arduino will send a http request every 2-3 second?
Here is my code:
#include <SPI.h>
#include <Ethernet.h>
int counter = 0;
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress server(xxx, xx, xx, xx);
IPAddress ip(192, 168, 1, 1);
EthernetClient client;
void setup() { //connect to server
Serial.begin(9600);
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
Ethernet.begin(mac, ip);
}
// give the Ethernet shield a second to initialize:
delay(1000);
Serial.println("connecting...");
connect();
}
void loop()
{
send(counter);
delay(1000);
// if there are incoming bytes available
// from the server, read them and print them:
if (client.available()) {
char c = client.read();
Serial.print(c);
}
// if the server's disconnected, stop the client:
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
// do nothing forevermore:
while(true);
}
counter++;
}
void connect(){
// if you get a connection, report back via serial:
client.connect(server, 80);
Serial.println("CONNECTED");
delay(1000);
}
void send(int value){
// Make a HTTP request:
client.print("GET /arduino.php?rom=D201");
client.print("&count=");
client.print(value);
client.println(" HTTP/1.0");
client.println("Host: 158.36.70.36");
client.println("Connection: close");
client.println();
Serial.print("Sending value");
Serial.println(value);
}
This Web client sketch has been tested and works flawlessly.
#include <SPI.h>
#include <Ethernet.h>
// this must be unique
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// change to your network settings
IPAddress ip(192,168,2,2);
IPAddress gateway(192, 168, 2, 1);
IPAddress subnet(255, 255, 255, 0);
// change to your server
IPAddress server(74,125,227,16); // Google
//Change to your domain name for virtual servers
char serverName[] = "www.google.com";
// If no domain name, use the ip address above
// char serverName[] = "74.125.227.16";
// change to your server's port
int serverPort = 80;
EthernetClient client;
int totalCount = 0;
char pageAdd[64];
// set this to the number of milliseconds delay
// this is 30 seconds
#define delayMillis 30000UL
unsigned long thisMillis = 0;
unsigned long lastMillis = 0;
void setup() {
Serial.begin(9600);
// disable SD SPI
pinMode(4,OUTPUT);
digitalWrite(4,HIGH);
// Start ethernet
Serial.println(F("Starting ethernet..."));
Ethernet.begin(mac, ip, gateway, gateway, subnet);
// If using dhcp, comment out the line above
// and uncomment the next 2 lines
// if(!Ethernet.begin(mac)) Serial.println(F("failed"));
// else Serial.println(F("ok"));
Serial.println(Ethernet.localIP());
delay(2000);
Serial.println(F("Ready"));
}
void loop()
{
thisMillis = millis();
if(thisMillis - lastMillis > delayMillis)
{
lastMillis = thisMillis;
// Modify next line to load different page
// or pass values to server
sprintf(pageAdd,"/",totalCount);
// sprintf(pageAdd,"/arduino.php?test=%u",totalCount);
if(!getPage(server,serverPort,pageAdd)) Serial.print(F("Fail "));
else Serial.print(F("Pass "));
totalCount++;
Serial.println(totalCount,DEC);
}
}
byte getPage(IPAddress ipBuf,int thisPort, char *page)
{
int inChar;
char outBuf[128];
Serial.print(F("connecting..."));
if(client.connect(ipBuf,thisPort) == 1)
{
Serial.println(F("connected"));
sprintf(outBuf,"GET %s HTTP/1.1",page);
client.println(outBuf);
sprintf(outBuf,"Host: %s",serverName);
client.println(outBuf);
client.println(F("Connection: close\r\n"));
}
else
{
Serial.println(F("failed"));
return 0;
}
// connectLoop controls the hardware fail timeout
int connectLoop = 0;
while(client.connected())
{
while(client.available())
{
inChar = client.read();
Serial.write(inChar);
// set connectLoop to zero if a packet arrives
connectLoop = 0;
}
connectLoop++;
// if more than 10000 milliseconds since the last packet
if(connectLoop > 10000)
{
// then close the connection from this end.
Serial.println();
Serial.println(F("Timeout"));
client.stop();
}
// this is a delay for the connectLoop timing
delay(1);
}
Serial.println();
Serial.println(F("disconnecting."));
// close client end
client.stop();
return 1;
}
If for some reason it keeps hanging, you can implement a watchdog timer mechanism. For more info about WDT on ATmega328P Datasheet.
I have an example from one of my projects:
void watchdogSetup(void) {
cli(); // disable all interrupts
wdt_reset(); // reset the WDT timer
/*
WDTCSR configuration:
WDIE = 1: Interrupt Enable
WDE = 1 :Reset Enable
WDP3 = 0 :For 2000ms Time-out
WDP2 = 1 :For 2000ms Time-out
WDP1 = 1 :For 2000ms Time-out
WDP0 = 1 :For 2000ms Time-out
*/
// Enter Watchdog Configuration mode:
WDTCSR |= (1<<WDCE) | (1<<WDE); //x |= y is the same as x = x | y
// Set Watchdog settings:
WDTCSR = (1<<WDIE) | (1<<WDE) | (0<<WDP3) | (1<<WDP2) | (1<<WDP1) | (1<<WDP0);
sei();
}
ISR(WDT_vect){// Watchdog timer interrupt.
digitalWrite(ETHERNET_SHIELD_RESET_PIN, LOW);
}