my esp8266 is printing out a ton of gibberish - arduino

my esp8266 seems to be printing out a ton of memory locations to the serial monitor on arduino. my code mainly takes a post request from an android app and uses the string to execute respective blocks of code like setting and entering password.
this is my code
*i initialized some declarations for testing so i dont have to use my android phone and can just test my functions by setting variables.
#include <base64.h>
#include <xbase64.h>
#include <AES.h>
#include <AESLib.h>
#include <AES_config.h>
#include <base64.h>
#include <ESP8266WebServer.h>
#include <Servo.h>
#include <Keypad.h>
#define SOUND_VELOCITY 0.034
#define CM_TO_INCH 0.393701
const byte ROWS = 3;
const byte COLS = 3;
char keys[ROWS][COLS] = {
{'1','2','3'},
{'4','5','6'},
{'7','8','9'}
};
byte rowPins[ROWS] = { D3, D2, D1};
byte colPins[COLS] = { D7, D6, D5};
const char* ssid = "ESP8266-AP";
const char* passwordd = "password";
const int trigPin=D4;
const int echoPin=D0;
const float DISTANCE_THRESHOLD = 20;
long duration;
float distanceCm;
float distanceInch;
String tempString;
String pass;
char keyp;
String newString = "1020"; //change to 0102 to test other case
Keypad pad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
String password = "0000"; //variable to store the password, default=0000
String input = ""; //variable to store the input
bool setPass = false; //variable to track if the user is setting the password
bool passwordSet = false; //variable to track if the password has been set
bool unlocked = false; //variable to track if the system is unlocked
bool doorOpen = false;
bool isPostHandled = true;
int openClose = 0;
const byte key[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };
ESP8266WebServer server(80);
AES aes;
Servo myservo;
void handlePost() {
String val = server.arg("data");
int decodedLength = base64_dec_len(val.c_str(), val.length());
char decodedData[decodedLength];
base64_decode(decodedData, val.c_str(), val.length());
byte decrypted[decodedLength];
aes.set_key(key, sizeof(key));
aes.decrypt((byte*)decodedData, decrypted);
String decryptedVal = String((char*)decrypted);
for(int i=0; i<4; i++){
tempString[i]=decryptedVal[i];
}
newString = String(tempString);
//Serial.println("Encrypted value: " + val);
//Serial.println("Decrypted value: " + decryptedVal);
server.send(200, "text/plain", "Value Received");
isPostHandled = true;
}
/*void moveServo() {
myservo.write(0);
delay(1000);
int count = 0;
myservo.write(180);
} */
//move servo, pass argument to control degrees
void moveServo(int position) {
myservo.write(position);
delay(1000);
}
float calculateDistance() {
// Trigger the ultrasonic sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
// Measure the echo return time and calculate the distance
duration = pulseIn(echoPin, HIGH);
float distanceCm = (duration / 2) * SOUND_VELOCITY;
float distanceInch = distanceCm * CM_TO_INCH;
return distanceInch;
}
void setup() {
float duration, distanceCm, distanceInch;
//esp declaration
Serial.begin(9600);
WiFi.mode(WIFI_AP);
WiFi.softAP(ssid, passwordd);
server.begin();
server.on("/post", HTTP_POST, handlePost);
Serial.println("Server started");
//servo motor declaration
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
myservo.attach(D8);
myservo.write(180); // set the servo to 0 degrees
}
void loop() {
server.handleClient();
float distance = calculateDistance();
if((distance < 20) && (openClose == 0)){
doorOpen = true;
}
if ((distance < 20) && (openClose == 1)) {
doorOpen = false;
}
if(isPostHandled){
if(newString == "0102"){
do{
password = ""; //set password to a null string
Serial.println("Please set 4 digit passcode");
for(int i=0; i<4; i++){
keyp = pad.getKey();
if (keyp != NO_KEY) {
password += keyp; //add the key press to the password
Serial.print("*"); //print a * to indicate a key press
}
if (password.length() == 4) { //if the password is the same length as desired
Serial.println("Password set: " + password);
passwordSet = true;
moveServo(0);
break;
}
}
}while(!passwordSet);
newString = "";
}
else if(newString == "1020"){
input = "";
Serial.println("Please enter passcode");
do{
for(int i=0; i<4; i++){
keyp = pad.getKey();
if (keyp != NO_KEY) {
input += keyp; //add the key press to the input
Serial.print("*"); //print a * to indicate a key press
}
}
}while(!unlocked && (input.length() != 4));
if (input == password) { //if the input is the same length as the password
delay(1000);
Serial.println("Unlocked");
moveServo(0); //unlock
unlocked = true;
}else{
Serial.println("Access Denied, Wrong password");
return;
}
}
}
else{
Serial.print("isPostHandled = false");
return;
}
}
and this is the output
3fffff40: 00000000 00001113 39999999 0013be3a
3fffff50: 3ffe8a32 fffffffc 3fff019c 3ffefe98
3fffff60: 3ffeffc0 00000002 3ffefeb0 40205875
3fffff70: 3fffdad0 00000002 3ffefeb0 402058be
3fffff80: 3fffdad0 00000000 3fff001c 40203919
3fffff90: 3ffefc68 3ffefff8 00000001 40205522
3fffffa0: 00000000 00000000 3ffefc68 3fff0108
3fffffb0: 3fffdad0 00000000 3fff00dc 40208560
3fffffc0: feefeffe feefeffe 3fffdab0 401012b9
<<<stack<<<
--------------- CUT HERE FOR EXCEPTION DECODER ---------------
���u�����Server started
Please enter passcode
i tried changing serial baud rate and i cant really find anything related to what i am facing on the internet

Related

How to call more than one web service in Arduino/Galileo Gen 2

I'm working on Galileo gen 2;
And I'm trying to use the following two web services:
POST /dashboard/read_write_ard.php?temp="+tempValue
POST /dashboard/appinsert.php?valeur="+tempValue
The first one inserts into table one...
and the second one will be used only if (tempValue < 24).
This is my code so far:
#include <SPI.h>
#include <Ethernet.h>
#include <Wire.h>
#include "rgb_lcd.h"
rgb_lcd lcd;
const int pinLight = A1;
const int pinLed = 13;
const int thresholdvalue = 400;
const int idealLightValue = 400 ;
const int pinTemp = A0;
const int B = 3975;
int etat=0;
const int pinSound = A2;
byte mac[] = {
0x98, 0x4F, 0xEE, 0x05, 0x37, 0x33
};//adress mac du carte
EthernetClient client;
IPAddress server(192,168, 1,7);
void setup() {
Serial.begin(9600);
pinMode(pinLed, OUTPUT);
lcd.begin(16, 2);
delay(1000);
system("ifup eth0");
if (Ethernet.begin(mac) == 0) {
Serial.println("\nFailed to configure Ethernet using DHCP");
delay(500);
}
delay(1000);
Serial.println(Ethernet.localIP());
}
void loop() {
system("ifup eth0");
digitalWrite(pinLed, HIGH);
lcd.print("Starting to loop ");
delay(1000);
lcd.clear();
int TempSensorValue = analogRead(pinTemp);
int LightSensorValue = analogRead(pinLight);
int SoundSensorValue = analogRead(pinSound);
float resistance = (float)(1023-TempSensorValue)*10000/TempSensorValue;
int temperature = 1/(log(resistance/10000)/B+1/298.15)-273.15;
Serial.println( temperature);
Serial.println(SoundSensorValue);
Serial.println( LightSensorValue);
delay(1000);
String chEtat = "POST /dashboard/read_write_ard.php?temp=";
chEtat += temperature ;
chEtat += "&light=";
chEtat += LightSensorValue;
chEtat +="&sound=";
chEtat +=SoundSensorValue;
if (client.connect(server, 80) ) {
Serial.println("connected");
lcd.print("Connected ");
delay(500);
lcd.clear();
if (temperature <= 40 ){
String chEtat2 = "POST /dashboard/appinsert.php?valeur=";
chEtat2 += temperature ;
chEtat2 += "&type=temperature" ;
client.println(chEtat2);
client.println(chEtat);
}else{
client.println(chEtat);
client.println();
}
}
while (client.available()) {
char c = client.read();
Serial.print(c);
}
if(client.connected()) {
Serial.println();
Serial.println("disconnecting.");
lcd.print("Dissconnecting");
delay(1000);
lcd.clear();
client.stop();
for (;;);
}
}
I have a database containing 2 tables - one for alert values like temperature and the other for normal cases - so I want to put a code when my cart Galileo can add in table 1 : the normal one.
And in case of temperature, let's say more than 24, the value of that temperature will be added to the second table using the web service created for that.
I'd like to know how to get these data soon.

tinkercad arduino lcd is not displaying

How I wanted it to work:
This is a thing that checks temperature and display the temperature and the temperature that I want. You can change the hoping temperature by using the buttons. One is high and the other is low.If the temperature is higher the fan gets on.If the spaeaker rings just once when the temp is higher than what I wanted it to be.
There seems to be no error in the code but the lcd is displaying nothing.
The speaker, TMP, MOTOR seems to be working well which is strange.
Please help me what's wrong.
Code:
*
[//LCD_Thermostat
#include <Wire.h>
#define TEMP_ADDR 72
#include <LiquidCrystal.h>
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
byte degree\[8\] = {
B00110,
B01001,
B01001,
B00110,
B00000,
B00000,
B00000,
B00000,
};
byte fan_on\[8\] = {
B00100,
B10101,
B01110,
B11111,
B01110,
B10101,
B00100,
B00000,
};
byte fan_off\[8\] = {
B00100,
B00100,
B00100,
B11111,
B00100,
B00100,
B00100,
B00000,
};
const int SPEAKER=8;
const int DOWN_BUTTON =9;
const int UP_BUTTON=10;
const int FAN =11;
const int T0=0;
boolean lastDownTempButton = LOW;
boolean currentDownTempButton = LOW;
boolean lastUpTempButton = LOW;
boolean currentUpTempButton = LOW;
int set_temp = 23;
boolean one_time = false;
void setup()
{
pinMode(FAN, OUTPUT);
//Create a wire object for the temp sensor
Wire.begin();
//Set up the LCD's number of columns and rows
lcd.begin(16, 2);
//Make custom characters
lcd.createChar(0, degree);
lcd.createChar(1, fan_off);
lcd.createChar(2, fan_on);
//Print a static message to the LCD
lcd.setCursor(0,0);
lcd.print("Current:");
lcd.setCursor(10,0);
lcd.write((byte)0);
lcd.setCursor(11,0);
lcd.print("C");
lcd.setCursor(0,1);
lcd.print("Set:");
lcd.setCursor(10,1);
lcd.write((byte)0);
lcd.setCursor(11,1);
lcd.print("C");
lcd.setCursor(15,1);
lcd.write(1);
}
boolean debounce(boolean last, int pin)
{
boolean current = digitalRead(pin);
if (last != current)
{
delay(5);
current = digitalRead(pin);
}
return current;
}
void loop()
{/*
Wire.beginTransmission(TEMP_ADDR);
Wire.write(0);
Wire.endTransmission();
Wire.requestFrom(TEMP_ADDR, 1);
while(Wire.available() == 0);
int c = Wire.read();
*/
// for LM35 temperature sensor (Chapter3. 아날로그 신호와 센서값)
int c = analogRead(T0);
c = c*5.0 /1024.0 * 100;
Serial.println(c);
lcd.setCursor(8,0); //Move the cursor
lcd.print(c); //Print this new value
lcd.setCursor(8,0);
lcd.print(c);
currentDownTempButton = debounce(lastDownTempButton, DOWN_BUTTON);
currentUpTempButton = debounce(lastUpTempButton, UP_BUTTON);
if (lastDownTempButton== LOW && currentDownTempButton == HIGH)
{
set_temp--;
}
//Turn up the set temp
else if (lastUpTempButton== LOW && currentUpTempButton == HIGH)
{
set_temp++;
}
//Print the set temp
lcd.setCursor(8,1);
lcd.print(set_temp);
lastDownTempButton = currentDownTempButton;
lastUpTempButton = currentUpTempButton;
if (c >= set_temp)
{
if (!one_time)
{
tone(SPEAKER, 400);
delay(500);
one_time = true;
}
else
{
noTone(SPEAKER);
}
digitalWrite(FAN, HIGH);
lcd.setCursor(15,1);
lcd.write(2);
}
else
{
noTone(SPEAKER);
one_time = false;
digitalWrite(FAN, LOW);
lcd.setCursor(15,1);
lcd.write(1);
}
}][1]
*
Try to use LCD wiring as described in LiquidCristal library, use examples such as HelloWorld.
Here you can find a 'Hello World' example

microphone sph0645 with I2S less sensitive after watchdog sleep with Adafruit Feather M0

I am using the Adafruit Feather M0 RFM69 with the Adafruit I2S MEMS Microphone Breakout SPH0645. Every second I take a reading (sampleRate = 16000, bits per sample = 32) using the I2S library and send it over the radio. This all works fine.
My problem is that, when I want to save power, I am getting weird readings after I wake the board from sleep (using Adafruit_SleepyDog library). The microphone somewhat still works, although it is much less sensitive, only picks up loud sounds and also returns 60dB in a quiet room. When I don't put it to sleep, in the same sound setting, I get 40dB. However, if I put a delay of 250ms after waking up, the microphone works fine again, like before, but this is obviously not saving energy then.
I wonder why this is happening. Is there something I can do to get the microphone to work quicker? I checked the datasheet, but it only says: "When Vdd is applied the microphone senses the
CLOCK line, if the frequency is greater than 900KHz, the microphone enters the normal mode of operation." This should not even take a few ms though?
Thanks in advance
#include <I2S.h>
#include <Adafruit_SleepyDog.h>
#include <SPI.h>
#include <RH_RF69.h>
/************ Radio Setup ***************/
#define RF69_FREQ 433.0
#define SLEEP
//#if defined(ARDUINO_SAMD_FEATHER_M0) // Feather M0 w/Radio
#define RFM69_CS 8
#define RFM69_INT 3
#define RFM69_RST 4
#define LED 13
//#endif
// radio
// Singleton instance of the radio driver
RH_RF69 rf69(RFM69_CS, RFM69_INT);
int transmit_interval = 1000;
int time_counter = 0;
int packetnum = 0;
// MIC
#define SAMPLES 1024//2048 // make it a power of two for best DMA performance
int samples[SAMPLES];
int measurementsdB = 0;
int current_measure;
#define ADC_SOUND_REF 65
#define DB_SOUND_REF 41
int sampleRate1 = 16000;
int bitsPerSample1 = 32;
typedef struct
{
uint8_t measurementdB = 123;
uint8_t battery = 111;
uint8_t test = 222;
} RadioMessage;
RadioMessage struct_message;
void setup()
{
delay(2000); // Wait so its easier to program
Serial.begin(115200);
//while (!Serial) { delay(1); } // wait until serial console is open, remove if not tethered to computer
// Init Mic
if (!I2S.begin(I2S_PHILIPS_MODE, sampleRate1, bitsPerSample1)) {
while (1); // do nothing
}
pinMode(LED, OUTPUT);
digitalWrite(LED, LOW);
pinMode(RFM69_RST, OUTPUT);
digitalWrite(RFM69_RST, LOW);
Serial.println("Feather RFM69 TX Test!");
Serial.println();
// manual reset
digitalWrite(RFM69_RST, HIGH);
delay(10);
digitalWrite(RFM69_RST, LOW);
delay(10);
if (!rf69.init()) {
Serial.println("RFM69 radio init failed");
while (1);
}
Serial.println("RFM69 radio init OK!");
// Defaults after init are 434.0MHz, modulation GFSK_Rb250Fd250, +13dbM (for low power module)
// No encryption
if (!rf69.setFrequency(RF69_FREQ)) {
Serial.println("setFrequency failed");
}
// If you are using a high power RF69 eg RFM69HW, you *must* set a Tx power with the
// ishighpowermodule flag set like this:
rf69.setTxPower(20, true); // range from 14-20 for power, 2nd arg must be true for 69HCW
// The encryption key has to be the same as the one in the server
uint8_t key[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};
rf69.setEncryptionKey(key);
Serial.print("RFM69 radio #"); Serial.print((int)RF69_FREQ); Serial.println(" MHz");
//GCLK->GENCTRL.bit.RUNSTDBY=1; // !! can go
}
void loop() {
Serial.println("START");
///// MIC
//PM->APBCMASK.reg |= PM_APBCMASK_I2S;
int a = 0;
while (a == 0) a = I2S.available();
uint8_t current_measure = sample_audio_signal(samples);
///// RADIO
if (true)//((time_counter + transmit_interval) < millis())
{
struct_message.measurementdB = current_measure;
//struct_message.battery = measuredvbat;
// Send a message!
/*
Serial.print("Array content: ");
uint8_t* bla = (uint8_t*) &struct_message;
for (int i = 0; i < 3; i++)
{
Serial.println(bla[i]);
}*/
rf69.send((const uint8_t*) &struct_message, sizeof(struct_message));
rf69.waitPacketSent();
Serial.print("Wait for reply");
// Now wait for a reply
uint8_t buf[RH_RF69_MAX_MESSAGE_LEN];
uint8_t len = sizeof(buf);
if (rf69.waitAvailableTimeout(100)) {
// Should be a reply message for us now
if (rf69.recv(buf, &len)) {
Serial.print("Got a reply: ");
Serial.println((char*)buf);
} else {
Serial.println("Receive failed");
}
} else {
Serial.println("No reply, is another RFM69 listening?");
}
Serial.println("Radio sleeping");
rf69.sleep();
time_counter = millis();
}
// sleep time
#ifdef SLEEP
int sleepMS = Watchdog.sleep(10);
delay(250);
#else
delay(1000);
#endif
Serial.println("loop ended");
}
void Blink(byte PIN, byte DELAY_MS, byte loops) {
for (byte i=0; i<loops; i++) {
digitalWrite(PIN,HIGH);
delay(DELAY_MS);
digitalWrite(PIN,LOW);
delay(DELAY_MS);
}
}
float sample_audio_signal(int samples[])
{
for (int i=0; i<SAMPLES; i++) {
int sample = 0;
while ((sample == 0) || (sample == -1) ) {
sample = I2S.read();
}
// convert to 18 bit signed
sample >>= 14;
samples[i] = sample;
}
// ok we have the samples, get the mean (avg)
float meanval = 0;
for (int i=0; i<SAMPLES; i++) {
meanval += samples[i];
}
meanval /= SAMPLES;
// subtract it from all samples to get a 'normalized' output
for (int i=0; i<SAMPLES; i++) {
samples[i] -= meanval;
}
// find the 'peak to peak' max
float maxsample, minsample;
minsample = 100000;
maxsample = -100000;
for (int i=0; i<SAMPLES; i++) {
minsample = min(minsample, samples[i]);
maxsample = max(maxsample, samples[i]);
}
int newdB = 20 * log10((float)maxsample / (float)ADC_SOUND_REF) + DB_SOUND_REF;
return newdB;
Ok, the best I got it down to is 3.8mA. I only got so far by leaving the voltage regulator and the internal oscillator (DFLL) on during sleeping.
After adding the following code to my setup routine, when board goes to sleep, the microphone still works after waking up:
SYSCTRL->DFLLCTRL.bit.RUNSTDBY=1;
SYSCTRL->VREG.bit.RUNSTDBY=1;
However, ideally I would like to get much less than that, but then the mic doesn't work...

Send Mirf values with ethercard

I have project where I'm getting data over nRF24L01 and using Mirf to that. Now I'm working for Hub which need to send data to my webservice. For ethernet my choice was ENC28j60 with ethercard library.
Question : How I can wait data from Mirf and just send data forward with Ethercard browseUrl? I can send data without Mirf but there's some loop which I'm not understand.
My code :
#include <SPI.h>
#include <Mirf.h>
#include <nRF24L01.h>
#include <MirfHardwareSpiDriver.h>
#include <EtherCard.h>
// Set network settings
static byte mymac[] = { 0x74, 0x69, 0x69, 0x2D, 0x30, 0x31 };
byte Ethernet::buffer[700];
static uint32_t timer;
// My webservice
const char website[] PROGMEM = "my.webservice.com";
// Mirf variables
int tmpVal1;
// Local components
const int Yellow = 6;
const int Blue = 5;
void setup() {
Serial.begin(57600);
// Setup leds
pinMode(Yellow, OUTPUT);
digitalWrite(Yellow, LOW);
pinMode(Blue, OUTPUT);
digitalWrite(Blue, LOW);
setupMirf();
setupEthernet();
}
void loop() {
// Waiting to get date from Mirf
while (!Mirf.dataReady()) {
//ether.packetLoop(ether.packetReceive());
}
Mirf.getData((byte *)&tmpVal1);
Serial.print(tmpVal1);
Serial.println(F(" C"));
// Receive responses
ether.packetLoop(ether.packetReceive());
if (millis() > timer) {
timer = millis() + 5000;
//Serial.println();
Serial.println("Sending data to webservice : ");
ether.browseUrl(PSTR("/sendingdata.asmx/sendingdata?"), "Device=100&DeviceValue=80", website, my_callback);
}
//ShowLedNotification();
}
// called when the client request is complete
static void my_callback (byte status, word off, word len) {
Serial.println(">>>");
Ethernet::buffer[off+300] = 0;
Serial.print((const char*) Ethernet::buffer + off);
Serial.println("...");
digitalWrite(Blue,HIGH);
delay(200);
digitalWrite(Blue,LOW);
}
void ShowLedNotification() {
if (tmpVal1 > 0 ) {
digitalWrite(Yellow, HIGH);
delay(1000);
digitalWrite(Yellow, LOW);
}
else
{
digitalWrite(Blue, HIGH);
delay(1000);
digitalWrite(Blue, LOW);
}
}
long readVcc() {
long result;
// Read 1.1V reference against AVcc
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
delay(2); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Convert
while (bit_is_set(ADCSRA,ADSC));
result = ADCL;
result |= ADCH<<8;
result = 1126400L / result; // Back-calculate AVcc in mV
return result;
}
//Setting up network and getting DHCP IP
void setupEthernet() {
Serial.println(F("Setting up network and DHCP"));
Serial.print(F("MAC: "));
for (byte i = 0; i < 6; ++i) {
Serial.print(mymac[i], HEX);
if (i < 5)
Serial.print(':');
}
Serial.println();
if (ether.begin(sizeof Ethernet::buffer, mymac) == 0)
Serial.println(F("Failed to access Ethernet controller"));
Serial.println(F("Setting up DHCP"));
if (!ether.dhcpSetup())
Serial.println(F("DHCP failed"));
ether.printIp("My IP: ", ether.myip);
ether.printIp("Netmask: ", ether.netmask);
ether.printIp("GW IP: ", ether.gwip);
ether.printIp("DNS IP: ", ether.dnsip);
// Check network connection
if (!ether.dnsLookup(website))
Serial.println("DNS failed");
ether.printIp("SRV: ", ether.hisip);
}
void setupMirf() {
//Initialize nRF24
Serial.println(F("Initializing Mirf"));
Mirf.spi = &MirfHardwareSpi;
Mirf.init();
Mirf.setRADDR((byte *)"serv1");
Mirf.payload = sizeof(tmpVal1);
// we use channel 90 as it is outside of WLAN bands
// or channels used by wireless surveillance cameras
Mirf.channel = 90;
Mirf.config();
}
Did get that work. Now using if clause not while Mirf.dataReady()
void loop() {
if (Mirf.dataReady()) {
Mirf.getData((byte *)&tmpVal1);
Serial.print(tmpVal1);
Serial.println(F(" C"));
ShowLedNotification();
// Send data to webservice
if (millis() > timer) {
timer = millis() + 5000;
Serial.println("Sending data to webservice");
String myVarsStr = "Device=";
myVarsStr += myDeviceID;
myVarsStr += "&DeviceValue=";
myVarsStr += tmpVal1;
char myVarsCh[40];
myVarsStr.toCharArray(myVarsCh, 40);
ether.browseUrl(PSTR("/receivedata.asmx/ReceiveData?"), myVarsCh, website, my_callback);
}
}
else
{
word pos = ether.packetReceive();
word len = ether.packetLoop(pos);
delay(200);
}
}

Arduino NFC PN532 library error

I am using this NFC Shield http://www.elecfreaks.com/wiki/index.php?title=RFID_/_NFC_Shield
and by using the provided library I am not able to run the examples.
This is the example code.
#include <PN532.h>
#define SCK 13
#define MOSI 11
#define SS 10
#define MISO 12
PN532 nfc(SCK, MISO, MOSI, SS);
void setup(void) {
Serial.begin(9600);
Serial.println("Hello!");
nfc.begin();
uint32_t versiondata = nfc.getFirmwareVersion();
if (! versiondata) {
Serial.print("Didn't find PN53x board");
while (1); // halt
}
// Got ok data, print it out!
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);
Serial.print("Supports "); Serial.println(versiondata & 0xFF, HEX);
// configure board to read RFID tags and cards
nfc.SAMConfig();
}
void loop(void) {
uint32_t id;
// look for MiFare type cards
id = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A);
if (id != 0) {
Serial.print("Read card #"); Serial.println(id);
}
}
and it gives this error
http://i.stack.imgur.com/MNvl9.jpg
And these are the detailed errors
In file included from readMifareTargetID.pde:1:
C:\Users\saqib\Documents\Arduino\libraries\PN532_SPI/PN532.h:44: error: expected `)' before 'cs'
C:\Users\saqib\Documents\Arduino\libraries\PN532_SPI/PN532.h:48: error: 'boolean' does not name a type
C:\Users\saqib\Documents\Arduino\libraries\PN532_SPI/PN532.h:49: error: 'uint32_t' does not name a type
C:\Users\saqib\Documents\Arduino\libraries\PN532_SPI/PN532.h:50: error: 'uint32_t' does not name a type
C:\Users\saqib\Documents\Arduino\libraries\PN532_SPI/PN532.h:51: error: 'uint32_t' does not name a type
C:\Users\saqib\Documents\Arduino\libraries\PN532_SPI/PN532.h:57: error: 'uint32_t' does not name a type
C:\Users\saqib\Documents\Arduino\libraries\PN532_SPI/PN532.h:58: error: 'uint32_t' does not name a type
C:\Users\saqib\Documents\Arduino\libraries\PN532_SPI/PN532.h:60: error: 'boolean' does not name a type
C:\Users\saqib\Documents\Arduino\libraries\PN532_SPI/PN532.h:65: error: 'uint8_t' does not name a type
C:\Users\saqib\Documents\Arduino\libraries\PN532_SPI/PN532.h:67: error: 'boolean' does not name a type
C:\Users\saqib\Documents\Arduino\libraries\PN532_SPI/PN532.h:68: error: 'uint8_t' does not name a type
C:\Users\saqib\Documents\Arduino\libraries\PN532_SPI/PN532.h:69: error: 'uint8_t' has not been declared
C:\Users\saqib\Documents\Arduino\libraries\PN532_SPI/PN532.h:69: error: 'uint8_t' has not been declared
C:\Users\saqib\Documents\Arduino\libraries\PN532_SPI/PN532.h:70: error: 'uint8_t' has not been declared
C:\Users\saqib\Documents\Arduino\libraries\PN532_SPI/PN532.h:70: error: 'uint8_t' has not been declared
C:\Users\saqib\Documents\Arduino\libraries\PN532_SPI/PN532.h:71: error: 'uint8_t' has not been declared
C:\Users\saqib\Documents\Arduino\libraries\PN532_SPI/PN532.h:72: error: 'uint8_t' does not name a type
In file included from C:\Program Files (x86)\Arduino\hardware\arduino\cores\arduino/Arduino.h:213,
from readMifareTargetID.pde:8:
C:\Program Files (x86)\Arduino\hardware\arduino\variants\mega/pins_arduino.h:35: error: expected unqualified-id before numeric constant
C:\Program Files (x86)\Arduino\hardware\arduino\variants\mega/pins_arduino.h:36: error: expected unqualified-id before numeric constant
C:\Program Files (x86)\Arduino\hardware\arduino\variants\mega/pins_arduino.h:37: error: expected unqualified-id before numeric constant
C:\Program Files (x86)\Arduino\hardware\arduino\variants\mega/pins_arduino.h:38: error: expected unqualified-id before numeric constant
readMifareTargetID:8: error: no matching function for call to 'PN532::PN532(int, int, int, int)'
C:\Users\saqib\Documents\Arduino\libraries\PN532_SPI/PN532.h:42: note: candidates are: PN532::PN532()
C:\Users\saqib\Documents\Arduino\libraries\PN532_SPI/PN532.h:42: note: PN532::PN532(const PN532&)
readMifareTargetID.pde: In function 'void setup()':
readMifareTargetID:16: error: 'class PN532' has no member named 'getFirmwareVersion'
readMifareTargetID:28: error: 'class PN532' has no member named 'SAMConfig'
readMifareTargetID.pde: In function 'void loop()':
readMifareTargetID:35: error: 'class PN532' has no member named 'readPassiveTargetID'
This is the .h file with the library
// PN532 library by adafruit/ladyada
// MIT license
// authenticateBlock, readMemoryBlock, writeMemoryBlock contributed
// by Seeed Technology Inc (www.seeedstudio.com)
#include <Arduino.h>
#define PN532_PREAMBLE 0x00
#define PN532_STARTCODE1 0x00
#define PN532_STARTCODE2 0xFF
#define PN532_POSTAMBLE 0x00
#define PN532_HOSTTOPN532 0xD4
#define PN532_FIRMWAREVERSION 0x02
#define PN532_GETGENERALSTATUS 0x04
#define PN532_SAMCONFIGURATION 0x14
#define PN532_INLISTPASSIVETARGET 0x4A
#define PN532_INDATAEXCHANGE 0x40
#define PN532_MIFARE_READ 0x30
#define PN532_MIFARE_WRITE 0xA0
#define PN532_AUTH_WITH_KEYA 0x60
#define PN532_AUTH_WITH_KEYB 0x61
#define PN532_WAKEUP 0x55
#define PN532_SPI_STATREAD 0x02
#define PN532_SPI_DATAWRITE 0x01
#define PN532_SPI_DATAREAD 0x03
#define PN532_SPI_READY 0x01
#define PN532_MIFARE_ISO14443A 0x0
#define KEY_A 1
#define KEY_B 2
class PN532{
public:
PN532(uint8_t cs, uint8_t clk, uint8_t mosi, uint8_t miso);
void begin(void);
boolean SAMConfig(void);
uint32_t getFirmwareVersion(void);
uint32_t readPassiveTargetID(uint8_t cardbaudrate);
uint32_t authenticateBlock( uint8_t cardnumber /*1 or 2*/,
uint32_t cid /*Card NUID*/,
uint8_t blockaddress /*0 to 63*/,
uint8_t authtype /*Either KEY_A or KEY_B */,
uint8_t * keys);
uint32_t readMemoryBlock(uint8_t cardnumber /*1 or 2*/,uint8_t blockaddress /*0 to 63*/, uint8_t * block);
uint32_t writeMemoryBlock(uint8_t cardnumber /*1 or 2*/,uint8_t blockaddress /*0 to 63*/, uint8_t * block);
boolean sendCommandCheckAck(uint8_t *cmd, uint8_t cmdlen, uint16_t timeout = 1000);
//
private:
uint8_t _ss, _clk, _mosi, _miso;
boolean spi_readack();
uint8_t readspistatus(void);
void readspidata(uint8_t* buff, uint8_t n);
void spiwritecommand(uint8_t* cmd, uint8_t cmdlen);
void spiwrite(uint8_t c);
uint8_t spiread(void);
};
and this the .cpp file
// PN532 library by adafruit/ladyada
// MIT license
// authenticateBlock, readMemoryBlock, writeMemoryBlock contributed
// by Seeed Technology Inc (www.seeedstudio.com)
#include <Arduino.h>
#include "PN532.h"
//#define PN532DEBUG 1
byte pn532ack[] = {0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00};
byte pn532response_firmwarevers[] = {0x00, 0xFF, 0x06, 0xFA, 0xD5, 0x03};
#define PN532_PACKBUFFSIZ 64
byte pn532_packetbuffer[PN532_PACKBUFFSIZ];
PN532::PN532(uint8_t clk, uint8_t miso, uint8_t mosi, uint8_t ss) {
_clk = clk;
_miso = miso;
_mosi = mosi;
_ss = ss;
pinMode(_ss, OUTPUT);
pinMode(_clk, OUTPUT);
pinMode(_mosi, OUTPUT);
pinMode(_miso, INPUT);
}
void PN532::begin() {
digitalWrite(_ss, LOW);
delay(1000);
// not exactly sure why but we have to send a dummy command to get synced up
pn532_packetbuffer[0] = PN532_FIRMWAREVERSION;
sendCommandCheckAck(pn532_packetbuffer, 1);
// ignore response!
}
uint32_t PN532::getFirmwareVersion(void) {
uint32_t response;
pn532_packetbuffer[0] = PN532_FIRMWAREVERSION;
if (! sendCommandCheckAck(pn532_packetbuffer, 1))
return 0;
// read data packet
readspidata(pn532_packetbuffer, 12);
// check some basic stuff
if (0 != strncmp((char *)pn532_packetbuffer, (char *)pn532response_firmwarevers, 6)) {
return 0;
}
response = pn532_packetbuffer[6];
response <<= 8;
response |= pn532_packetbuffer[7];
response <<= 8;
response |= pn532_packetbuffer[8];
response <<= 8;
response |= pn532_packetbuffer[9];
return response;
}
// default timeout of one second
boolean PN532::sendCommandCheckAck(uint8_t *cmd, uint8_t cmdlen, uint16_t timeout) {
uint16_t timer = 0;
// write the command
spiwritecommand(cmd, cmdlen);
// Wait for chip to say its ready!
while (readspistatus() != PN532_SPI_READY) {
if (timeout != 0) {
timer+=10;
if (timer > timeout)
return false;
}
delay(10);
}
// read acknowledgement
if (!spi_readack()) {
return false;
}
timer = 0;
// Wait for chip to say its ready!
while (readspistatus() != PN532_SPI_READY) {
if (timeout != 0) {
timer+=10;
if (timer > timeout)
return false;
}
delay(10);
}
return true; // ack'd command
}
boolean PN532::SAMConfig(void) {
pn532_packetbuffer[0] = PN532_SAMCONFIGURATION;
pn532_packetbuffer[1] = 0x01; // normal mode;
pn532_packetbuffer[2] = 0x14; // timeout 50ms * 20 = 1 second
pn532_packetbuffer[3] = 0x01; // use IRQ pin!
if (! sendCommandCheckAck(pn532_packetbuffer, 4))
return false;
// read data packet
readspidata(pn532_packetbuffer, 8);
return (pn532_packetbuffer[5] == 0x15);
}
uint32_t PN532::authenticateBlock(uint8_t cardnumber /*1 or 2*/,uint32_t cid /*Card NUID*/, uint8_t blockaddress /*0 to 63*/,uint8_t authtype/*Either KEY_A or KEY_B */, uint8_t * keys) {
pn532_packetbuffer[0] = PN532_INDATAEXCHANGE;
pn532_packetbuffer[1] = cardnumber; // either card 1 or 2 (tested for card 1)
if(authtype == KEY_A)
{
pn532_packetbuffer[2] = PN532_AUTH_WITH_KEYA;
}
else
{
pn532_packetbuffer[2] = PN532_AUTH_WITH_KEYB;
}
pn532_packetbuffer[3] = blockaddress; //This address can be 0-63 for MIFARE 1K card
pn532_packetbuffer[4] = keys[0];
pn532_packetbuffer[5] = keys[1];
pn532_packetbuffer[6] = keys[2];
pn532_packetbuffer[7] = keys[3];
pn532_packetbuffer[8] = keys[4];
pn532_packetbuffer[9] = keys[5];
pn532_packetbuffer[10] = ((cid >> 24) & 0xFF);
pn532_packetbuffer[11] = ((cid >> 16) & 0xFF);
pn532_packetbuffer[12] = ((cid >> 8) & 0xFF);
pn532_packetbuffer[13] = ((cid >> 0) & 0xFF);
if (! sendCommandCheckAck(pn532_packetbuffer, 14))
return false;
// read data packet
readspidata(pn532_packetbuffer, 2+6);
#ifdef PN532DEBUG
for(int iter=0;iter<14;iter++)
{
Serial.print(pn532_packetbuffer[iter], HEX);
Serial.print(" ");
}
Serial.println();
// check some basic stuff
Serial.println("AUTH");
for(uint8_t i=0;i<2+6;i++)
{
Serial.print(pn532_packetbuffer[i], HEX); Serial.println(" ");
}
#endif
if((pn532_packetbuffer[6] == 0x41) && (pn532_packetbuffer[7] == 0x00))
{
return true;
}
else
{
return false;
}
}
uint32_t PN532::readMemoryBlock(uint8_t cardnumber /*1 or 2*/,uint8_t blockaddress /*0 to 63*/, uint8_t * block) {
pn532_packetbuffer[0] = PN532_INDATAEXCHANGE;
pn532_packetbuffer[1] = cardnumber; // either card 1 or 2 (tested for card 1)
pn532_packetbuffer[2] = PN532_MIFARE_READ;
pn532_packetbuffer[3] = blockaddress; //This address can be 0-63 for MIFARE 1K card
if (! sendCommandCheckAck(pn532_packetbuffer, 4))
return false;
// read data packet
readspidata(pn532_packetbuffer, 18+6);
// check some basic stuff
#ifdef PN532DEBUG
Serial.println("READ");
#endif
for(uint8_t i=8;i<18+6;i++)
{
block[i-8] = pn532_packetbuffer[i];
#ifdef PN532DEBUG
Serial.print(pn532_packetbuffer[i], HEX); Serial.print(" ");
#endif
}
if((pn532_packetbuffer[6] == 0x41) && (pn532_packetbuffer[7] == 0x00))
{
return true; //read successful
}
else
{
return false;
}
}
//Do not write to Sector Trailer Block unless you know what you are doing.
uint32_t PN532::writeMemoryBlock(uint8_t cardnumber /*1 or 2*/,uint8_t blockaddress /*0 to 63*/, uint8_t * block) {
pn532_packetbuffer[0] = PN532_INDATAEXCHANGE;
pn532_packetbuffer[1] = cardnumber; // either card 1 or 2 (tested for card 1)
pn532_packetbuffer[2] = PN532_MIFARE_WRITE;
pn532_packetbuffer[3] = blockaddress;
for(uint8_t byte=0; byte <16; byte++)
{
pn532_packetbuffer[4+byte] = block[byte];
}
if (! sendCommandCheckAck(pn532_packetbuffer, 20))
return false;
// read data packet
readspidata(pn532_packetbuffer, 2+6);
#ifdef PN532DEBUG
// check some basic stuff
Serial.println("WRITE");
for(uint8_t i=0;i<2+6;i++)
{
Serial.print(pn532_packetbuffer[i], HEX); Serial.println(" ");
}
#endif
if((pn532_packetbuffer[6] == 0x41) && (pn532_packetbuffer[7] == 0x00))
{
return true; //write successful
}
else
{
return false;
}
}
uint32_t PN532::readPassiveTargetID(uint8_t cardbaudrate) {
uint32_t cid;
pn532_packetbuffer[0] = PN532_INLISTPASSIVETARGET;
pn532_packetbuffer[1] = 1; // max 1 cards at once (we can set this to 2 later)
pn532_packetbuffer[2] = cardbaudrate;
if (! sendCommandCheckAck(pn532_packetbuffer, 3))
return 0x0; // no cards read
// read data packet
readspidata(pn532_packetbuffer, 20);
// check some basic stuff
Serial.print("Found "); Serial.print(pn532_packetbuffer[7], DEC); Serial.println(" tags");
if (pn532_packetbuffer[7] != 1)
return 0;
uint16_t sens_res = pn532_packetbuffer[9];
sens_res <<= 8;
sens_res |= pn532_packetbuffer[10];
Serial.print("Sens Response: 0x"); Serial.println(sens_res, HEX);
Serial.print("Sel Response: 0x"); Serial.println(pn532_packetbuffer[11], HEX);
cid = 0;
for (uint8_t i=0; i< pn532_packetbuffer[12]; i++) {
cid <<= 8;
cid |= pn532_packetbuffer[13+i];
Serial.print(" 0x"); Serial.print(pn532_packetbuffer[13+i], HEX);
}
#ifdef PN532DEBUG
Serial.println("TargetID");
for(uint8_t i=0;i<20;i++)
{
Serial.print(pn532_packetbuffer[i], HEX); Serial.println(" ");
}
#endif
return cid;
}
/************** high level SPI */
boolean PN532::spi_readack() {
uint8_t ackbuff[6];
readspidata(ackbuff, 6);
return (0 == strncmp((char *)ackbuff, (char *)pn532ack, 6));
}
/************** mid level SPI */
uint8_t PN532::readspistatus(void) {
digitalWrite(_ss, LOW);
delay(2);
spiwrite(PN532_SPI_STATREAD);
// read byte
uint8_t x = spiread();
digitalWrite(_ss, HIGH);
return x;
}
void PN532::readspidata(uint8_t* buff, uint8_t n) {
digitalWrite(_ss, LOW);
delay(2);
spiwrite(PN532_SPI_DATAREAD);
#ifdef PN532DEBUG
Serial.print("Reading: ");
#endif
for (uint8_t i=0; i<n; i++) {
delay(1);
buff[i] = spiread();
#ifdef PN532DEBUG
Serial.print(" 0x");
Serial.print(buff[i], HEX);
#endif
}
#ifdef PN532DEBUG
Serial.println();
#endif
digitalWrite(_ss, HIGH);
}
void PN532::spiwritecommand(uint8_t* cmd, uint8_t cmdlen) {
uint8_t checksum;
cmdlen++;
#ifdef PN532DEBUG
Serial.print("\nSending: ");
#endif
digitalWrite(_ss, LOW);
delay(2); // or whatever the delay is for waking up the board
spiwrite(PN532_SPI_DATAWRITE);
checksum = PN532_PREAMBLE + PN532_PREAMBLE + PN532_STARTCODE2;
spiwrite(PN532_PREAMBLE);
spiwrite(PN532_PREAMBLE);
spiwrite(PN532_STARTCODE2);
spiwrite(cmdlen);
uint8_t cmdlen_1=~cmdlen + 1;
spiwrite(cmdlen_1);
spiwrite(PN532_HOSTTOPN532);
checksum += PN532_HOSTTOPN532;
#ifdef PN532DEBUG
Serial.print(" 0x"); Serial.print(PN532_PREAMBLE, HEX);
Serial.print(" 0x"); Serial.print(PN532_PREAMBLE, HEX);
Serial.print(" 0x"); Serial.print(PN532_STARTCODE2, HEX);
Serial.print(" 0x"); Serial.print(cmdlen, HEX);
Serial.print(" 0x"); Serial.print(cmdlen_1, HEX);
Serial.print(" 0x"); Serial.print(PN532_HOSTTOPN532, HEX);
#endif
for (uint8_t i=0; i<cmdlen-1; i++) {
spiwrite(cmd[i]);
checksum += cmd[i];
#ifdef PN532DEBUG
Serial.print(" 0x"); Serial.print(cmd[i], HEX);
#endif
}
uint8_t checksum_1=~checksum;
spiwrite(checksum_1);
spiwrite(PN532_POSTAMBLE);
digitalWrite(_ss, HIGH);
#ifdef PN532DEBUG
Serial.print(" 0x"); Serial.print(checksum_1, HEX);
Serial.print(" 0x"); Serial.print(PN532_POSTAMBLE, HEX);
Serial.println();
#endif
}
/************** low level SPI */
void PN532::spiwrite(uint8_t c) {
int8_t i;
digitalWrite(_clk, HIGH);
for (i=0; i<8; i++) {
digitalWrite(_clk, LOW);
if (c & _BV(i)) {
digitalWrite(_mosi, HIGH);
} else {
digitalWrite(_mosi, LOW);
}
digitalWrite(_clk, HIGH);
}
}
uint8_t PN532::spiread(void) {
int8_t i, x;
x = 0;
digitalWrite(_clk, HIGH);
for (i=0; i<8; i++) {
if (digitalRead(_miso)) {
x |= _BV(i);
}
digitalWrite(_clk, LOW);
digitalWrite(_clk, HIGH);
}
return x;
}
I am a beginner and any help will be greatly appreciated.Thanks
you're not including the stdlib and stdbool headers that give you respectively the uint8_t/uint32_t type and boolean type, please consider adding this at the top of your files:
#include <stdint.h>
#include <stdbool.h>
Dont exactly know how it happened but I did try some things that I would like to mention which may help somebody else with this problem.
I deleted all my libraries of NFC(PN532) and added the original library using Arduino's own add library option.
Other than that I just changed my board to Uno and then changed it back to 2560 mega and compiled the sketch and it works now.
Note:(FOR ANYBODY NEW WHO READS THIS) Anybody using Arduino 1.0 or greater for such libraries should edit the .h and .cpp files by removing WProgram.h with Arduino.h.

Resources