Can't mix 2 Arduino sketches (RFID + WEB SERVER)

Hello, my problem is that I can't combine 2 Arduino sketches. The first one use RFID, and the second one is a web server. And i need to show the informations from the RFID badge on the web server when it's receive the signal.

Here is the RFID sketch :

int data1 = 0;
int ok=-1;
// define the tag numbers that can have access 
int yellowtag[14] = {
  1,11,3,1,12,224,152,118,255,194,248,-1,-1,-1}; //  my yellow tag. Change this to suit your own tags, use example 15.1 sketch to read your tags
int redtag[14] = {
  1,11,3,1,11,141,42,116,255,51,133,-1,-1,-1}; // my red tag...
int newtag[14] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0}; // used for read comparisons
int okdelay = 500; // this is the time the output will be set high for when an acceptable tag has been read
int notokdelay = 500; // time to show no entry (red LED)
void setup()
{
  Serial.flush(); // need to flush serial buffer, otherwise first read from reset/power on may not be correct
  pinMode(3, OUTPUT); // this if for "rejected" LED
  pinMode(4, OUTPUT); // this will be set high when correct tag is read. Use to switch something on, for now - an LED. 
  Serial.begin(9600); // for debugging
}

boolean comparetag(int aa[14], int bb[14])
//  compares two arrrays, returns true if identical - good for comparing tags
{
  boolean ff=false;
  int fg=0;
  for (int cc=0; cc<14; cc++)
  {
    if (aa[cc]==bb[cc])
    {
      fg++;
    }
  }
  if (fg==14)
  {
    ff=true;
  }
  return ff;
}

void checkmytags()

{
  ok=0; // this variable helps decision making, if it is 1, we have a match, zero - a read but no match, -1, no read attempt made
  if (comparetag(newtag,yellowtag)==true)
  {
    ok++;
    Serial.println("Ludo");
  }
  if (comparetag(newtag,redtag)==true)
  {
   Serial.println("Cyril");
    ok++;
    
  }
}

void readTag() 

{
  ok=-1;
  if (Serial.available() > 0) // if a read has been attempted
  {
    // read the incoming number on serial RX
    delay(100);  // Needed to allow time for the data to come in from the serial buffer. 
    for (int z=0; z<14; z++) // read the rest of the tag
    {
      data1=Serial.read();
      
      newtag[z]=data1;
    }
    Serial.flush(); // stops multiple reads
    // now to match tags up
    checkmytags(); // compare the number of the tag just read against my own tags' number
  }
  //now do something based on tag type
  if (ok>0==true) // if we had a match
  {
    digitalWrite(4, HIGH);
    delay(okdelay);
    digitalWrite(4, LOW);
    ok=-1;
  } 
  else if (ok==0) // if we didn't have a match
  {
    digitalWrite(3, HIGH);
    delay(notokdelay);
    digitalWrite(3, LOW);
    ok=-1;
  }
}

void loop()
{
  readTag(); // we should create a function to take care of reading tags, as later on 
  // we will want other things to happen while waiting for a tag read, such as 
  // displaying data on an LCD, etc
}

Here is the web server one :

#include <Ethernet.h>

#include <SPI.h>

byte mac[] = { 
  0x90, 0xA2, 0xDA, 0x0D, 0x9D, 0xF7};
IPAddress ip(192,168,1,3);
IPAddress gateway(192,168,1,1);	
IPAddress subnet(255, 255, 255, 0);

EthernetServer server(80);

const int PRESSURE = 0x1F;      //3 most significant bits of pressure
const int PRESSURE_LSB = 0x20;  //16 least significant bits of pressure
const int TEMPERATURE = 0x21;   //16 bit temperature reading

const int dataReadyPin = 6; 
const int chipSelectPin = 7;

float temperature = 0.0;
long pressure = 0;
long lastReadingTime = 0;

void setup() {
 
  SPI.begin();

 
  Ethernet.begin(mac, ip);
  server.begin();

  
  pinMode(dataReadyPin, INPUT);
  pinMode(chipSelectPin, OUTPUT);

  Serial.begin(9600);

  writeRegister(0x02, 0x2D);
  writeRegister(0x01, 0x03);
  writeRegister(0x03, 0x02);


  delay(1000);


  writeRegister(0x03, 0x0A);

}

void loop() { 

  if (millis() - lastReadingTime > 1000){

    if (digitalRead(dataReadyPin) == HIGH) {
      getData();

      lastReadingTime = millis();
    }
  }

  listenForEthernetClients();
}


void getData() {
  Serial.println("Getting reading");

  int tempData = readRegister(0x21, 2);

  temperature = (float)tempData / 20.0;

  byte  pressureDataHigh = readRegister(0x1F, 1);   
  pressureDataHigh &= 0b00000111; //you only needs bits 2 to 0


  unsigned int pressureDataLow = readRegister(0x20, 2);    

  pressure = ((pressureDataHigh << 16) | pressureDataLow)/4;

  Serial.print("Temperature: ");
  Serial.print(temperature);
  Serial.println(" degrees C");
  Serial.print("Pressure: " + String(pressure));
  Serial.println(" Pa");
}

void listenForEthernetClients() {

  EthernetClient client = server.available();
  if (client) {
    Serial.println("Got a client");

    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();

        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();

         
        
          
          client.print ("Ludovic");
          client.println("
");
        client.print("/");
        client.println("
");
          client.print("28/01/2023" + String(pressure));
          client.println("
"); 
          client.print("/");
         client.println("
");
         client.print("15:24" + String(pressure));
          client.println("
"); 
          
          client.println("
");
           client.println("
");
          client.print ("Cyril");
          client.println("
");
        client.print("/");
        client.println("
");
          client.print("20/02/2023" + String(pressure));
          client.println("
"); 
          client.print("/");
         client.println("
");
         client.print("15:39" + String(pressure));
          client.println("
");
          
          
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        } 
        else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
  }
} 

//Send a write command to SCP1000
void writeRegister(byte registerName, byte registerValue) {
  // SCP1000 expects the register name in the upper 6 bits
  // of the byte:
  registerName <<= 2;
  // command (read or write) goes in the lower two bits:
  registerName |= 0b00000010; //Write command

  // take the chip select low to select the device:
  digitalWrite(chipSelectPin, LOW); 

  SPI.transfer(registerName); //Send register location
  SPI.transfer(registerValue); //Send value to record into register

  // take the chip select high to de-select:
  digitalWrite(chipSelectPin, HIGH); 
}


//Read register from the SCP1000:
unsigned int readRegister(byte registerName, int numBytes) {
  byte inByte = 0;           // incoming from  the SPI read
  unsigned int result = 0;   // result to return 

  // SCP1000 expects the register name in the upper 6 bits
  // of the byte:
  registerName <<=  2;
  // command (read or write) goes in the lower two bits:
  registerName &= 0b11111100; //Read command

  // take the chip select low to select the device:
  digitalWrite(chipSelectPin, LOW); 
  // send the device the register you want to read:
  int command = SPI.transfer(registerName); 
  // send a value of 0 to read the first byte returned:
  inByte = SPI.transfer(0x00); 
  
  result = inByte;
  // if there's more than one byte returned, 
  // shift the first byte then get the second byte:
  if (numBytes > 1){
    result = inByte << 8;
    inByte = SPI.transfer(0x00); 
    result = result |inByte;
  }
  // take the chip select high to de-select:
  digitalWrite(chipSelectPin, HIGH); 
  // return the result:
  return(result);
}

I tried to mix them, but i've 0 knowledge in Arduino, our teacher doesn't learn us how it's works.
Can you please help us with mixing them.

Hi, This is a very common problem: adding two or more working sketches into one sketch. We really need a good guideline on this.

Has anyone seen a guideline or document on this subject? I'd like to host it on the http://ArduinoInfo.Info WIKI If nothing shows up, I'll put it on my ToDo list...

Putting a bunch of code together and then getting a Zillion error messages is No Fun!

FIRST! Start by understanding both sketches and the resources and libraries they use before attempting to stitch them together. If there is any part of either sketch you don't understand, that will be the part that causes you trouble.

For now, what I suggest is go to Arduino Software and then Example Sketches on the http://ArduinoInfo.Info WIKI here:

See the Sketch Template here: http://arduino-info.wikispaces.com/YourDuinoStarter_SketchTemplate . Copy and Paste that into a blank IDE window.

Copy the sections from ONE of your existing sketches into the sections of that template. Verify that to make sure it is all OK. Save with a name.
Get another blank window and sketch template. Copy you second working sketch into that and make sure it verifies OK. Save with name.
Get ANOTHER blank window and sketch template. Copy the sections, one by one, and run Verify after each thing you add.

/-----( Import needed libraries )-----/
Copy the #define statements for libraries one at a time and Verify after each one. If you have obvious Library Conflicts you'll know that right here.

/-----( Declare Constants and Pin Numbers )-----/
#define your pin numbers here. See if you have any conflicts. Verify.

/-----( Declare objects )-----/
Example: your "EthernetServer server(80);" Verify. See if any conflicts here.

/-----( Declare Variables )-----/
Copy in both sets of variables, check for conflicts, Verify.

void setup() /****** SETUP: RUNS ONCE ******/
Start adding statements in SETUP from both sketches, Verify often.

void loop() /****** LOOP: RUNS CONSTANTLY ******/
This is the hard part, because the code and logic has to work in the right sequence and with workable timing.

Really think through the code in each sketch. Figure out how it can work together. You MAY have to change the way some things are done. NonTrivial!

/-----( Declare User-written Functions )-----/
Functions can go After "LOOP". I suggest you copy the functions you have, like "boolean comparetag(int aa[14], int bb[14])" and "void readTag() " into this area to keep things organized.

Personally, I like to have LOOP just contain three functions as shown in this example: http://arduino-info.wikispaces.com/YourDuinoStarter_AutomationExample

OK, this is difficult, but I hope this will help you stay organized and find problems one at a time.

Divide and Conquer!

Terry:

Great effort. Thanks for doing it.

May I offer a friendly amendment? There is a missing Step 0 which usually turns out to be actual the root cause of problems new coders have combining sketches:

  1. Start by understanding both sketches and the resources and libraries they use before attempting to stitch them together. If there is any part of either sketch you don't understand, that will be the part that causes you trouble.

This might be called Dr. Frankenstein's Law...

Cheers,

-br

There is a missing Step 0 which usually turns out to be actual the root cause of problems new coders have combining sketches:

Oh, yeah! Great point. Stolen, added above :slight_smile:
Thanks, br !

UPDATE: I added a page on the http://ArduinoInfo.Info WIKI about this issue, here: http://arduino-info.wikispaces.com/CombiningArduinoSketches

Anyone with suggestions or pointers to other guidelines etc. please email me...

Please see the new post about this here: http://arduino.cc/forum/index.php/topic,159406.0.html

Have you solved your problem? As i have the same, i'd like to know your experience.

Have a look at this Simple Merge Demo

Then post your best attempt at merging your codes. If your merged code won't compile please post the compiler error messages.

...R

I'v followed your advice merging sketches, and compile goes fine.
But actually web() function is not working.
Here is my code:

#include <Wire.h>
#include <SPI.h>
#include <Adafruit_PN532.h>
#include <etherShield.h>
#include <ETHER_28J60.h>

#define PN532_SCK  (2)
#define PN532_MOSI (3)
#define PN532_SS   (4)
#define PN532_MISO (5)

#define PN532_IRQ   (2)
#define PN532_RESET (3)  // Not connected by default on the NFC Shield

Adafruit_PN532 nfc(PN532_SCK, PN532_MISO, PN532_MOSI, PN532_SS);

static uint8_t mac[6] = {0x54, 0x55, 0x58, 0x10, 0x10, 0x24};
static uint8_t ip[4] = {192, 168, 2, 15};
static uint16_t port = 80;

ETHER_28J60 ethernet;

void setup() {
  Serial.begin(115200);
  Serial.println("Hello!");

  nfc.begin();

  ethernet.setup(mac, ip, port);

  uint32_t versiondata = nfc.getFirmwareVersion();
  if (! versiondata) {
    Serial.print("Didn't find PN53x board");
    while (1);
  }

  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);

  nfc.setPassiveActivationRetries(0xFF);

  nfc.SAMConfig();

  Serial.println("Waiting for an ISO14443A card");
}

void loop() {
  readTag();
  web();
}


void readTag () {

  boolean success;
  uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
  uint8_t uidLength;        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)
  uint8_t readCard[4];
  uint8_t checkArray[][4] =
  {
    {0xAA, 0xAA, 0xAA, 0xAA},
    {0xBB, 0xBB, 0xBB, 0xBB},
    {0xCC, 0xCC, 0xCC, 0xCC},
    {0xDD, 0xDD, 0xDD, 0xDD},
    {0xEE, 0xEE, 0xEE, 0xEE},
    {0xFF, 0xFF, 0xFF, 0xFF},
  };

  success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, &uid[0], &uidLength);

  if (success) {
    for (int i = 0; i < 4; i++) {
      readCard[i] = uid[i];
      Serial.println(readCard[i], HEX);
    }

    Serial.println("Found a card!");
    Serial.print("UID Length: "); Serial.print(uidLength, DEC); Serial.println(" bytes");
    Serial.print("UID Value: ");
    for (uint8_t i = 0; i < uidLength; i++)
    {
      Serial.print(" 0x");
      Serial.print(uid[i], HEX);
    }
    Serial.println("");
  }
  else
  {
    Serial.println("Timed out waiting for a card");
  }

  Serial.println("Checking Match");

  for (int i = 0; i < 6; i++)
  {
    Serial.print("Testing Match with checkArray ");
    Serial.println(i);
    if ((memcmp(readCard, checkArray[i], 4)) == 0)
    {
      Serial.println("Arrays Match");
      analogWrite(7, 255);
      delay(800);
      analogWrite(7, 0);
      delay(5000);
      break;
    }

    else
      Serial.println("No Match");
  }
}

void web() {

  char* params;
  if (params = ethernet.serviceRequest())
  {
    {
      ethernet.print("Hola, bro!");
      ethernet.print("
");
    }
    ethernet.respond();
    delay(100);
  }
}

tejunk:
But actually web() function is not working.

How do you know?
What actually happens (or does not happen) ?

You have some huge delay()s in your readTag() function. I suspect they might get in the way - but as you have not explained what the overall program is supposed to do I don't know.

...R