Arduino NFC PN532 library error - arduino
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.
Related
How to Send Float/Double over SPI Arduino (SAMD21 Based Board)
I am trying to send a double/float over SPI from my SAMD21 based board, with chip select on pin A1/A2. I have copied some code from the internet, but I don't really understand it, plus it only works for sending data between two Arduino Unos. Here is my master: #include <SPI.h> float a = 3.14159; float b = 2.252332; uint8_t storage [12]; float buff[2] = {a, b}; void setup() { digitalWrite(SS, HIGH); SPI.begin(); Serial.begin(9600); SPI.setClockDivider(SPI_CLOCK_DIV8); } void loop() { digitalWrite(SS, LOW); memcpy(storage, &buff, 8); SPI.transfer(storage, sizeof storage ); //SPI library allows a user to //transfer a whole array of bytes and you need to include the size of the //array. digitalWrite(SS, HIGH); delay(1000); } And here is my slave: #include <SPI.h> byte storage [8]; volatile byte pos; volatile boolean process; float buff[2]; void setup() { pinMode(MISO,OUTPUT); SPCR |= _BV(SPE); SPCR |= _BV(SPIE); pos = 0; process = false; Serial.begin(9600); } ISR(SPI_STC_vect) { byte gathered = SPDR; if( pos < sizeof storage) { storage[pos++] = gathered; } else process = true; } void loop() { if( process ) { memcpy(buff,&storage,8); Serial.print("This is val1:");Serial.println(buff[0], 5); Serial.print("This is val2:");Serial.println(buff[1], 6); storage[pos] = 0; pos = 0; process = false; } } Any help would be aprreciated, and please understand that I am a newb in this subject.
Code error in smart irrigation system, using dht11 sensor
I have wrtitten a code for automatically watering plant using esp8266, dht11, moisture sensor but my code has some error, i dont know how to fix it #include <DHT.h> #include <ESP8266WiFi.h> String apiKey = "X5AQ3EGIKMBYW31H"; // Enter your Write API key here const char* server = "api.thingspeak.com"; const char *ssid = "CircuitLoop"; // Enter your WiFi Name const char *pass = "circuitdigest101"; // Enter your WiFi Password #define DHTPIN D3 // GPIO Pin where the dht11 is connected DHT dht(DHTPIN, DHT11); WiFiClient client; const int moisturePin = A0; // moisteure sensor pin const int motorPin = D0; unsigned long interval = 10000; unsigned long previousMillis = 0; unsigned long interval1 = 1000; unsigned long previousMillis1 = 0; float moisturePercentage; //moisture reading float h; // humidity reading float t; //temperature reading void setup() { Serial.begin(115200); delay(10); pinMode(motorPin, OUTPUT); digitalWrite(motorPin, LOW); // keep motor off initally dht.begin(); Serial.println("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, pass); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); // print ... till not connected } Serial.println(""); Serial.println("WiFi connected"); } void loop() { unsigned long currentMillis = millis(); // grab current time h = dht.readHumidity(); // read humiduty t = dht.readTemperature(); // read temperature if (isnan(h) || isnan(t)) { Serial.println("Failed to read from DHT sensor!"); return; } moisturePercentage = ( 100.00 - ( (analogRead(moisturePin) / 1023.00) * 100.00 ) ); if ((unsigned long)(currentMillis - previousMillis1) >= interval1) { Serial.print("Soil Moisture is = "); Serial.print(moisturePercentage); Serial.println("%"); previousMillis1 = millis(); } if (moisturePercentage < 50) { digitalWrite(motorPin, HIGH); // tun on motor } if (moisturePercentage > 50 && moisturePercentage < 55) { digitalWrite(motorPin, HIGH); //turn on motor pump } if (moisturePercentage > 56) { digitalWrite(motorPin, LOW); // turn off mottor } if ((unsigned long)(currentMillis - previousMillis) >= interval) { sendThingspeak(); //send data to thing speak previousMillis = millis(); client.stop(); } } void sendThingspeak() { if (client.connect(server, 80)) { String postStr = apiKey; // add api key in the postStr string postStr += "&field1="; postStr += String(moisturePercentage); // add mositure readin postStr += "&field2="; postStr += String(t); // add tempr readin postStr += "&field3="; postStr += String(h); // add humidity readin postStr += "\r\n\r\n"; client.print("POST /update HTTP/1.1\n"); client.print("Host: api.thingspeak.com\n"); client.print("Connection: close\n"); client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n"); client.print("Content-Type: application/x-www-form-urlencoded\n"); client.print("Content-Length: "); client.print(postStr.length()); //send lenght of the string client.print("\n\n"); client.print(postStr); // send complete string Serial.print("Moisture Percentage: "); Serial.print(moisturePercentage); Serial.print("%. Temperature: "); Serial.print(t); Serial.print(" C, Humidity: "); Serial.print(h); Serial.println("%. Sent to Thingspeak."); } } This is the error which i get Arduino: 1.8.9 (Windows 8.1), Board: "Generic ESP8266 Module, 80 MHz, Flash, Disabled, All SSL ciphers (most compatible), ck, 26 MHz, 40MHz, DOUT (compatible), 512K (no SPIFFS), 2, nonos-sdk 2.2.1 (legacy), v2 Lower Memory, Disabled, None, Only Sketch, 115200" sketch_oct03a:7:16: error: 'D3' was not declared in this scope #define DHTPIN D3 // GPIO Pin where the dht11 is connected ^ C:\Users\Shweta\Desktop\Libraries\sketch_oct03a\sketch_oct03a.ino:8:9: note: in expansion of macro 'DHTPIN' DHT dht(DHTPIN, DHT11); ^ sketch_oct03a:12:22: error: 'D0' was not declared in this scope const int motorPin = D0; ^ exit status 1 'D3' was not declared in this scope This report would have more information with "Show verbose output during compilation" option enabled in File -> Preferences.
Digital pins are not prefixed with D, unlike their analog counterparts. #define DHTPIN 3 const int motorPin = 0;
How to lower power consumption ARDUINO and RFID mfrc522
Im making a project that i scan rfid cards to gain access to a door. I have made the code the way i want it to function but currently its drawing 22mA. I want this project to be powered by an 4Ah Lead acid battery. I have removed the leds from the reader and from the arduino to lower consumption. Also i run arduino at 1Mhz and that looks that lowered the consumption a lot. Also i disabled Analog converter of arduino. IM using arduino nano and RFID-RC522 reader the output is an 5 volt relay. Here is the code: #include <SPI.h> #include <MFRC522.h> #include <EEPROM.h> #define SS_PIN 10 #define RST_PIN 9 MFRC522 mfrc522(SS_PIN, RST_PIN); #define relay 4 #define led 2 #define button 5 byte readCard[4]; byte storeCard[4]; byte lastCard[4] = {1,2,3,4}; uint8_t successread = 0; int flag=0; void setup() { CLKPR = 0x80; CLKPR = 0x04; ADCSRA = 0; pinMode(relay, OUTPUT); pinMode(button, INPUT_PULLUP); pinMode(led, OUTPUT); digitalWrite(relay, LOW); digitalWrite(led, LOW); SPI.begin(); mfrc522.PCD_Init(); } void loop() { do { successread = getID(); } while(!successread); digitalWrite(led, HIGH); delayMicroseconds(100); digitalWrite(led, LOW); lastcard(); if(digitalRead(button)==LOW){ save_delCard(); } if(checkID(readCard) && !(digitalRead(button)==LOW)){ if(flag==0){ digitalWrite(relay, HIGH); flag = !flag; } else{ digitalWrite(relay, LOW); flag = !flag; } } } /////////READ CARD FROM READER///////////////// uint8_t getID(){ if ( ! mfrc522.PICC_IsNewCardPresent()) { //If a new PICC placed to RFID reader continue return 0; } if ( ! mfrc522.PICC_ReadCardSerial()) { //Since a PICC placed get Serial and continue return 0; } for (uint8_t i=0; i<4; i++){ readCard[i] = mfrc522.uid.uidByte[i]; } mfrc522.PICC_HaltA(); // stop reading return 1; } ///////////////////SAVE OR DELETE CARD///////////////////////// uint8_t save_delCard(){ uint8_t count = EEPROM.read(0); int start = (count*4) + 1; int num = count*4 +1; if(checkID(readCard)){ uint8_t slot = slotcheck(readCard); for(uint8_t m=0;m<4;m++){ EEPROM.write((num-m-1),0); } for(uint8_t k=0;k<4;k++){ EEPROM.write((((slot-1)*4)+1+k),lastCard[k]); } count--; } else{ count++; } for(uint8_t j=0; j<4;j++){ EEPROM.write(j + start, readCard[j]); } EEPROM.write(0,count); return 0; } ////////////////////READ FROM MEMORY////////////////////////////////// uint8_t readID(uint8_t number){ uint8_t start = (number*4) + 1; for(uint8_t j=0;j<4;j++){ storeCard[j] = EEPROM.read(start + j); } } ///////////////////COMPARE IDS/////////////////////////////// bool compare(byte arraya[],byte arrayb[]){ for(uint8_t i=0;i<4;i++){ if(arraya[i]!=arrayb[i]){ return false; } else{ return true; } } } /////////CHECK IF CARD IS IN MEMORY///////////////////////////////////// bool checkID(byte arraya[]){ uint8_t count = EEPROM.read(0); for(int i=0;i<count;i++){ readID(i); if(compare(arraya, storeCard)){ return true; } else { } } return false; } ////////////////FINDS WHERE CARD IS IN MEMORY////////////////// uint8_t slotcheck(byte arraya[]){ uint8_t count = EEPROM.read(0); uint8_t slot=0; for(int i=0;i<count;i++){ readID(i); slot = i+1; if(compare(arraya, storeCard)){ return slot; } else { } } return NULL; } ///////////////SAVES LAST CARD///////////////////// void lastcard(){ uint8_t count = EEPROM.read(0); for(uint8_t p=0;p<4;p++){ lastCard[p] = EEPROM.read((count*4)-3+p); } } //////////////////////////////////////////////////////////////////
integrating the AdafruitFona GSM shield with tiny gps library
i need help in integrating the two libraries so that i can send the GPS data via GSM . Information regarding the use of two special Serial is needed and also a help with the code is needed . The below segmnet containts the code for the GPS shield this has to be used to generate the location and this data has to be sent via gsm to a mobile number. #include <TinyGPS++.h> #include <SoftwareSerial.h> /* This sample sketch demonstrates the normal use of a TinyGPS++ (TinyGPSPlus) object. It requires the use of SoftwareSerial, and assumes that you have a 4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx). */ static const int RXPin = 4, TXPin = 3;//was 4 and 3; static const uint32_t GPSBaud = 9600; // The TinyGPS++ object TinyGPSPlus gps; // The serial connection to the GPS device SoftwareSerial ss(RXPin, TXPin); void setup() { Serial.begin(115200); ss.begin(GPSBaud); Serial.println(F("GPS GSM tracking system")); Serial.println(F("Sabdadon Presents")); Serial.print(F("Search and Rescue")); Serial.println(TinyGPSPlus::libraryVersion()); Serial.println(F("Sabarish")); Serial.println(); } void loop() { // This sketch displays information every time a new sentence is correctly encoded. while (ss.available() > 0) if (gps.encode(ss.read())) displayInfo(); if (millis() > 500000 && gps.charsProcessed() < 10) { Serial.println(F("No GPS detected: check wiring.")); while(true); } } void displayInfo() { delay(10000); Serial.print(F("Location: ")); if (gps.location.isValid()) { Serial.print(gps.location.lat(), 5); Serial.print(F(",")); Serial.print(gps.location.lng(), 5); // latitude=gps.location.lat(); //longitude=gps.location.lng(); //if(latitude && longitude) } else { Serial.print(F("INVALID")); } Serial.print(F(" Date/Time: ")); if (gps.date.isValid()) { Serial.print(gps.date.month()); Serial.print(F("/")); Serial.print(gps.date.day()); Serial.print(F("/")); Serial.print(gps.date.year()); } else { Serial.print(F("INVALID")); } Serial.print(F(" ")); if (gps.time.isValid()) { if (gps.time.hour() < 10) Serial.print(F("0")); Serial.print(gps.time.hour()); Serial.print(F(":")); if (gps.time.minute() < 10) Serial.print(F("0")); Serial.print(gps.time.minute()); Serial.print(F(":")); if (gps.time.second() < 10) Serial.print(F("0")); Serial.print(gps.time.second()); Serial.print(F(".")); if (gps.time.centisecond() < 10) Serial.print(F("0")); Serial.print(gps.time.centisecond()); } else { ss.read(); Serial.print(F("INVALID")); } Serial.println(); } FOR GSM #include "Adafruit_FONA.h" #define FONA_RX 2//2 #define FONA_TX 3//3 #define FONA_RST 4//4 char replybuffer[255]; #include <SoftwareSerial.h> #include <AltSoftSerial.h> SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX); SoftwareSerial *fonaSerial = &fonaSS; Adafruit_FONA fona = Adafruit_FONA(FONA_RST); uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0); uint8_t type; void setup() { while (!Serial); Serial.begin(115200); Serial.println(F("FONA basic test")); Serial.println(F("Initializing....(May take 3 seconds)")); fonaSerial->begin(4800); if (! fona.begin(*fonaSerial)) { Serial.println(F("Couldn't find FONA")); while (1); } type = fona.type(); Serial.println(F("FONA is OK")); Serial.print(F("Found ")); switch (type) { case FONA800L: Serial.println(F("FONA 800L")); break; case FONA800H: Serial.println(F("FONA 800H")); break; case FONA808_V1: Serial.println(F("FONA 808 (v1)")); break; case FONA808_V2: Serial.println(F("FONA 808 (v2)")); break; case FONA3G_A: Serial.println(F("FONA 3G (American)")); break; case FONA3G_E: Serial.println(F("FONA 3G (European)")); break; default: Serial.println(F("???")); break; } // Print module IMEI number. char imei[15] = {0}; // MUST use a 16 character buffer for IMEI! uint8_t imeiLen = fona.getIMEI(imei); if (imeiLen > 0) { Serial.print("Module IMEI: "); Serial.println(imei); } } void loop() { Serial.print(F("FONA> ")); while (! Serial.available() ) { if (fona.available()) { Serial.write(fona.read()); } } // send an SMS! char sendto[21], message[141]; flushSerial(); Serial.print(F("Send to #")); readline(sendto, 20); Serial.println(sendto); Serial.print(F("Type out one-line message (140 char): ")); readline(message, 140); Serial.println(message); if (!fona.sendSMS(sendto, message)) { Serial.println(F("Failed")); } else { Serial.println(F("Sent!")); } } void flushSerial() { while (Serial.available()) Serial.read(); } char readBlocking() { while (!Serial.available()); return Serial.read(); } uint16_t readnumber() { uint16_t x = 0; char c; while (! isdigit(c = readBlocking())) { //Serial.print(c); } Serial.print(c); x = c - '0'; while (isdigit(c = readBlocking())) { Serial.print(c); x *= 10; x += c - '0'; } return x; } uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout) { uint16_t buffidx = 0; boolean timeoutvalid = true; if (timeout == 0) timeoutvalid = false; while (true) { if (buffidx > maxbuff) { //Serial.println(F("SPACE")); break; } while (Serial.available()) { char c = Serial.read(); //Serial.print(c, HEX); Serial.print("#"); Serial.println(c); if (c == '\r') continue; if (c == 0xA) { if (buffidx == 0) // the first 0x0A is ignored continue; timeout = 0; // the second 0x0A is the end of the line timeoutvalid = true; break; } buff[buffidx] = c; buffidx++; } if (timeoutvalid && timeout == 0) { //Serial.println(F("TIMEOUT")); break; } delay(1); } buff[buffidx] = 0; // null term return buffidx; }
Here is a step-by-step to mix your GPS input device and your GSM output device. Remainder for Arduino principles: The void setup() function is performed one time after startup. The void loop() function is performed periodically after the setup(). Step1 - declaration of GPS device and Serial link // GPS and Serial link static const int RXPin = 4, TXPin = 3;//was 4 and 3; static const uint32_t GPSBaud = 9600; // The TinyGPS++ object TinyGPSPlus DeviceGPS; // The serial connection to the GPS device SoftwareSerial SerialGPS(RXPin, TXPin); Step2 - declaration of GSM/FONA device and Serial link Including the SendTo SMS number !!! #define FONA_RX 2//2 #define FONA_TX 3//3 #define FONA_RST 4//4 // The serial connection to the GSM device SoftwareSerial SerialFONA = SoftwareSerial(FONA_TX, FONA_RX); // The FONA/GSM Cellular Module device Adafruit_FONA DeviceFONA = Adafruit_FONA(FONA_RST); // The destination SMS number static const char *sSendTo = "<NUMBER>"; Step3 - setup() function for (Console, GPS and GSM) It is possible to add some extra Init. // only execute once void setup() { // Wait and Init Console while (!Serial); // Serial over USB Serial.begin(115200); // Init GPS link SerialGPS.begin(GPSBaud); Serial.print(F("TinyGPSPlus ver: ")); Serial.println(TinyGPSPlus::libraryVersion()); // Init GSM link SerialFONA.begin(4800); if (! DeviceFONA.begin(SerialFONA)) { Serial.println(F("Couldn't find FONA")); while (1); // Stop working } // Add some extra Init } Step4 - loop() function to wait GPS location and send SMS It is possible to use String() to create the SMS based on the acquired DeviceGPS.location.lng() and DeviceGPS.location.lat(). // executed periodicaly void loop() { // check until GPS message while (SerialGPS.available() > 0) { // get for a complete GPS message DeviceGPS.encode(SerialGPS.read()); } // flush GSM serial link while (SerialFONA.available() > 0) { if (DeviceFONA.available()) { DeviceFONA.flush(); } } // send an SMS! char sendto[21], message[141]; // Wait for location (lng, lat, alt) is OK if (DeviceGPS.location.isValid()) { // ==> create SMS with longitude & latitude } }
RFID (SoftwareSerial) influences/breaks connection with SD (SPI)
I'm creating a RFID logger with Arduino. I connected a RFID scanner, RTC module and a SD card reader. All parts are working fine together but when i started combining different sketches a problem occured. Reading files and writing to files on the SD card is no problem as long as i don't scan a RFID card. When input is received from the RFID scanner it is no longer possible to read or write to the sd card. The connection seems to be "disconnected" as soon as RFID input is received. I tried using different pins for the RFID scanner, another sequence of initializing in the setup but it doesn't make a difference. Is this a limitation of the Arduino or am I doing something wrong? I'm using a ATS125KRW RFID shield and a Catalex MicroSD card adpater in combination with a Arduino Mega. // SD #include <SD.h> File myFile; char idArray[100][11]; char nameArray[100][11]; // RTC #include <Wire.h> #include "RTClib.h" RTC_DS1307 rtc; // RFID #include <SoftwareSerial.h> SoftwareSerial rfid = SoftwareSerial(A8 , A9); //(RX,TX) String cardID; //string to store card id char c; char cardArray[11]; int incomingByte = 0; // for incoming serial data String rfidInput; boolean logtosd; void setup() { Serial.begin(9600); initializeRFID(); initializeSD(); initializeRTC(); readfromSD(); } void loop() { while(rfid.available()>0) { c = rfid.read(); rfidInput += c; } if(rfidInput.length() >=12) { Serial.print("SCanned: "); Serial.println(rfidInput); //writetoSD(rfidInput); writetoSD("kaart"); rfidInput = ""; } while(Serial.available()>0) { c = Serial.read(); cardID += c; } if(cardID.length() >= 2) { writetoSD(cardID); cardID = ""; } } void initializeSD() { // GND en VCC aansluiting via pin 48 en 49 pinMode(48, OUTPUT); // set pin to output digitalWrite(48, LOW); // GND pin dus LOW pinMode(49, OUTPUT); // set pin to output digitalWrite(49, HIGH); // VCC pin dus HIGH pinMode(53, OUTPUT); if (!SD.begin(53)) { Serial.println("SD initialization failed"); return; } Serial.println("SD initialized"); } void readfromSD() { //open the file for reading: myFile = SD.open("db.txt"); if (myFile) { char line[25]; //Array to store entire line int linenumber = 0; int arrayPlace = 0; while (myFile.available()) { char ch = myFile.read(); if(ch != '\n') { line[arrayPlace] = ch; arrayPlace ++; } else { char id[11]; char name[11]; //get ID from entire line for(int x = 0; x <= 10 ; x++) { id[x] = line[x]; } //Get NAME from entire line for(int x = 11; x <= 19 ; x++) { if (line[x] != ';') { name[x-11] = line[x]; } else { // NULL TERMINATE THE ARRAY name[x-11] = '\0'; //STOP x = 20; } } // save name to nameArray for(int x = 0; x <= 11 ; x++) { nameArray[linenumber][x] = name[x]; } // NULL TERMINATE THE ARRAY id[10] = '\0'; // save id to idArray for(int x = 0; x <= 11 ; x++) { idArray[linenumber][x] = id[x]; } linenumber +=1; arrayPlace = 0; } //else } //while // close the file: myFile.close(); } else { // if the file didn't open, print an error: Serial.println("error opening db.txt"); } } void writetoSD(String cardID) { //open file for writing myFile = SD.open("test.txt", FILE_WRITE); // if the file opened okay, write to it: if (myFile) { Serial.println("Writing time to test.txt..."); DateTime now = rtc.now(); myFile.print(now.day(), DEC); myFile.print('/'); myFile.print(now.month(), DEC); myFile.print('/'); myFile.print(now.year(), DEC); myFile.print(' '); myFile.print(now.hour(), DEC); myFile.print(':'); myFile.print(now.minute(), DEC); myFile.print(':'); myFile.print(now.second(), DEC); myFile.print('\t'); Serial.println("Writing string to test.txt..."); myFile.println(cardID); // close the file: myFile.flush(); Serial.println("done."); } else { // if the file didn't open, print an error: Serial.println("error opening test.txt"); } } void initializeRTC() { // GND en VCC aansluiting via pin 18 en 19 pinMode(18, OUTPUT); // set pin to output digitalWrite(18, LOW); // GND pin dus LOW pinMode(19, OUTPUT); // set pin to output digitalWrite(19, HIGH); // VCC pin dus HIGH #ifdef AVR Wire.begin(); #else Wire1.begin(); // Shield I2C pins connect to alt I2C bus on Arduino Due #endif rtc.begin(); Serial.print("RTC Initialized: "); DateTime now = rtc.now(); Serial.print(now.day(), DEC); Serial.print('/'); Serial.print(now.month(), DEC); Serial.print('/'); Serial.print(now.year(), DEC); Serial.print(' '); Serial.print(now.hour(), DEC); Serial.print(':'); Serial.print(now.minute(), DEC); Serial.print(':'); Serial.print(now.second(), DEC); Serial.println(); } void initializeRFID() { rfid.begin(9600); Serial.println("RFID initialized"); }
I think you are running out of RAM ,i have done a lot of data logging on SD card with Arduino and its a very resources taking job for the minial 2kb ram on the UNO (assuming u using UNO). Try using MemoryFree() library before every place you see there might be problem to see if you are running outta memory?