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.
Related
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");
}
//----------------------------------------------------------------------------
}
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.
I am writing a program to access WHO_AM_I registers on Accelerometer and Gyroscope via i2c on beaglebone black. Here is the basic code.`
int main(void)
{
char rxBuffer[40];
char txBuffer[32];
int gyroAddress = 0x20;
int acceleroAddress = 0x1e;
int tenBitAddress = 0;
int opResult = 0;
int i2cFD = open("/dev/i2c-1",O_RDWR);
opResult = ioctl(i2cFD, I2C_TENBIT, tenBitAddress);
opResult = ioctl(i2cFD,I2C_SLAVE, acceleroAddress);
memset(rxBuffer, 0, sizeof(rxBuffer));
memset(txBuffer, 0, sizeof(txBuffer));
txBuffer[0] = 0x0D;
opResult = write(i2cFD, txBuffer, 1);
if (opResult !=1) printf("No ACK bit!\n");
opResult = read(i2cFD, rxBuffer, 1);
printf("Part ID: %d\n", (int)rxBuffer[0]);
//for gyro
opResult = ioctl(i2cFD, I2C_SLAVE, gyroAddress);
txBuffer[0] = 0x0C;
opResult = write(i2cFD, txBuffer, 1);
if (opResult != 1) printf("No ACK bit!\n");
opResult = read(i2cFD, rxBuffer, 1);
printf("Part ID: %d\n", (int)rxBuffer[0]);
}
`
I get Part ID for both as zero but when I probe the sensor using i2cget commands it gives me the expected "0xC7" value. Any idea what I am doing wrong?
I have a Visual Studio 2008 C++ project where I need to decode a 6-byte array of data in to a structure.
My thought was to do something like this:
#pragma pack( push, 1 )
struct Map
{
BYTE alpha : 8;
BYTE bravo : 8;
UINT charlie : 24;
BYTE delta : 8;
BYTE padding0 : 8; // ensure correct byte boundary
BYTE padding1 : 8;
};
#pragma pack( pop )
// sizeof( Map ) == 8 bytes
BYTE test_data[ 6 ] = { 0x07, // alpha
0x0B, // bravo
0x00, // charlie high byte
0x00, // charlie med byte
0x01, // charlie low byte
0x33 }; // delta
Map map = { };
memcpy( &map, test_data, sizeof( test_data ) );
ASSERT( map.alpha == 0x07 );
ASSERT( map.bravo == 0x0B );
ASSERT( map.charlie == 0x01 );
ASSERT( map.delta == 0x33 );
But, the data in charlie and delta is never correct.
Is there a way to structure my struct to get this correct or am I stuck setting each field individually?
Thanks
To do this in a portable way:
struct Map
{
BYTE alpha;
BYTE bravo;
UINT charlie;
BYTE delta;
Map(const BYTE data[6])
: alpha(data[0])
, bravo(data[1])
, charlie((data[2] << 16) | (data[3] << 8) | data[4])
, delta(data[5])
{}
};
int main()
{
BYTE test_data[ 6 ] = { 0x07, // alpha
0x0B, // bravo
0x00, // charlie high byte
0x00, // charlie med byte
0x01, // charlie low byte
0x33 }; // delta
Map map(test_data);
ASSERT( map.alpha == 0x07 );
ASSERT( map.bravo == 0x0B );
ASSERT( map.charlie == 0x01 );
ASSERT( map.delta == 0x33 );
}
You cannot serialize compound types naively. Just write it yourself:
std::tuple<char, char, unsigned int, char>
parse(char const * buf)
{
return std::make_tuple(buf[0],
buf[1],
buf[2] + 256 * buf[3] + 256 * 256 * buf[4],
buf[5]);
}
Of course you have to match the endianness of the integer to that which is documented by your serialized format, little-endian in my example.