I'm running out of arduino space, how to save space [closed] - arduino

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 days ago.
Improve this question
How can I reduce the size of this code on Arduino Nano? I minimized the code as much as I can, maybe there is something else to minimize, I tried to mess with libraries but then the whole program crashes. Here is the code:
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <EthernetENC.h>
#define DEBUG
//===========================================[ETHERNET]===========================================
#define STATIC
static byte IP_ADDRESS[] = {10,0,0,150};
//static byte DNS_ADDRESS[] = {10,0,0,1};
byte MAC_ADDRESS[] = {0x80, 0x7D, 0x3A, 0x11, 0x20, 0xC8};
// Initialize Arduino Ethernet Client
EthernetClient client;
// Variable Setup
int failedCounter = 0;
#define WIRE Wire
Adafruit_SSD1306 display = Adafruit_SSD1306(128, 32, &WIRE);
#define LED_PIN 3
RF24 radio(9,10); // CE, CSN
const byte address[6] = "00001";
struct MyStruct{
char node[11];
char type[15];
float value;
};
void setup(){
Serial.begin(115200);
#ifdef DEBUG
Serial.println(F("DT:Init;Name:CGStudio - Reciver v2 05.02.2023;"));
#endif
// Ethernet initialization
Ethernet.init(4);
#ifdef STATIC
Ethernet.begin(MAC_ADDRESS,IP_ADDRESS);
#else
Ethernet.begin(MAC_ADDRESS);
#endif
delay(1000);
#ifdef DEBUG
Serial.print(F("DT:InitETH;LocalIP:"));
Serial.print(Ethernet.localIP());
Serial.print(F(";HardwareStatus:"));
Serial.print(Ethernet.hardwareStatus());
Serial.println(F(";"));
#endif
pinMode(LED_PIN, OUTPUT);
// SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
if(!radio.begin()) Serial.println(F("DT:InitNRF;Status:NOTOK;"));
else Serial.println(F("DT:InitNRF;Status:OK;"));
radio.openReadingPipe(0, address);
radio.setPALevel(RF24_PA_MAX);
radio.startListening();
display.display();
// Clear the buffer.
display.clearDisplay();
display.display();
//display.clearDisplay();
//display.setTextSize(1);
//display.setTextColor(SSD1306_WHITE);
//display.setCursor(0,0);
//display.print("CGStudio\n");
//display.print("Reciver\n");
//display.print("v2 05.02.2023\n");
//display.display();
//delay(1000);
}
void loop(){
digitalWrite(LED_PIN, HIGH);
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0,0);
display.print("IP: ");
display.print(Ethernet.localIP());
display.print(" ");
display.print(Ethernet.hardwareStatus());
if(radio.available()){
digitalWrite(LED_PIN, LOW);
MyStruct myStruct;
radio.read(&myStruct, sizeof(myStruct));
#ifdef DEBUG
Serial.print(myStruct.node);
Serial.print(" - ");
Serial.print(myStruct.type);
Serial.print(" - ");
Serial.println(myStruct.value);
#endif
//display.setCursor(1,1);
display.print("\nID: ");
display.print(myStruct.node);
display.print("\nType:");
display.print(myStruct.type);
display.print("\nValue:");
display.println(myStruct.value);
display.display(); // actually display all of the above
if(myStruct.node == "1;CGSMeteo"){
if(myStruct.type == "TEMP_DHT") updateThingSpeak("field1="+String(myStruct.value));
if(myStruct.type == "HUMIDITY_DHT") updateThingSpeak("field2="+String(myStruct.value));
if(myStruct.type == "PASCAL_BMP") updateThingSpeak("field3="+String(myStruct.value));
if(myStruct.type == "LDR") updateThingSpeak("field4="+String(myStruct.value));
if(myStruct.type == "PPM_MQ135") updateThingSpeak("field5="+String(myStruct.value));
if(myStruct.type == "RAIN") updateThingSpeak("field6="+String(myStruct.value));
if(myStruct.type == "TEMP_DMP") updateThingSpeak("field7="+String(myStruct.value));
if(myStruct.type == "Temp_Dallas") updateThingSpeak("field8="+String(myStruct.value));
}
}
}
void updateThingSpeak(String tsData){
if(client.connect("api.thingspeak.com", 80)){
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: XXXXXXXXXXXXX\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(tsData.length());
client.print("\n\n");
client.print(tsData);
if(client.connected()){
//Serial.println("Connecting to ThingSpeak...");
failedCounter = 0;
}else{
failedCounter++;
//Serial.println("Connection to ThingSpeak failed ("+String(failedCounter, DEC)+")");
}
}else{
failedCounter++;
//Serial.println("Connection to ThingSpeak Failed ("+String(failedCounter, DEC)+")");
}
}
Are there any other ways to shrink the code to fit on the Arduino?
Are there any generators or sites that help minimize the size of the libraries?

Related

Receiving all zeros in payload sent from nodemcu to Arduino UNO over UART using SerialTransfer library

I have a nodemcu master streaming sensor values to Arduino Uno slave over UART using SerialTransfer.h. I have set up an additional serial port on Arduino digital pins 2, 3 for Rx, Tx using SoftwareSerial.h. I have wired the Tx on nodemcu to Rx on Uno and Rx on nodemcu to Tx on the Uno. I have a level-shifter to adjust for 3.3 V nodemcu and 5 V Arduino. I have made sure to provide a common ground.
I transmit a struct from nodemcu with sensor values (bool and int types, hard-coded for demo) but receive only zero values at the Arduino, as seen with Serial monitor. My code is below. I'd appreciate any inputs.
I have tried the following with no difference.
With and without an extra serial port on Uno created using SoftwareSerial.h
Reversing the set up with Arduino Uno master and nodemcu slave
With and without level-shifter on nodemcu Tx and Arduino Uno Rx
Here is the code for nodemcu master.
#include <Wire.h>
#include <SerialTransfer.h>
SerialTransfer masterMCU;
struct PAYMASTER {
/*
water: instruction to switch pump on or off. Note the float sensor in pump's circuit will prevent overflow.
fan: instruction to control fan speed - LO, MED, HIGH. Note PC fan requires an int between 0 and 255.
led: instruction to control LED brightness. Note that the FastLED library requires an int between 0 and 255.
*/
bool water;
int fan;
int led;
} instructions = {
true,
201,
60
};
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
delay(999);
masterMCU.begin(Serial);
delay(999);
}
void debug() {
Serial.print("MASTER: ");
Serial.print(millis());
Serial.print(" Water: ");
Serial.print(instructions.water);
Serial.print(", Fan: ");
Serial.print(instructions.fan);
Serial.print(", LED: ");
Serial.println(instructions.led);
}
void loop() {
// put your main code here, to run repeatedly:
masterMCU.txObj(instructions, sizeof(instructions));
masterMCU.sendData(sizeof(instructions));
debug();
delay(999);
}
Here is the code for Arduino Uno slave.
#include <Wire.h>
#include <SerialTransfer.h>
#include <SoftwareSerial.h>
SerialTransfer slaveMCU;
SoftwareSerial extra(2, 3); // Rx 2, Tx 3
struct PAYMASTER {
/*
water: instruction to switch pump on or off. Note the float sensor in pump's circuit will prevent overflow.
fan: instruction to control fan speed - LO, MED, HIGH. Note PC fan requires an int between 0 and 255.
led: instruction to control LED brightness. Note that the FastLED library requires an int between 0 and 255.
*/
bool water;
int fan;
int led;
} instructions;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
delay(201);
extra.begin(9600);
delay(201);
slaveMCU.begin(extra);
delay(201);
}
void debug() {
Serial.print("SLAVE: ");
Serial.print(millis());
Serial.print(" Water: ");
Serial.print((bool)instructions.water);
Serial.print(", Fan: ");
Serial.print(instructions.fan);
Serial.print(", LED: ");
Serial.println(instructions.led);
}
void loop() {
// put your main code here, to run repeatedly:
if (slaveMCU.available()) {
slaveMCU.rxObj(instructions, sizeof(instructions));
debug();
} else if (slaveMCU.status < 0) {
Serial.print("ERROR: ");
if(slaveMCU.status == -1)
Serial.println(F("CRC_ERROR"));
else if(slaveMCU.status == -2)
Serial.println(F("PAYLOAD_ERROR"));
else if(slaveMCU.status == -3)
Serial.println(F("STOP_BYTE_ERROR"));
}
delay(999);
}
I made a few changes and data are received with correct values now.
I replaced delay() with millis() in master.
I replaced SerialTransfer::sendData() with SerialTransfer::sendDatum() in master. The former is for streaming multiple objects whereas the latter is for streaming a single object.
I replaced int types with uint8_t in the struct that is sent over wires in both master and slave.
The values are received correctly at Arduino Uno now. None of the changes made any difference until 3. above. I have retained the other changes as they also appear important to the result. Here is the final code that works for correct transmission and reception of objects from nodemcu master to Arduino Uno slave.
nodemcu master:
#include <Wire.h>
#include <SerialTransfer.h>
SerialTransfer masterMCU;
unsigned long tic = millis();
unsigned long toc = tic;
#define DELTA 1000
struct PAYMASTER {
/*
water: instruction to switch pump on or off. Note the float sensor in pump's circuit will prevent overflow.
fan: instruction to control fan speed - LO, MED, HIGH. Note PC fan requires an int between 0 and 255.
led: instruction to control LED brightness. Note that the FastLED library requires an int between 0 and 255.
*/
bool water;
uint8_t fan;
uint8_t led;
} instructions = {
true,
201,
60
};
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
delay(999);
masterMCU.begin(Serial);
delay(999);
}
void debug() {
Serial.print("MASTER: ");
Serial.print(millis());
Serial.print(" Water: ");
Serial.print(instructions.water);
Serial.print(", Fan: ");
Serial.print(instructions.fan);
Serial.print(", LED: ");
Serial.println(instructions.led);
}
void loop() {
// put your main code here, to run repeatedly:
toc = millis();
if ((toc - tic) > DELTA) {
masterMCU.txObj(instructions, sizeof(instructions));
masterMCU.sendDatum(instructions), sizeof(instructions);
debug();
tic = toc;
}
}
Arduino Uno slave:
#include <Wire.h>
#include <SerialTransfer.h>
#include <SoftwareSerial.h>
SerialTransfer slaveMCU;
SoftwareSerial Extra(2, 3); // Rx: 2, Tx: 3
unsigned long tic = millis();
unsigned long toc = tic;
struct PAYMASTER {
/*
water: instruction to switch pump on or off. Note the float sensor in pump's circuit will prevent overflow.
fan: instruction to control fan speed - LO, MED, HIGH. Note PC fan requires an int between 0 and 255.
led: instruction to control LED brightness. Note that the FastLED library requires an int between 0 and 255.
*/
bool water;
uint8_t fan;
uint8_t led;
} instructions;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
delay(201);
Extra.begin(9600);
delay(201);
slaveMCU.begin(Extra);
delay(201);
}
void debug() {
Serial.print("SLAVE: ");
Serial.print(millis());
Serial.print(" Water: ");
Serial.print((bool)instructions.water);
Serial.print(", Fan: ");
Serial.print(instructions.fan);
Serial.print(", LED: ");
Serial.println(instructions.led);
}
void loop() {
// put your main code here, to run repeatedly:
if (slaveMCU.available()) {
slaveMCU.rxObj(instructions);
debug();
} else if (slaveMCU.status < 0) {
Serial.print("ERROR: ");
if(slaveMCU.status == -1)
Serial.println(F("CRC_ERROR"));
else if(slaveMCU.status == -2)
Serial.println(F("PAYLOAD_ERROR"));
else if(slaveMCU.status == -3)
Serial.println(F("STOP_BYTE_ERROR"));
}
}

SPI Micro SD Card - error opening textfile - why isn't it working?

First of all sorry for my bad english and my programming skills... im still a beginner. I have a problem implementing the example code into my project. The example code for Datalogging on my SD-Card works. So there are no wiring faults.. Implementing this working code in my project, the arduino cant find the text data and i dont know why. can anybody help me ?
im working with an arduino nano V3. and a SPI Card Reader.
Here is what happening in the serial monitor:
Initializing SD card...card initialized.
error opening datalog.txt
Here is my Code - sorry for the used German words... but i think they wont disturb.
#include <LiquidCrystal_I2C.h>
#include "RTClib.h"
RTC_DS3231 rtc;
#include <SimpleDHT.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
#include <SPI.h>
#include <SD.h>
const int chipSelect = 10; // SD KARTE
int pinDHT22 = 2; // Kombisensor
SimpleDHT22 dht22(pinDHT22);
float temperature = 0;
float humidity = 0;
volatile float windgeschwindigkeit = 0;
unsigned long previousMillis = 0;
volatile int Impulscounter = 0; // Impulszähler für Windgeschwindigkeit
unsigned long windmillis = 0;
int a = 0;
File Datenlog;
void wind()
{
Impulscounter = Impulscounter + 1;
if( Impulscounter == 1)
{
windmillis = millis();
}
}
void setup()
{
pinMode(3, INPUT);
lcd.begin();
lcd.backlight();
Serial.begin(9600);
attachInterrupt(1, wind, RISING);
while (!Serial) { // wait for serial port to connect. Needed for native USB port only
;
}
Serial.print("Initializing SD card...");
if (!SD.begin(chipSelect)) { // see if the card is present and can be initialized:
Serial.println("Card failed, or not present");
// don't do anything more:
while (1);
}
Serial.println("card initialized.");
Datenlog = SD.open("test.txt", FILE_WRITE);
if (Datenlog){
Datenlog.print("Tag "); // ... und die Textdatei anschließend befüllt werden.
Datenlog.print("Datum ");
Datenlog.print("Uhrzeit ");
Datenlog.print("Aussentemperatur ");
Datenlog.print("Aussenfeuchtigkeit ");
Datenlog.print("Windgeschwindigkeit ");
Datenlog.print("Gehaeusetemperatur ");
Datenlog.close();
Serial.print ( "it worked");
}
else {
Serial.println("error opening datalog.txt");
}
}

Multi-file arduino esp8266 sketch sharing a reference to server

As my sketches get bigger, the code looks awful as one file and the number of global variables is too high.
For the webconfig part of my sketch the device attempts to get online and if it fails it scans for available wifi networks, goes into Access Point Mode, starts a server, sends the list of ssid's and listens for a response of an ssid/passwd pair. The server is only for the configuration.
Ideally I'd like the cleaned up main.ino file to look like
#include "config.h"
void setup(){
Serial.begin(115200);
Serial.println();
Serial.println("--------------------------");
Serial.println("ESP8266 multifile");
Serial.println("--------------------------");
getOnline();
}
void loop(){
if(IN_CONFIG_MODE){
server.handleClient();
}
}
with a config.h something like..
#ifndef config_h
#define config_h
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
ESP8266WebServer server;
void getOnline();
#endif
and then a config.cpp where it does all stuff described above yet gives the main.ino program access to the server instance so it can listen in the main loop.
#include "config.h"
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
char *espssid = "espAPsb";
char *ssid = "street_no_vale2";
char *pwd = "jjjjjjjjx";
char ssids[300];
extern server(80);
void handleRoot(){
server.send(200, "text/html", "<h1>root of espAPsb AP server</h1>");
//send json of available ssids
}
void scan(){
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(100);
int n = WiFi.scanNetworks();
Serial.println("scan done");
if (n == 0)
Serial.println("no networks found");
else
{
Serial.print(n);
Serial.println(" networks found");
for (int i = 0; i < n; ++i)
{
// Print SSID and RSSI for each network found
Serial.print(i + 1);
Serial.print(": ");
Serial.print(WiFi.SSID(i));
Serial.print(" (");
Serial.print(WiFi.RSSI(i));
Serial.print(")");
Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*");
delay(10);
}
}
Serial.println("");
}
void setupAP(){
WiFi.softAP(espssid);
server.on("/", handleRoot);
server.begin();
Serial.println();
Serial.print("connected as AP ");
Serial.println(espssid);
Serial.print("IP address: ");
Serial.println(WiFi.softAPIP());
}
void getOnline(){
WiFi.begin(ssid, pwd);
int tries =0;
int success=1;
while (WiFi.status() != WL_CONNECTED ) {
delay(500);
Serial.print(".");
tries++;
if (tries==15){
success=0;
Serial.println("WiFi not connected");
scan();
setupAP();
break;
}
}
if (success){
Serial.println("");
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
}
You can make an own library from your networking code, which you can easily reuse.
https://www.arduino.cc/en/Hacking/LibraryTutorial
Alternatively, you can use multiple "tabs" in Arduino IDE which works like a standard multi-source project. http://arduino.land/FAQ/content/7/43/en/breaking-a-sketch-into-multiple-files.html
(Btw, StackExchange hosts a dedicated Ardunio microsite here: https://arduino.stackexchange.com/ Have fun there :)

Why Arduino int can't count over 14464?

I got some problem about reading from MPU6050 and then write to SD card.
Actually I could successfully do the read-and-write, but I found Arduino UNO can't count over 14464!?
I set every line of my data that is:
count, time(millis()), ax, ay, az, gx, gy, gz
It could record the data right till count to 14464 (I) and it will end the loop automated.
It really bothers me... and it seems no one face this problem before.
Here is my code:
#include "I2Cdev.h"
#include "MPU6050.h"
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
#include "Wire.h"
#endif
MPU6050 accelgyro;
//SD card here
#include <SPI.h>
#include <SD.h>
File myFile;
//////////Global Variable Here//////////
int16_t ax, ay, az;
int16_t gx, gy, gz;
int count = 1;
//set sec & count_limit
int set_time = 1000 * 60;
int count_limit = 80000;
int BTN = 7;
// uncomment "OUTPUT_READABLE_ACCELGYRO" if you want to see a tab-separated
// list of the accel X/Y/Z and then gyro X/Y/Z values in decimal. Easy to read,
// not so easy to parse, and slow(er) over UART.
#define OUTPUT_READABLE_ACCELGYRO
//Set LED
#define R_PIN 8
#define G_PIN 9
bool blinkState_R = false;
bool blinkState_G = false;
void setup() {
// configure Arduino LED for
pinMode(R_PIN, OUTPUT);
pinMode(G_PIN, OUTPUT);
pinMode(BTN, INPUT);
digitalWrite(G_PIN, HIGH);
// join I2C bus (I2Cdev library doesn't do this automatically)
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
Wire.begin();
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
Fastwire::setup(400, true);
#endif
// initialize serial communication
// (38400 chosen because it works as well at 8MHz as it does at 16MHz, but
// it's really up to you depending on your project)
Serial.begin(38400);
// initialize device
Serial.println("Initializing I2C devices...");
accelgyro.initialize();
accelgyro.setFullScaleAccelRange(MPU6050_ACCEL_FS_2);
// verify connection
Serial.println("Testing device connections...");
Serial.println(accelgyro.testConnection() ? "MPU6050 connection successful" : "MPU6050 connection failed");
// use the code below to change accel/gyro offset values
accelgyro.setXGyroOffset(59);
accelgyro.setYGyroOffset(42);
accelgyro.setZGyroOffset(-8);
accelgyro.setXAccelOffset(1359);
accelgyro.setYAccelOffset(-1620);
accelgyro.setZAccelOffset(1917);
/////////////////////////////////////////////////////////////////////
//SD card Initailize
/////////////////////////////////////////////////////////////////////
Serial.print("Initializing SD card...");
if (!SD.begin(4)) {
Serial.println("initialization failed!");
digitalWrite(R_PIN, HIGH);
return;
}
Serial.println("initialization done.");
digitalWrite(R_PIN, LOW);
if (SD.exists("example.txt")) {
Serial.println("example.txt exists.");
}
else {
Serial.println("example.txt doesn't exist.");
}
// open a new file and immediately close it:
Serial.println("Creating example.txt...");
myFile = SD.open("example.txt", FILE_WRITE);
myFile.close();
// Check to see if the file exists:
if (SD.exists("example.txt")) {
Serial.println("example.txt exists.");
}
else {
Serial.println("example.txt doesn't exist.");
}
// delete the file:
Serial.println("Removing example.txt...");
SD.remove("example.txt");
if (SD.exists("example.txt")) {
Serial.println("example.txt exists.");
}
else {
Serial.println("example.txt doesn't exist.");
}
delay(3000);
////////////////////////////////////////////////////////////////////////////////
//SD END
////////////////////////////////////////////////////////////////////////////////
digitalWrite(G_PIN, LOW);
}
void loop() {
// read raw accel/gyro measurements from device
accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
blinkState_R = !blinkState_R;
digitalWrite(R_PIN, blinkState_R);
// these methods (and a few others) are also available
//accelgyro.getAcceleration(&ax, &ay, &az);
//accelgyro.getRotation(&gx, &gy, &gz);
////////////////////////////////////////////
// Write to SD Card
///////////////////////////////////////////
// write data to file
if(count <= count_limit ){
myFile = SD.open("IMU_LOG.txt", FILE_WRITE);
Serial.print(count);Serial.print("\t"); myFile.print(count); myFile.print("\t");
Serial.print(millis()); Serial.print("\t"); myFile.print(millis()); myFile.print("\t");
Serial.print(ax); Serial.print("\t"); myFile.print(ax); myFile.print("\t");
Serial.print(ay); Serial.print("\t"); myFile.print(ay); myFile.print("\t");
Serial.print(az); Serial.print("\t"); myFile.print(az); myFile.print("\t");
Serial.print(gx); Serial.print("\t"); myFile.print(gx); myFile.print("\t");
Serial.print(gy); Serial.print("\t"); myFile.print(gy); myFile.print("\t");
Serial.print(gz); Serial.print("\n"); myFile.print(gz); myFile.print("\n");
myFile.close();
delay(5);
blinkState_G = !blinkState_G;
digitalWrite(G_PIN, blinkState_G);
}else{
while(1){
Serial.print("Process done.\n");
digitalWrite(G_PIN, OUTPUT);
delay(2000);
}
count= count + 1 ;
}
You should be getting a compiler warning here.
int count_limit = 80000;
The maximum value of int on your platform is 32,767. When you set an int to something larger, the behavior is undefined, which is bad news because it means that your program is incorrect.
In this particular case, you might notice that 80000 = 14464 + 216, which explains why it stopped at 14464, if int is 16 bits long.
You will need to use long if you want to count higher than 65,535.
long count_limit = 80000L;
long count = 1;

Arduino NFC PN532

Hello im trying to make a program to compare the NFC tag #ID, im very used to Arduino, but im not used to SPI Programming.
i searched a lot, but i dont really know what i need exactly.
im trying match the NFC tag #ID and the variable NFC1.
Can anyone help me? please?
i just need some info/help to make the if statement work.
#include <PN532.h>
#include <SPI.h>
//SPI: 10 (SS), 11 (MOSI), 12 (MISO), 13 (SCK)
/*Chip select pin can be connected to D10 or D9 which is hareware optional*/
/*if you the version of NFC Shield from SeeedStudio is v2.0.*/
#define PN532_CS 10
PN532 nfc(PN532_CS);
#define NFC_DEMO_DEBUG 1
int BUZZER = 6;
uint32_t NFC1 = 3795120787;
int NFC2 = 3262404755;
int NFC3 = 46356883;
int NFC4 = 35320979;
int NFC5 = 3257334163;
void setup(void) {
pinMode(BUZZER, OUTPUT);
#ifdef NFC_DEMO_DEBUG
Serial.begin(9600);
Serial.println("Hello!");
#endif
nfc.begin();
uint32_t versiondata = nfc.getFirmwareVersion();
if (! versiondata) {
#ifdef NFC_DEMO_DEBUG
Serial.print("Didn't find PN53x board");
Serial.print("");
#endif
while (1); // halt
}
#ifdef NFC_DEMO_DEBUG
// 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);*/
#endif
// 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) {
#ifdef NFC_DEMO_DEBUG
Serial.println("");
Serial.print("Card #");
Serial.println(id);
analogWrite(BUZZER, 50);
delay(100);
analogWrite(BUZZER, 0);
delay(1000);
#endif
//char ch = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A);
if(NFC1 = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A)){
analogWrite(6, 255);
delay(250);
analogWrite(6, 0);
/*analogWrite(BUZZER, 50);
delay(50);
analogWrite(BUZZER, 0);
delay(50);
analogWrite(BUZZER, 50);
delay(50);
analogWrite(BUZZER, 0);*/}
else {
analogWrite(5, 255);
delay(250);
analogWrite(5, 0);
/*analogWrite(BUZZER, 50);
delay(100);
analogWrite(BUZZER, 0);
delay(100);
analogWrite(BUZZER, 50);
delay(100);
analogWrite(BUZZER, 0);
delay(100);
analogWrite(BUZZER, 50);
delay(100);
analogWrite(BUZZER, 0);*/}
}
}
Common mistake and the compiler could have helped you
Change this line:
uint32_t NFC1 = 3795120787;
To this line:
const uint32_t NFC1 = 3795120787;
You will now get a compiler error, which would have resulted in you going :o.
This line needs a ==, not a =. Not this:
if(NFC1 = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A)){ / doh!
This:
if(NFC1 == nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A)){ / ahh
Side note, this is a common typing error and reason why
if(1 == somevar) // is superior to
if(somevar == 1) // something that seems exactly the same
Because the compiler will tell you
if(1 = somevar) // no, you can't assign to a constant
if(somevar = 1) // okay, whatever you want boss
This advice is from "Writing Solid Code", Maguire and Moore, and has served me well.

Resources