# Question
Title: My outputs are not outputting any current at only two of my pinmodes but work fine on the others
My pinMode output 5 and 6 don't works with this code but will work when they are stand alone.

What is causing the Arduino to not output anything from these outputs within my code?

```
#include <SoftwareSerial.h>                    // use the software serial library
SoftwareSerial mySerial(3,4); // receive data at pin 3; transmit data at pin 2
int setpoint;
float val;
int roomtemp;
int UCL;
int LCL;

float salinity;
void setup()
{
    // put your setup code here, to run once:
    Serial.begin(9600);
    pinMode(5,OUTPUT);
    pinMode(6,OUTPUT);
    pinMode(3,OUTPUT);
    pinMode(2, OUTPUT);
    roomtemp=25;
    setpoint=7.0291*roomtemp+334.73;
    UCL=setpoint+6.12;
    LCL=setpoint-6.12;
    Serial.print("Setpoint =");
    Serial.print(setpoint);
    Serial.print("Degrees Celsius");
    Serial.print("UCL =");
    Serial.print(UCL);
    Serial.print("Degrees Celsius");
    Serial.print("LCL =");
    Serial.print(LCL);
    Serial.print("Degrees Celsius");
    mySerial.begin(9600);
    delay(500);           // set data rate to 9600 baud; wait for bootup
    mySerial.write(254);
    mySerial.write(128);
    mySerial.write(254);
    mySerial.write(1);    // clear screen & move to top left position
    mySerial.write(254);
    mySerial.write(132);
    mySerial.print("LCL");
    mySerial.write(254);
    mySerial.write(139);
    mySerial.print("SP");
    mySerial.write(254);
    mySerial.write(144);
    mySerial.print("UCL");
    mySerial.write(254);
    mySerial.write(192);
    mySerial.print("S:");
    mySerial.write(254);
    mySerial.write(195);
    mySerial.print(0.072,3);
    mySerial.write(254);
    mySerial.write(201);
    mySerial.print(0.100,3);
    mySerial.write(254);
    mySerial.write(207);
    mySerial.print(0.108,3);
    mySerial.write(254);
    mySerial.write(148);
    mySerial.print("T:");
    mySerial.write(254);
    mySerial.write(152);
    mySerial.print("24.1");
    mySerial.write(254);
    mySerial.write(158);
    mySerial.print("25.0");
    mySerial.write(254);
    mySerial.write(164);
    mySerial.print("25.9");
    mySerial.write(254);
    mySerial.write(212);
    mySerial.write(254);
    mySerial.write(212);
    mySerial.print("S=");
    mySerial.write(254);
    mySerial.write(220);
    mySerial.print("T=");
}

void loop()
{
    Serial.println();
    int val=analogRead(5);
    Serial.print("Analog Value =");
    Serial.print(val);
    Serial.print("Temperature =");
    Serial.println((0.14227*val)-47.621);

    if(val<LCL) { digitalWrite(3,HIGH); }
    else if(val>UCL) { digitalWrite(3,LOW); }

    mySerial.write(254);
    mySerial.write(227);

    if(val<LCL) { mySerial.write("H= ON"); }

    mySerial.write(254);
    mySerial.write(227);

    if(val>UCL) { mySerial.write("H=OFF"); }

    digitalWrite(2, HIGH);
    delay(100);
    int analogS=analogRead(4);
    digitalWrite(2, LOW);
    Serial.println(analogS);
    delay(1000);
    salinity = 2.0955*pow(10,-19)*pow(analogS,5.8106)*100.000;
    Serial.print("Salinity =");
    Serial.println(salinity);
    mySerial.write(254);
    mySerial.write(214);
    mySerial.print(salinity);
    mySerial.write(254);
    mySerial.write(222);
    mySerial.print((0.14227*val)-47.621,1);
    Serial.println("analog value");
    Serial.print(analogRead(4));
    float target= (salinity-(salinity-.1)*.60);
    float numer=((((target)*.08585-(salinity)*.08585)/(.1-(.1*.15+salinity*.85)))*60.0);
    float denom= ((.1));
    float valve= ((numer/denom)/10.00);

    if(.096<salinity>.104) {
        delay(5000);
    }

    if(salinity>.104) {
        Serial.print("Entering DIon Function");
        digitalWrite(6,HIGH);
        delay(valve);
        digitalWrite(6,LOW);
        delay(5000);
    }

    if(salinity<.096) {
        Serial.print("Entering Saltyon Function");
        digitalWrite(5,HIGH);
        delay(valve);
        digitalWrite(5,LOW);
        delay(5000);
    }

    Serial.print("time");
    Serial.println(valve);
}

```

# Answer
I think the problem is not in the output pin (which you say works elsewhere) but in your calculations. I made a Minimal, Complete, and Verifiable example of the part of the code that does the calculations, testing every possible reading you might have got from `analogRead(4)` (mainly because I found the calculations code rather obscure). Here it is:

```
float salinity;
void setup()
  {
  Serial.begin(9600);
  }

void loop()
  {
  for (int analogS=0; analogS < 1024; analogS++)
    {
    Serial.print ("analogS = ");
    Serial.print (analogS);
    salinity = 2.0955*pow(10,-19)*pow(analogS,5.8106)*100.000;
    Serial.print (", Salinity = ");
    Serial.print (salinity);
    float target= (salinity-(salinity-.1)*.60);
    float numer=((((target)*.08585-(salinity)*.08585)/(.1-(.1*.15+salinity*.85)))*60.0);
    float denom= ((.1));
    float valve= ((numer/denom)/10.00);
    Serial.print(",  valve = ");
    Serial.println(valve);
    }
   Serial.flush ();
   exit (1);
  }

```

Testing that reveals:

```
analogS = 0, Salinity = 0.00,  valve = 3.64
analogS = 1, Salinity = 0.00,  valve = 3.64
analogS = 2, Salinity = 0.00,  valve = 3.64
analogS = 3, Salinity = 0.00,  valve = 3.64
... some lines omitted ...
analogS = 1016, Salinity = 6.21,  valve = 3.64
analogS = 1017, Salinity = 6.25,  valve = 3.64
analogS = 1018, Salinity = 6.28,  valve = 3.64
analogS = 1019, Salinity = 6.32,  valve = 3.64
analogS = 1020, Salinity = 6.35,  valve = 3.64
analogS = 1021, Salinity = 6.39,  valve = 3.64
analogS = 1022, Salinity = 6.43,  valve = 3.64
analogS = 1023, Salinity = 6.46,  valve = 3.64

```

As you can see, `valve` is always 3.64, so you will be doing this:

```
    digitalWrite(6,HIGH);
    delay(3);
    digitalWrite(6,LOW);

```

In other words, port 6 will be HIGH for 3 milliseconds, probably too short a time for you to notice. Ditto for port 5.

---

Also this doesn't do what I suspect you think it does:

```
if(.096<salinity>.104) {
    delay(5000);
}

```

That will evaluate `.096 < salinity` to be 0 or 1. Then it will evaluate:

```
0 > 0.104
1 > 0.104

```

This is not what you are intending, I think. Try:

```
if(salinity < .096 || salinity > .104) {
    delay(5000);
}

```

If that is what you mean, I can't be sure - maybe you mean the opposite:

```
if(salinity > .096 && salinity < .104) {
    delay(5000);
}

```

If you write things out clearly, without trying to do shortcuts, it will be much more obvious what the test really is.
> 1 votes

---
Tags: arduino-uno, code-review
---


title: Arduino with HC 08 bluetooth module

text:
# Question
Title: Arduino with HC 08 bluetooth module
I am connecting Arduino Uno R3 with HC 08 module lie following

```
Arduino 5v -> HC 08 Vcc
Arduino gnd -> HC 08 gnd
Arduino Pin 5 -> HC 08 RXD
Arduino Pin 6 -> HC 08 TXD

```

Then I connected two LEDs to 9 and 10 pins

Then loading following sketch.

```
#include <SoftwareSerial.h>

int availableLEDpin = 9;
int notAvailableLEDpin = 10;
SoftwareSerial hc_08(5, 6); // RX-5, TX-6
void setup() {
  pinMode(availableLEDpin, OUTPUT);
  pinMode(notAvailableLEDpin, OUTPUT);
  Serial.begin(9600);
  hc_08.begin(9600);

}

void loop() {
  hc_08.listen();
  if (hc_08.available()) {
    Serial.println(hc_08.read());
    digitalWrite(availableLEDpin, HIGH);
    digitalWrite(notAvailableLEDpin, LOW);

  }
  else {
    digitalWrite(availableLEDpin, LOW);
    digitalWrite(notAvailableLEDpin, HIGH);
  }
  delay(100);
}

```

I am trying to connect to bluetooth from y iOS application. The application is searching and connecting to the HC 08 correctly. And sending data successfully - Swift code log showing sent successfully.

But back in Arduino, always led connected to pin notAvailableLEDpin is glowing and nothing is printing in serial monitor. What is wrong with my implementation?

# Answer
> 1 votes
You have the receive port on your arduino connected to the receive port on your bluetooth module. Connect pin 5 to the Tx on your module and connect pin 6 to the Rx on your module.

# Answer
> 0 votes
it's better to use digital pin 8/10 as RX, digital pin 9/11 and TX as your softwareserial pins since these pins are dedicated for softwareserial knowing you use the generic softwareserial library and mind your supply to only use 3v3 volts as much as possible, specially for the TX softwareserial pin of your arduino going to RX pin of HC08, you need to lessen the voltage output of that arduino pin into 3v3 volt also, using voltage divider. It will harm your HC08 module and might not work properly.

---
Tags: arduino-uno, bluetooth, softwareserial
---


# Question
Title: My shield does not have further female headers? How do I stack more shields?
I purchased a motor shield (L293D) and it doesn't have the female header which I can connect to another shield. What can I do to stack up more shields? For being more specific I ordered my shield from here: https://www.amazon.in/Simple-Labs-SLAEX039-Shield-Arduino/dp/B00K2Z3GAE/ref=sr\_1\_1?ie=UTF8&qid=1518767182&sr=8-1&keywords=motor+shield+for+arduino+uno&dpID=41h0ag2SCgL&preST=\_SX342\_QL70\_&dpSrc=srch

And please tell me how to do it because it is new for me. A guide or something?

# Answer
> 2 votes
Many shields cannot be stacked, even if you replace the headers. The biggest reason is that the shield uses most of, if not all, the available pins. Motor shield often fall into this category, so they don't add the pointless expense of stackable headers.

Before you consider stacking any shields, whether they have stackable headers or not, you first need to learn how the shields work and what pins they require to ensure there are no conflicts.

---
Tags: shields
---


# Question
Title: Determine an earthquake intensity/magnitude level using ADXL345 and Arduino
I want to create a project using Arduino that monitor the Earthquake. I used an ADXL345 Accelerometer to detect if there is an earthquake. I used the Adafruit ADXL345 example to determine a acceleration of x-axis, y-axis and z-axis in terms of m/s^2. I want to used the Japan Meteorological Agency seismic intensity scale to determine the intensity level of the earthquake because it gives the Peak Ground Acceleration. If there is a way to determine the earthquake intensity level using ADXL345?

# Answer
> 0 votes
\[Copied from https://stackoverflow.com/questions/48365221/accelerometer-using-adxl345-for-earthquake-detection\]

That sensor is not suitable. It has 13 bit resolution at +-16g full range. That gives you a sensitivity of 0.002g for the lsb. In order to detect an earthquake directly below you, you need approx. a few milli-g (e.g. see here), even less for earthquakes with an epicentre elsewhere.

You want a sensor which is much more sensitive by a factor of 100 and probably with more resolution (better ADC), too.

(And you should have been able to do this quick google-search analysis yourself ;) )

---
Tags: arduino-mega, accelerometer
---


# Question
Title: ESP-01 adapter and logic level converter
I read that I'll need a logic level converter like this to run an ESP8266-01 from the Uno.

But I saw this ESP adapter:

http://www.ebay.com/itm/ESP-01-ESP8266-Serial-Wi-Fi-Wireless-Adapter-Module-3-3V-5V-Compatible-Arduino-/282524471281?hash=item41c7c54ff1:g:wp0AAOSwQ59ZaClP

Two questions:

1. The ESP-01 has 8 connections but this has only 4, how come? Will I get the same functionality?
2. If I'll use this adapter, then I won't need the logic level converter?

# Answer
The module has a 3.3V voltage regulator circuit and **5v-3.3v onboard level conversion circuit**.

Yes, the module can be used with Arduino UNO R3 or compatible board without needing an additional level converter, as it is integrated in the module.

The module has Vcc, GND, TX and RX, so it means it uses a serial protocol for Arduino communication (and you will need two pins in the Arduino). Other pins in the ESP-01 are not needed in this scenario, but you still have access to them via the 8-pins female connector on the module.

It's totally plug and play.

**Addendum: The old way**

This how you connect a standard ESP-01 with an Arduino. The module you are looking at include all the resistors and also connect the CH\_PD pin to Vcc. You only need to connect four pins. It saves you time, money and space.
> 4 votes

# Answer
The ESP-01 is a microcontroller that works only with 3.3V. If you don't use a logic converter, it will not work correctly with 5V on TX and RX and you might even damage your module if you use it like that. So answering your second question, the important thing to keep in mind is that you need to power it with 3.3V and the logic level of the data you send must also be 3.3V.

As for the number of pins, the 4 pins are for VCC, GND, TX and RX. These are the only ones you'll need to connect with Arduino. The other pins on the ESP-01 are CH\_PD, RST and two GPIOs.

(I'm not sure if you need to connect any of these while using it with Arduino, but in my experience using it standalone i know CH\_PD must be connected to VCC in operation mode, and RST must be connected with GND on flashing mode.)
> 1 votes

# Answer
I used in one of my projects, instead of a logic level converter, some voltage dividers on the pins, Arduino inputs don't mind the 3.3v, it works just the same.
> 0 votes

---
Tags: arduino-uno, esp8266, voltage-level, adapter
---


# Question
Title: Using the physical serial port on a BSFrance LoRa32u4?
I can use the serial-over-USB channel by simply using `Serial` in my code.

The LoRa32u4 has an RXD1 and TXD1 pair on pins 20/21 (Arduino 0/1).

https://docs.bsfrance.fr/documentation/11296\_LORA32U4/LoRa32u4\_pinout\_diagram.pdf

How do I configure and use this serial port (for receiving NMEA GPS)?

# Answer
> 1 votes
> \[ATmega32U4-based boards use\] Serial1 to communicate via TTL (5V) serial on pins 0 (RX) and 1 (TX). Serial is reserved for USB CDC communication. For more information, refer to the Leonardo getting started page and hardware page.

---
Tags: serial, atmega32u4
---


# Question
Title: How to measure electrical conductivity using Arduino?
I want to measure TSS (Total soluble salt) in the soil. I have found in some literature that, through measuring of electrical conductivity, it is much easier to measure TSS. So, I thought, If I can measure electrical conductivity, it might be possible to find out TSS.

Logic behind the TSS is that, pure water is poor conductor of electric, increasing of soluble salt in water proportionately lift up the conductivity. So are there any sensors that readily measure conductivity? A point I also want to mention, can a voltmeter be useful for that?

# Answer
The answer is Three Dollar EC - PPM Meter \[Arduino\]. I tried it against a consumer level EC meter and got the same results after calibration. It's cheap and simple.

The only warning is that there is several scales in use to measure EC, so results may not be comparable between diferentes devices **and** you have to read carefully the EC recomendations for your water solution.

**EC units**

Electrical conductivity can be expressed using a number of different units, but the typical unit is siemens per meter2 per mole (S/m2/mole) or millisiemens per centimetre (mS/cm). The mS/cm unit is generally used in Europe as a guide to the concentration of nutrients in water. In North America, conductivity is converted into a count of the ions in the water using parts per million (which can also be converted into units including mg/l etc.). This is done by converting the EC into a value based on the ions contained in the solution. Fortunately, there is a fixed calculation for the relationship between all these units, which is given in the table below.

**Code for the EC meter**

```
/*
  ElCheapo Arduino EC-PPM measurments

  This scrip uses a common USA two prong plug and a 47Kohm Resistor to measure the EC/PPM of a Aquaponics/Hydroponics Sytem.
  You could modift this code to Measure other liquids if you change the resitor and values at the top of the code.

  This Program will give you a temperature based feed controller. See Read me in download file for more info.

  28/8/2015  Michael Ratcliffe  Mike@MichaelRatcliffe.com

          This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see .

    Parts:
    -Arduino - Uno/Mega
    -Standard American two prong plug
    -1 kohm resistor
    -DS18B20 Waterproof Temperature Sensor

    Limitations:
    -
    -

    See www.MichaelRatcliffe.com/Projects for a Pinout and user guide or consult the Zip you got this code from

*/

#include <OneWire.h>
#include <DallasTemperature.h>

//************************* User Defined Variables ********************************************************//

int R1= 1000;
int Ra=25;          //Resistance of powering Pins
int ECPin= A0;
int ECGround=A1;
int ECPower =A4;

//*********** Converting to ppm [Learn to use EC it is much better**************//
// Hana      [USA]        PPMconverion:   0.5
// Eutech    [EU]         PPMconversion:  0.64
// Tranchen  [Australia]  PPMconversion:  0.7
// Why didnt anyone standardise this?

float PPMconversion=0.5;

//*************Compensating for temperature ************************************//
// The value below will change depending on what chemical solution we are measuring
// 0.019 is generaly considered the standard for plant nutrients [google "Temperature compensation EC" for more info
float TemperatureCoef = 0.019; //this changes depending on what chemical we are measuring

//********************** Cell Constant For Ec Measurements *********************//
// Mine was around 2.9 with plugs being a standard size they should all be around the same
// But If you get bad readings you can use the calibration script and fluid to get a better estimate for K
float K=2.34;

//************ Temp Probe Related *********************************************//
#define ONE_WIRE_BUS 10          // Data wire For Temp Probe is plugged into pin 10 on the Arduino
const int TempProbePossitive =8;  //Temp Probe power connected to pin 9
const int TempProbeNegative=9;    //Temp Probe Negative connected to pin 8

//***************************** END Of Recomended User Inputs *****************************************************************//

OneWire oneWire(ONE_WIRE_BUS);// Setup a oneWire instance to communicate with any OneWire devices
DallasTemperature sensors(&oneWire);// Pass our oneWire reference to Dallas Temperature.

float Temperature=10;
float EC=0;
float EC25 =0;
int   ppm =0;

float raw= 0;
float Vin= 5;
float Vdrop= 0;
float Rc= 0;
float buffer=0;

//*********************************Setup - runs Once and sets pins etc ******************************************************//
void setup()
{
    Serial.begin(9600);
    pinMode(TempProbeNegative , OUTPUT);  //seting ground pin as output for tmp probe
    digitalWrite(TempProbeNegative , LOW); //Seting it to ground so it can sink current
    pinMode(TempProbePossitive , OUTPUT); //ditto but for positive
    digitalWrite(TempProbePossitive , HIGH);
    pinMode(ECPin,INPUT);
    pinMode(ECPower,OUTPUT);//Setting pin for sourcing current
    pinMode(ECGround,OUTPUT);//setting pin for sinking current
    digitalWrite(ECGround,LOW);//We can leave the ground connected permanantly

    delay(100);// gives sensor time to settle
    sensors.begin();
    delay(100);
    //** Adding Digital Pin Resistance to [25 ohm] to the static Resistor *********//
    // Consule Read-Me for Why, or just accept it as true
    R1=(R1+Ra);// Taking into acount Powering Pin Resitance

    Serial.println("ElCheapo Arduino EC-PPM measurments");
    Serial.println("By: Michael Ratcliffe  Mike@MichaelRatcliffe.com");
    Serial.println("Free software: you can redistribute it and/or modify it under GNU ");
    Serial.println("");
    Serial.println("Make sure Probe and Temp Sensor are in Solution and solution is well mixed");
    Serial.println("");
    Serial.println("Measurements at 5's Second intervals [Dont read Ec morre than once every 5 seconds]:");
}

void loop()
{
    GetEC();          //Calls Code to Go into GetEC() Loop [Below Main Loop] dont call this more that 1/5 hhz [once every five seconds] or you will polarise the water
    PrintReadings();  // Cals Print routine [below main loop]
    delay(5000);
}

void GetEC()
{
    sensors.requestTemperatures();          // Send the command to get temperatures
    Temperature=sensors.getTempCByIndex(0); //Stores Value in Variable
    //************Estimates Resistance of Liquid ****************//
    digitalWrite(ECPower,HIGH);
    raw= analogRead(ECPin);
    raw= analogRead(ECPin);// This is not a mistake, First reading will be low beause if charged a capacitor
    digitalWrite(ECPower,LOW);

    //***************** Converts to EC **************************//
    Vdrop= (Vin*raw) / 1024.0;
    Rc = (Vdrop*R1) / (Vin-Vdrop);
    Rc = Rc-Ra; //acounting for Digital Pin Resitance
    EC = 1000/ (Rc*K);

    //*************Compensating For Temperaure********************//
    EC25  =  EC / (1+ TemperatureCoef*(Temperature-25.0));
    ppm=(EC25)*(PPMconversion*1000);
}

//***This Loop Is called From Main Loop- Prints to serial usefull info ***//
void PrintReadings()
{
    Serial.print("Rc: ");
    Serial.print(Rc);
    Serial.print(" EC: ");
    Serial.print(EC25);
    Serial.print(" Simens  ");
    Serial.print(ppm);
    Serial.print(" ppm  ");
    Serial.print(Temperature);
    Serial.println(" *C ");
};

```

**Code for calibration**

```
/*
  ElCheapo Arduino EC-PPM measurments Calibration

  This Script is used for calibration of the sensor and fine tuning of the Cell Constant K
  Submerge the sensor and temperature probe in the calibration solution and leave for a while so the temperature probe can settle
  Change the value of the calibration solution to suit the solutiton strength
  Stir the probe to make sure the solution is well mixed and upload the code to the arduino
  Open the terminal for an update of the estimated Cell Constant K [should be around 3] and use this new value in the main EC code.

  28/8/2015  Michael Ratcliffe  Mike@MichaelRatcliffe.com

          This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see .

    Parts:
    -Arduino - Uno/Mega
    -Standard American two prong plug
    -1 kohm resistor
    -DS18B20 Waterproof Temperature Sensor

    See www.MichaelRatcliffe.com/Projects for a Pinout and user guide or consult the Zip you got this code from

*/

//************************** Libraries Needed To Compile The Script [See Read me In Download] ***************//
// Both below Library are custom ones [ SEE READ ME In Downloaded Zip If You Dont Know how To install Use them or add a pull up resistor to the temp probe

#include <OneWire.h>
#include <DallasTemperature.h>

//************************* User Defined Variables ********************************************************//

float CalibrationEC = 0.762; //EC value of Calibration solution is s/cm

//##################################################################################
//-----------  Do not Replace R1 with a resistor lower than 300 ohms    ------------
//##################################################################################
int R1 = 1000;
int Ra = 25; //Resistance of powering Pins
int ECPin = A0;
int ECGround = A1;
int ECPower = A4;

//*************Compensating for temperature ************************************//
//The value below will change depending on what chemical solution we are measuring
//0.019 is generaly considered the standard for plant nutrients [google "Temperature compensation EC" for more info
float TemperatureCoef = 0.019; //this changes depending on what chemical we are measuring

//************ Temp Probe Related *********************************************//
#define ONE_WIRE_BUS 10          // Data wire For Temp Probe is plugged into pin 10 on the Arduino
const int TempProbePossitive = 8; //Temp Probe power connected to pin 9
const int TempProbeNegative = 9;  //Temp Probe Negative connected to pin 8

//***************************** END Of Recomended User Inputs *****************************************************************//

OneWire oneWire(ONE_WIRE_BUS);// Setup a oneWire instance to communicate with any OneWire devices
DallasTemperature sensors(&oneWire);// Pass our oneWire reference to Dallas Temperature.

float TemperatureFinish = 0;
float TemperatureStart = 0;
float EC = 0;
int ppm = 0;

float raw = 0;
float Vin = 5;
float Vdrop = 0;
float Rc = 0;
float K = 0;
int i = 0;
float buffer = 0;

//*********************************Setup - runs Once and sets pins etc ******************************************************//
void setup()
{
    Serial.begin(9600);
    pinMode(TempProbeNegative , OUTPUT);  //seting ground pin as output for tmp probe
    digitalWrite(TempProbeNegative , LOW); //Seting it to ground so it can sink current
    pinMode(TempProbePossitive , OUTPUT); //ditto but for positive
    digitalWrite(TempProbePossitive , HIGH);
    pinMode(ECPin, INPUT);
    pinMode(ECPower, OUTPUT); //Setting pin for sourcing current
    pinMode(ECGround, OUTPUT); //setting pin for sinking current
    digitalWrite(ECGround, LOW); //We can leave the ground connected permanantly

    delay(100);// gives sensor time to settle
    sensors.begin();
    delay(100);
    //** Adding Digital Pin Resistance to [25 ohm] to the static Resistor *********//
    // Consule Read-Me for Why, or just accept it as true
    R1 = (R1 + Ra);

    Serial.println("ElCheapo Arduino EC-PPM measurments Calibration");
    Serial.println("By: Michael Ratcliffe  Mike@MichaelRatcliffe.com");
    Serial.println("Free software: you can redistribute it and/or modify it under GNU ");
    Serial.println("");
    Serial.println("Make sure Probe and Temp Sensor are in Solution and solution is well mixed");
    Serial.println("");
    Serial.println("Starting Calibration: Estimated Time 60 Seconds:");
};
//******************************************* End of Setup
//************************************* Main Loop - Runs Forever ***************************************************************//
//Moved Heavy Work To subroutines so you can call them from main loop without cluttering the main loop
void loop()
{
    i = 1;
    buffer = 0;
    sensors.requestTemperatures();// Send the command to get temperatures
    TemperatureStart = sensors.getTempCByIndex(0); //Stores Value in Variable

    //************Estimates Resistance of Liquid ****************//
    while(i <= 10) {
        digitalWrite(ECPower, HIGH);
        raw = analogRead(ECPin);
        raw = analogRead(ECPin); // This is not a mistake, First reading will be low
        digitalWrite(ECPower, LOW);
        buffer = buffer + raw;
        i++;
        delay(5000);
    };

    raw = (buffer / 10);

    sensors.requestTemperatures();// Send the command to get temperatures

    TemperatureFinish = sensors.getTempCByIndex(0); //Stores Value in Variable

    //*************Compensating For Temperaure********************//
    EC = CalibrationEC * (1 + (TemperatureCoef * (TemperatureFinish - 25.0))) ;

    //***************** Calculates R relating to Calibration fluid **************************//
    Vdrop = (((Vin) * (raw)) / 1024.0);

    Rc = (Vdrop * R1) / (Vin - Vdrop);

    Rc = Rc - Ra;

    K = 1000 / (Rc * EC);

    Serial.print("Calibration Fluid EC: ");

    Serial.print(CalibrationEC);

    Serial.print(" S  ");  //add units here

    Serial.print("Cell Constant K");

    Serial.print(K);

    if(TemperatureStart == TemperatureFinish) {
        Serial.println("  Results are Trustworthy");
        Serial.println("  Safe To Use Above Cell Constant in Main EC code");

    } else {
        Serial.println("  Error -Wait For Temperature To settle");
        Serial.print("Temp start=");
        Serial.print(TemperatureStart);
        Serial.print(" Temp end=");
        Serial.println(TemperatureFinish);
    }
}
//*************************** End Of Main Loop *******************************************************************//

```

EDIT:

Make sure to use a factory sealed male plug. If water get inside the plug, the voltage reading will be inaccurate.
> 6 votes

# Answer
That should be possible ... connect +5V to one end, an analog input pin on the other, don't forget a resistor which is high enough not to get more current than allowed. Than measure on the analog input pin the conductivity (value) and act on it.

Afaik the max amperage for an analog pin is 20 mA if I remember correctly. Thus a resistor of V = I * R \<=\> 5 = 0.02 * R \<=\> R = 5 / 0.02 = 250 ohm should be ok. This will only occur if the conductivity is 100%. If you get a very low conductivity than you will get very low numbers when reading the analog pin. When you get too less values, you have to lower the resistor value, but you risk of burning a pin when too much current gets across.
> 1 votes

---
Tags: electricity
---


# Question
Title: Is there a sensor to measure a distance between 2 point as in range [0-2 meter]?
I'm looking for a way of detecting if 2 pieces of hardware are within 2 meters of eachother or not. The idea is to build a prototype to lock computers automatically. I just need a recommendation on the sensor if it exists. Geofencing, bluetooth etc are not reliable enough.

# Answer
> 1 votes
You can use a lot of different methods with advantages/disadvantages:

* Use an IR LED/receiver and calculate the distance of travelling of the lights. Disadvantage: you need a very precise timing mechanism (light is fast), also take latency into account for non-light parts, and hardware needs to be in visible range and pointing to each other with LEDs)
* Use an ultrasonic sensor like SR-HC04. Disadvantage: devices must point to each other in a small precise angle.
* Using an RF method and sending/receiving e.g. via nRF24L01+ 2.4 GHz trasnceivers, to check the difference in time between sending and receiving when very close or a few meters apart. However, there might be aspects that might distort the result (other receivers/transmitters, what kind of material is in between, nRF antenna placement/direction etc). Using lowest speed (most reliable), highest power.

---
Tags: sensors
---


# Question
Title: Strange discrete errors when reading HC-SR04 sonar sensor
I'm experimenting with an HC-SR04 sonar sensor. Basically I'm measuring the distance to a cardboard box twice a second with these lines of code running on an ESP32:

```
unsigned long sonarMeasure() {
    digitalWrite(TRIGGER, HIGH);
    delayMicroseconds(10);
    digitalWrite(TRIGGER, LOW);
    return pulseIn(ECHO, HIGH);
}

double distance = duration * 0.03455;

```

The results are a bit strange. I know, that I can't expect millimeter accuracy. But why are there rather **discrete jumps of about 4 mm**? And when looking closer, there is **another frequent jump of \<1mm**:

(As far as I can tell, the jumps increase at larger distances.)

**Is this an issue of how I read the sensor on the ESP32, or is it something happening internally on the HC-SR04?**

I'd love to understand the reason for this effect to be able to improve the accuracy of my measurements.

# Answer
I think it's from the HC-SR04... it uses echos and it seems your bad readings are some kind of echo reflections.

What you should do is either remove the bad readings, or take the average/most common value of the last x readings.

Or throw away values too far off some default (like the last average) and average the rest.
> 1 votes

---
Tags: sensors, hc-sr04, timing, esp32
---


# Question
Title: RPM measurement using quadrature encoder
I am trying to build a RPM controller for my project. I am using a quadrature encoder (ppr=400) and Arduino Uno for this purpose. I am using the code given below inorder to caluculate the RPM of the DC motor. I get a reading on my serial Monitor. However, this RPM doesn't match with my manual calculation (i.e when I calculate the RPM Manually using a stop watch- for lower speeds).

EDIT-\> Eg- Manually I get around 10 RPM, but my program shows 60 and more.

I have used one interrupt pin on my Arduino UNO.

```
#define encoder0PinA  2
#define encoder0PinB  3
int power=6; // to power up the encoder
int gnd=4;  // to provide ground to the encoder
int motor=11; //motor PWM pin
int dir=10;
volatile unsigned int encoder0Pos = 0;

void setup() {
  pinMode(encoder0PinA, INPUT);
  digitalWrite(encoder0PinA, HIGH);       // turn on pull-up resistor
  pinMode(encoder0PinB, INPUT);
  digitalWrite(encoder0PinB, HIGH);       // turn on pull-up resistor
  pinMode(power,OUTPUT);
  pinMode(gnd,OUTPUT);
  digitalWrite(power,HIGH);
  digitalWrite(gnd,LOW);
  pinMode(motor,OUTPUT);
  pinMode(dir,OUTPUT);
  digitalWrite(dir,LOW);

  attachInterrupt(0, doEncoder, RISING);  // encoder pin on interrupt 0 - pin 2
  Serial.begin (9600);
  Serial.println("start");    // a personal quirk
  analogWrite(motor,120); // to set a particular test RPM to the motor.
}

void loop() {
  encoder0Pos=0;
  delay(1000);
  float rpm=encoder0Pos/(400);
  Serial.println(rpm);
}

void doEncoder() {

  encoder0Pos++;
  }

```

Also I tried the very first code on the following link "https://playground.arduino.cc/Main/RotaryEncoders".. In this case my Arduino stops transmitting completely. I tried the same code on one of my friend's setup.. surprisingly it works there. Can't understand where I am going wrong... Is my coding approach correct?? Please enlighten me... Thank you.

# Answer
Ensure the encoder outputs 400 pulses on each phase. It could be 200 on each phase for one rotation

Rather then clearing your pulseCount, figure out the time it take to make one rotation (as close as you can tell) and turn the motor on for only that amount of time, and then off again. This will allow you a more controlled environment to test your code in, and it will be the same(almost) every time.

You are calculating revolutions per second with your code, not per min number of pulses/400(if this is correct number)=Revolutions which you are clearing ever 1000ms

Ensure good connections on your wiring as it does not take much to allow the interrupt to fire twice when it should have only fired once.

Use the second phase of the encoder, this is what gives the ability to decipher bad signals and change of dirrection, ie- multiple A pulses in a row(without any B pulse) does not equal movement, it means either the motor is hanging out right on a phase line, or something is causing the interrupt to fire more often then it should.
> 1 votes

---
Tags: interrupt
---


# Question
Title: Using a Micro SD card for data logging, bad idea? Reliable?
I'm planning a project that will read data from an I/O board. The micro SD card would hold data for input bit identity, labeling ?, then logging after events end.

Nothing would be written to or read from the micro sd, unless an event takes place, usually 2-10 events/hour. System will run 24/7 for years, hopefully. Is a micro sd card the best way? Is it reliable enough?

# Answer
> 4 votes
We've been maintaining a network of loggers (60+ currently deployed) using SD card connected directly to the SPI pins (see: http://www.mdpi.com/1424-8220/18/2/530 for details) and our experience is that the SD cards are really reliable provided you don't have a brown-out when they are writing, even when we abuse them with hot surface deployments in the tropical sun. And we buy them used, (since the older, smaller Nokia & Sandisk cards have lower sleep currents) but test them well with H2testw. However there is one problem that develops over time: the actual SD adapters are not made that well, and tend to have solder flux residue left on the little pads used to hold the contact springs, and these will corrode over time if moisture gets in. I give everything a sonic bath in 90% isopropyl until the parts are squeaky clean, and then always put 2x10gram desiccant packs into the logger housings (with color indicator beads). If you are careful about the cleaning, the contacts last for years, but if you forget, and moisture gets into the housing, then the SD card contact spring solder points are often the first things to corrode.

# Answer
> 0 votes
As far as durability concern, SD cards are quite durable.

8-10 years data storage and operations would be OKAY. In a practical scenario, average time is about to 5-6 years.

Just you have to keep some important and necessary instructions/cautions keep in mind while dealing with SD card and for its long life.

Importantly, use standard standard manufacture SD card (suggestion - Swissbit)

* Don't store them below -40 °C or above +70 °C
* Don't pressurized

Here are a few links, which may help you.

https://superuser.com/questions/17350/whats-the-life-expectancy-of-an-sd-card

SD cards generally have wear leveling (https://en.wikipedia.org/wiki/Wear\_leveling)

Hope, this will helpful.

---
Tags: sd-card, datalogging
---


# Question
Title: SOMETHING WRONG IN DHT22 PROGRAM showing error as expected unqualified id before'. ' token
I am using a arduino and dht22 sensor for my project purpose annd gettting error as expecte before unqualified '.' token

MY CODE IS :

```
#include <DHT.h>

#include <LiquidCrystal.h>
#include <SoftwareSerial.h>
#include <Wire.h>

#define DHTPIN 8
#define DHTTYPE DHT22

LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

int ldrpin=A0;
int ldr=0;

DHT dht(DHTPIN, DHTTYPE);

//
//
//
//
//
//
//
//

void setup()
    {

   lcd.begin(16, 2);
   Serial.begin (9600);
   DHT .begin();
     pinMode(ldrpin,INPUT);

}

//
//
//
//
//
//
//

void loop()
    {

  lcd.setCursor(0,0);

 //ldr
  ldr=analogRead(ldrpin);

//LDR DISPLAY
  Serial.println("LIGHT INTENSITY");
  Serial.println(ldr);
  Serial.print(" lx\t");
  delay(2000);

   lcd.clear();
    lcd.setCursor(0, 0);

   lcd.print("LIGHT INTENSITY");
    delay(200);
    lcd.print(ldr);
      delay(2000);

//dht22
delay(2000);

   int chk = DHT.read(DHTPIN);
    float humidity = DHT.humidity;
    float temperature = DHT.temperature;

//dht22 display
1.  Serial.println("Humidity: ");
2.    Serial.print(h);
3.    Serial.print(" %\t");
4.    Serial.println("Temperature: ");
5.    Serial.print(t);
  Serial.println(" *C ");

```

my error message is

```
Arduino: 1.6.4 (Windows 8.1), Board: "Arduino Uno"

LCD.ino: In function 'void setup()':
LCD:38: error: expected unqualified-id before '.' token
LCD.ino: In function 'void loop()':
LCD:80: error: expected primary-expression before '.' token
LCD:81: error: expected primary-expression before '.' token
LCD:82: error: expected primary-expression before '.' token
LCD:87: error: expected ';' before 'Serial'
LCD:88: error: expected ';' before 'Serial'
LCD:89: error: expected ';' before 'Serial'
LCD:90: error: expected ';' before 'Serial'
LCD:91: error: expected ';' before 'Serial'
expected unqualified-id before '.' token

```

This report would have more information with "Show verbose output during compilation" enabled in File \> Preferences.

some one help me please!!

# Answer
Line 38, 80, 81, 82: `DHT` is a class name, `dht` is an instance of that class (an object, a variable), so write:

```
   dht.begin();

```

And all those call to DHT.something? Wrong too. Reemplaza DHT with dht.

All others errors: Why are you written "1. ", "2. ", before statements? Delete those numbers:

```
Serial.println("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.println("Temperature: ");
Serial.print(t);
Serial.println(" *C ");

```

Also, you are missing a "}" to end loop().

When you correct this errors, others will surface.
> 1 votes

---
Tags: arduino-uno, compilation-errors
---


# Question
Title: avr/io.h No such file or directory error when compiling using avr-gcc
I am trying to use the atmega328p as standalone microchip and program it. I ama using an Arduino Uno as ISP. I have written a simple program to test it however when I try to compile it using

```
avr-gcc -mmcu=atmega328p -o main.out main.c

```

I get the error:

```
main.c:1:20: fatal error: avr/io.h: No such file or directory
compilation terminated.

```

I am running OpenSUSE Leap 42.3 and i have installed **avr-gcc**, **avr-libc**.

My code:

```
#include <avr/io.h>

int main() {
    DDRB = 1;
    PORTB = 1;
}

```

Thank you in advance!

# Answer
I’m guessing you started with the toolchain Arduino put on your machine.

Try explicitly including the header files on the include path with the `-I` switch.

```
avr-gcc -mmcu=atmega328p -I /path/to/avr/include -o main.out main.c

```

Just search for the `io.h` file. It should be somewhere close by to where you found the compiler.
> 1 votes

---
Tags: c, linux, avr-toolchain, avr-gcc
---


# Question
Title: arduino rfid with led, code is compiling but not working as expected!
code is compiling, what I want is that when rfid tag kept led should get on but instead its getting to the else loop.

```
int count = 0;
char input[12]; // rfid input
int led = 3; // led pin
char first[20] = {"270059204B15"}; //rfid tag no
char a[24];

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(led, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (Serial.available() > 0) // code for rfid input
  { count = 0;
    while (Serial.available() && count < 12)
    {
      input[count] = Serial.read();
      count++;
      delay(10);
    }
    Serial.print(input);
  }

  if (strcmp(input, first) == 0) /*comparing two string rfid tag no and input
   if matches led is on*/
  {
    digitalWrite(led, LOW); /* as the board which we are using is in sink
    mode low is taken as 1 or on*/
    delay(500);
    Serial.print("led is on\n");
  }

  else
  { digitalWrite(led, HIGH);
    delay(500);
    Serial.print("led is off\n");
  }
}

```

# Answer
> 2 votes
Your unespecified problems are consecuence of a collection of small details.

1. You are not putting a binary zero to end the input string.
2. That's not the way to read serial input.
3. Code doesn't filter out control caracteres (LF, CR).

Here is your code cleaned up:

```
#define ID_SIZE 12

int count=0;
char input[ID_SIZE + 1]; // rfid input
int led=3; // led pin
char first[ID_SIZE + 1]= {"270059204B15"}; //rfid tag no

void setup()
{
    // put your setup code here, to run once:
    Serial.begin(9600);
    pinMode(led,OUTPUT);
}

void loop()
{

    // put your main code here, to run repeatedly:
    while(Serial.available() > 0 && count < 12) {  // code for rfid input
       char c = Serial.read();
       if (isAlphaNumeric(c)) {
          input[count++]=c;
          }
      }

    input[count] = 0;
    if(count >= 12) {
        Serial.print(input);
    }

    if(strcmp(input,first)==0) /*comparing two string rfid tag no and input
   if matches led is on*/
    {
        digitalWrite(led,LOW); /* as the board which we are using is in sink
    mode low is taken as 1 or on*/
        delay(500);
        Serial.println("led is on\n");
        input[0] = count = 0;
    }

    else {
        digitalWrite(led,HIGH);
        delay(500);
        Serial.println("led is off\n");
    }
}

```

And here is the result:

Edit:

The C strings are char arrays of undefined lenght. To signal the end of the string, put a binary zero next to the (effective) last element. Then, if you want to store a 10 chars string, you need an 11 elements arrays (10 for the string itself, 1 for the binary zero).

Failure to put a binary zero at the end of a string is a very common cause of program failure.

Control characters. In general, when you type "TEST" in the Serial Monitor and press SEND, what Arduino receive is the word TEST itself, plus a Line Feed/Carriage Return pair (LF/CR) to mark the end of the line.

In real world, your serial input can be *contaminated* with tabs, spaces, LF/CR and other valid chars. You need to discard them (unless they are valid for your app).

---
Tags: arduino-uno, led, rfid
---


title: uno timer0 prescale

text:
# Question
Title: uno timer0 prescale
I have a project where I need to get a low frequency to get a pwm suited from my project. The problem is that after I modify the frequency of timer0 the millis() becomes slower or faster depending on prescalar. So a fix as stated here is to change prescalar in wiring.c. But I don't know for what reason when I set it to 256 or 1024 the millis return 0. For 1-64 works fine.

```
Timer 0 uses a prescale factor which is set to 64 by default
To set the prescale factor use this line in the setup function

Setting                          Prescale_factor
TCCR0B = _BV(CS00);              1
TCCR0B = _BV(CS01);              8
TCCR0B = _BV(CS00) | _BV(CS01);  64
TCCR0B = _BV(CS02);              256
TCCR0B = _BV(CS00) | _BV(CS02);  1024

To use Fast PWM on Timer 0
Write this line in the setup function
TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM01) | _BV(WGM00);
And to calculate the PWM frequency, use
Fast_PWM_frequency = (16 000 000)/(Prescale_factor*256);

To use Phase-correct PWM on Timer 0 (half the frequency of Fast PWM)
Write this line in the setup function
TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM00);
And to calculate the PWM frequency, use
Phase_correct_PWM_frequency = (16 000 000)/(Prescale_factor*510);

Changing the prescale factor on Timer0 will affect functions
millis(), micros(), delay(),...

To adjust millis(), micros(), delay(),... accordingly,
You can modify a line in the wiring.c function in the Arduino program files
hardware\arduino\cores\arduino\wiring.c

In the beginning of wiring.c you can find:
// the prescaler is set so that timer0 ticks every 64 clock cycles, and the
// the overflow handler is called every 256 ticks.
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))

You need to modify the prescale factor in this function to the corresponding line

For fast PWM (default):
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(PRESCALE_FACTOR* 256))
For phase-correct PWM :
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(PRESCALE_FACTOR * 510))

```

# Answer
Integer math in C is done in an `int` or `unsigned int` by default. `int` is 16-bit on AVR. 256 * 256 overflows to 0, as does 1024 * 256. You will need to tell the compiler to perform the math in a longer type.

```
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(256 * 256L))

```
> 0 votes

---
Tags: timers, millis
---


title: UNO: AnalogRead results not as expected

text:
# Question
Title: UNO: AnalogRead results not as expected
I'm new to Arduino, and trying to build a project that will measure the voltage and current from two, unconnected, 12v batteries. The present test environment comprises:-

* a 13.8v power supply (run from the mains (240v)) which is powering two separate voltage dividers;
* a take-off from one voltage divider going to A0, the take-off to the second going to A3;
* a connection from Arduino GND to the -ve rail on the bread-board;

The voltage dividers are identical - both comprising 10kOhm and 200kOhm resistors - so I am expecting that an analogRead of A0 and A3 would return similar results, which they don't. A0 is up around the 344 mark, A3 is down around 133. So, the problem is that identical voltage dividers are not giving the same readings from the same input voltage.

Code and results follow, and I would be grateful for any hints, tips and further education!

Code follows

```
#define NUMBER_OF_SAMPLES 10
int looped = 0;

void setup()
{
  Serial.begin(57600);  Serial.println("Test sketch starting");
}

void loop()
{
  int temp1=0;
  int temp2=0;
  int temp3=0;

  looped++;

  for(int count=0; count<NUMBER_OF_SAMPLES; count++)
  {
    temp1 = analogRead(A0);
    temp3 += temp1;

    Serial.print("temp1 = ");
    Serial.print(temp1);    Serial.print(",");
    delay(200);
  }
  Serial.println(temp3);
  temp3 = 0;
  for(int count=0; count<NUMBER_OF_SAMPLES; count++)
  {

    temp2 = analogRead(A2);
    temp3 += temp2;
    Serial.print("temp2 = ");
    Serial.print(temp2);    Serial.print(",");
    delay(200);
  }
  Serial.println(temp3);
  Serial.println("");

  if(looped>NUMBER_OF_SAMPLES)
  {
    delay(500000);
  }
}

```

And this is the output.

```
Test sketch starting
temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,3450
temp2 = 129,temp2 = 125,temp2 = 137,temp2 = 137,temp2 = 126,temp2 = 136,temp2 = 134,temp2 = 136,temp2 = 132,temp2 = 132,1324

temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,3450
temp2 = 132,temp2 = 133,temp2 = 136,temp2 = 137,temp2 = 135,temp2 = 129,temp2 = 132,temp2 = 137,temp2 = 131,temp2 = 130,1332

temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 345,temp1 = 344,temp1 = 344,3448
temp2 = 133,temp2 = 134,temp2 = 132,temp2 = 128,temp2 = 133,temp2 = 134,temp2 = 131,temp2 = 125,temp2 = 130,temp2 = 129,1309

temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 345,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 345,3442
temp2 = 132,temp2 = 133,temp2 = 135,temp2 = 132,temp2 = 131,temp2 = 133,temp2 = 134,temp2 = 133,temp2 = 131,temp2 = 130,1324

temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,3440
temp2 = 133,temp2 = 133,temp2 = 131,temp2 = 133,temp2 = 132,temp2 = 133,temp2 = 133,temp2 = 130,temp2 = 133,temp2 = 138,1329

temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,3440
temp2 = 133,temp2 = 135,temp2 = 133,temp2 = 133,temp2 = 131,temp2 = 133,temp2 = 133,temp2 = 133,temp2 = 133,temp2 = 133,1330

temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,temp1 = 344,3440
temp2 = 131,temp2 = 134,temp2 = 128,temp2 = 134,temp2 = 134,temp2 = 132,temp2 = 132,temp2 = 132,temp2 = 132,temp2 = 133,1322

temp1 = 344,temp1 = 343,temp1 = 344,temp1 = 344,temp1 = 343,temp1 = 344,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 344,3435
temp2 = 142,temp2 = 141,temp2 = 135,temp2 = 135,temp2 = 135,temp2 = 133,temp2 = 134,temp2 = 133,temp2 = 133,temp2 = 132,1353

temp1 = 343,temp1 = 344,temp1 = 344,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,3432
temp2 = 135,temp2 = 130,temp2 = 136,temp2 = 135,temp2 = 141,temp2 = 130,temp2 = 135,temp2 = 133,temp2 = 134,temp2 = 131,1340

temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,3430
temp2 = 129,temp2 = 133,temp2 = 129,temp2 = 131,temp2 = 133,temp2 = 130,temp2 = 131,temp2 = 135,temp2 = 134,temp2 = 133,1318

temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,temp1 = 343,3430
temp2 = 131,temp2 = 135,temp2 = 130,temp2 = 128,temp2 = 137,temp2 = 136,temp2 = 136,temp2 = 131,temp2 = 134,temp2 = 134,1332

```

# Answer
Assuming you are using an Arduino Uno, I set up your test situation on my bench.

I modified the prints as jsotola suggested to move the "temp1 = " out of the loop.

I measured 0.670V on the A0 port and 0.666 on the A2 port.

We would expect 0.657V as per the Voltage Divider Calculator.

```
Vout = Vin * R2 / (R1 + R2)
13.8 * 10 / (200 + 10) = 0.657

```

As suggested on my page about the ADC the formula for converting a reading into a voltage is:

```
float voltage = ((float) rawADC  + 0.5 ) / 1024.0 * Vref;

```

Therefore a reading of 134 gives the correct results:

```
(134 + 0.5) / 1024 * 5 = 0.657

```

My results were:

```
Test sketch starting
temp1 = 133,134,133,134,134,134,134,134,134,134,1338
temp2 = 133,132,133,134,132,133,133,134,133,133,1330

temp1 = 134,134,134,134,133,134,134,134,134,134,1339
temp2 = 134,133,133,132,133,133,133,134,133,133,1331

temp1 = 134,134,134,133,134,134,134,133,134,134,1338
temp2 = 133,133,133,134,133,133,133,133,133,132,1330

temp1 = 134,134,133,135,134,134,134,134,134,134,1340
temp2 = 133,133,133,133,133,133,132,133,133,134,1330

temp1 = 134,134,134,134,134,134,134,134,134,134,1340
temp2 = 133,133,132,133,133,134,133,133,134,133,1331

temp1 = 134,133,133,134,134,133,134,134,134,134,1337
temp2 = 132,133,133,133,134,133,133,133,133,133,1330

temp1 = 134,134,134,135,134,133,134,134,134,134,1340
temp2 = 133,133,133,134,133,133,133,133,133,132,1330

```

This therefore shows that your sketch is working properly, and that there must be some electrical issue in your voltage divider or your connections.

---

The slight differences would be accounted for by noise in the voltage divider circuitry.
> 1 votes

---
Tags: analogread
---


# Question
Title: Arduino : How to write a variable value into a text file and modify it in the SD card?
I want to write a variable value into a text file in the SD card and modify it while reading if needed. I found a text reading code which reads a desired line in the text file.(not tested)

//reading code

```
#include <SD.h>

int stepToLoad = 1;
int endOfLineNumber = 0;
int stepCount = 0;
int stringIndex = 0;
File configFile;
char inputString [1280];
char inputChar;

void setup() {
  stepToLoad = 13;
  if (!SD.begin(36)) {
    return;
  }

  if (SD.exists("config.txt")) {
    configFile = SD.open("config.txt");
    getStepCount();
    getStepData();
    configFile.close();
  }
}

void loop() {

}

void getStepData() {

  if (configFile) {
    while (configFile.available()) {
      inputChar = configFile.read(); // Gets one byte from serial buffer
      if (inputChar != '^') { // define breaking char here

        inputString[stringIndex] = inputChar; // Store it
        stringIndex++; // Increment where to write next

      } else {
        endOfLineNumber++;
        stringIndex++;
        if (endOfLineNumber == stepToLoad) { //this is the correct line to load

          break; //break out of the "while" loop
        } else { //not the correct line to load, reset and continue

          stringIndex = 0;
        }
      }

    }

  }
}

void getStepCount() {
  if (configFile) {
    while (configFile.available()) {
      inputChar = configFile.read(); // Gets one byte from serial buffer
      if (inputChar == '^') { // define breaking char here
        stepCount++;
      }
    }
  }
}

```

# Answer
As far as I know it is not possible to read a file and meanwhile change a value.

What normally is done is:

* Read the file
* Store it in memory
* Change the value in memory
* Write the file

However, since the SRAM memory is very limited, the following approach is better:

* For every buffer (512 bytes):
    + Read 512 bytes buffer
    + Change values in the buffer if needed
    + Write 512 bytes to another file
    + Until the end of the file to read is reached
* Remove the original file
* Change the name of the new file to the old file
> 1 votes

# Answer
> How to write a variable value into a text file and modify it in the SD card?

This software design issue depends much on the chosen representation on file. In principle, there are two design dimensions. The first is textual or binary representation. The second is fixed or variable size records.

With textual representation (e.g. Serial.print) values are converted to text and stored on the file. The size of the record (e.g. line) depends on the number of characters needed for the value. New-line is often used as the record delimiter. To locate a specific record the file has to be scanned. There is no way to calculate the position of a record. When reading back the value the textual representation must be parsed and the internal representation in memory restored.

With binary representation (e.g. Serial.write) values are written directly from memory to the file. The size of the record is fixed as the size of a struct. Locating a specific record is easy; record index time record size. The SD library file.seek(position) is perfect to index the record. When reading the value back to memory there is no need for conversion as in textual representation.

It should be added that fixed size textual representation is also possible, e.g. make each line the same length by using a padding character (space, etc).

A text file with variable values is the more difficult as it is both textual representation and variable record. It is also the most inefficient as it requires compute power for the value representation conversions. The major advantage is that the text file can be generated with a ordinary text editor. No special tool or program is needed.

Binary file format with fixed records will require initialization.

Cheers!
> 1 votes

# Answer
It was super complicated for me at first but I understand it now. I'll upload just the DS3231 Code with the SD card functionality

```
#include <Wire.h>
#include <DS3231.h>
#include <SPI.h>
#include <SD.h>

DS3231 clock;
RTCDateTime dt;
File myFile;
String fileName = "000000.txt";

void setup()
{
  Serial.begin(9600);

  // Initialize DS3231
  Serial.println("Initialize DS3231");;
  clock.begin();

  // Set sketch compiling time
  clock.setDateTime(__DATE__, __TIME__);

  // Set from UNIX timestamp
  // clock.setDateTime(1397408400);

  // Manual (YYYY, MM, DD, HH, II, SS
  // clock.setDateTime(2016, 12, 9, 11, 46, 00);
}

void getName(){
  String date = clock.dateFormat("mdy", dt);
  fileName[0] = date[0];
  fileName[1] = date[1];
  fileName[2] = date[2];
  fileName[3] = date[3];
  fileName[4] = date[4];
  fileName[5] = date[5];
}

void sdCard() {
  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }

  Serial.println("initialization done.");

  getName();

  myFile = SD.open(fileName, FILE_WRITE);

  if (myFile) {
    Serial.print("Writing to file...");
    myFile.println("testing 1, 2, 3.");
    Serial.println("done.");
  }
  else {
    Serial.println("error opening file");
  }
}

void loop()
{
  dt = clock.getDateTime();

  Serial.print("Long number format:          ");
  Serial.println(clock.dateFormat("H:i:s", dt));

  sdCard();
  getName();

  myFile = SD.open(fileName, FILE_WRITE);
  myFile.println("Testing 1...2...3...")

}

```

So what I did here was initialize the variable for the text name with placeholders and I used the date in a 6 digit format. Both variables being a string, I can set the first position of the text name to be the first position of the date. So all values are replaced. Should be the same thing for an 8 digit text name, but after that there is a limit, not including the file extension.
> 0 votes

---
Tags: arduino-uno, sd-card, string
---


title: LCD Lifespans Constantly Running

text:
# Question
Title: LCD Lifespans Constantly Running
I am creating an arduino alarm clock/light sculpture, but I can't for the life of me find any information about the lifespans of LCDs that are running 24/7 for a very long time. If anyone has any information on them, please tell me. Specifically, I am using this one.

# Answer
The lifespan of the LCD and the electronics is just like any electronics part. When it is bad quality it will last a few years, when it is good quality it is more than 10 years.

A LCD watch from the 1970s might still work today. That is a few decades.

The backlight might get dim. That depends on the quality of the led and how bright it is set. The cheapest leds have only 50% brightness left after a few months. I suppose they didn't put the cheapest led in that display. I expect it to be okay for many years. Don't set it to the highest brightness. A resistor for the backlight of 220 Ω is common, you could start with 470 Ω and see if that is bright enough.

I see sometimes that the backlight display is directly connected to 5V, without resistor. If you have done that, then you have reduced its lifespan.

There are a few weak parts: The potentiometer for the contrast, the large capacitors on the Arduino board (if there are any), and the power supply.

If the display is more or less at the same room temperature, you could replace the potentiometer with a single resistor of 100Ω to 10kΩ from the LCD contrast pin to GND.
> 1 votes

---
Tags: lcd
---


title: Buttons, LOW vs no connection

text:
# Question
Title: Buttons, LOW vs no connection
I'm working with a very simple circuit to understand push buttons. The code in the tutorial uses the INPUT\_PULLUP pinmode. I understand the idea of the pinmode, but I have two questions:

There must be a difference between a LOW reading and no connection, correct? How does the arduino differentiate between the two?

I tried to experiment with this idea. So my thought was that you could create a circuit where the LED only stays lit when you hold the button down. In this setup, I used just normal INPUT for pinmode. So the logic was: if LOW then turn light on, else light off. The turnout was the light was almost always on and just really finicky when i moved the board. Why?

Thanks!

# Answer
> 6 votes
> There must be a difference between a LOW reading and no connection, correct?

No, the input circuitry measures a voltage. The exact details are in the datasheet, but how could it know there is nothing connected? There is not some sort of sensor that detects the insertion of a wire into the input. Therefore it is trying to read a voltage all the time.

With nothing connected then stray voltages from nearby circuitry will influence the reading.

---

> ... and just really finicky when i moved the board ...

Yep, you are influencing the voltage by capacitance from your hand.

You need to have a definite voltage for "no switch pressed" which can be a resistor to ground (eg. 10k) or a resistor to +5V.

I have a tutorial on this.

---

It sounds like you have wired your switch like this:

Because you don't have a definite voltage there, the input could "randomly" switch between LOW and HIGH.

---

You could add a pull-down resistor:

---

Or a pull-up resistor:

---

Or use the INPUT\_PULLUP mode to create a pull-up resistor in the processor hardware. (There is no INPUT\_PULLDOWN mode).

Then you will get consistent results.

---
Tags: button
---


# Question
Title: EDB char array problem. New input word overlaps the previous words saved
I have been searching everywhere now and nothing seems to work out for me. When I try to input a new word, it overlaps the previously entered words.
Here is my struct definition:

```
struct LogEvent{
  char fullname[30];
} logEvent;

```

Here is how I assign a value to fullname:

```
strcpy(logEvent.fullname, testName);

```

Here is how I print the output:

```
for(int i = 0; i <= db.count(); i++)
{
  EDB_Status result = db.readRec(i, EDB_REC logEvent);
  if(result == EDB_OK)
  {
     Serial.print(logEvent.fullname);
     Serial.print(" ");
  }
}

```

Here is the sample output:

```
Input 1 - Lebron James
Output 1- Lebron James

Input 2 - Kobe Bryant
Output 2 - Kobe Bryant Kobe Bryant  (The output should be - Lebron James Kobe Bryant)

Input 3 - LeGoat
Output 3 - LeGoat LeGoat LeGoat (The output should be - Lebron James Kobe Bryant LeGoat)

```

**How to fix this?**

EDIT. Here is my code:

```
#include "Arduino.h"
#include <EDB.h>

// Use the external SPI SD card as storage
#include <SPI.h>
#include <SD.h>

int recnumber = 1;
//Arbitrary definition
struct LogEvent {
    int id;
    int temperature;
    char fullname[30];
}
logEvent;

inline void writer (unsigned long address, const byte* data, unsigned int  recsize) {
    digitalWrite(13, HIGH);
    dbFile.seek(address);
    dbFile.write(data,recsize);
    dbFile.flush();
    digitalWrite(13, LOW);
}

inline void reader (unsigned long address, byte* data, unsigned int recsize) {
   digitalWrite(13, HIGH);
   dbFile.seek(address);
   dbFile.read(data,recsize);
   digitalWrite(13, LOW);
}
  EDB db(&writer, &reader);

// Run the demo
void setup()
{
    pinMode(13, OUTPUT);
    digitalWrite(13, LOW);

    Serial.begin(9600);
    Serial.println(" Extended Database Library + External SD CARD storage demo");
    Serial.println();

    randomSeed(analogRead(0));

    if (!SD.begin(SD_PIN)) {
        Serial.println("No SD-card.");
        return;
    }

    // Check dir for db files
    if (!SD.exists("/db")) {
        Serial.println("Dir for Db files does not exist, creating...");
        SD.mkdir("/db");
    }

    if (SD.exists(db_name)) {

        dbFile = SD.open(db_name, FILE_WRITE);

      // Sometimes it wont open at first attempt, espessialy after cold start
      // Let's try one more time
        if (!dbFile) {
            dbFile = SD.open(db_name, FILE_WRITE);
        }

        if (dbFile) {
            Serial.print("Openning current table... ");
            EDB_Status result = db.open(0);
            if (result == EDB_OK) {
                Serial.println("DONE");
            } else {
                Serial.println("ERROR");
                Serial.println("Did not find database in the file " + String(db_name));
                Serial.print("Creating new table... ");
                db.create(0, TABLE_SIZE, (unsigned int)sizeof(logEvent));
                Serial.println("DONE");
                return;
            }
        } else {
            Serial.println("Could not open file " + String(db_name));
            return;
        }
    } else {
        Serial.print("Creating table... ");
        // create table at with starting address 0
        dbFile = SD.open(db_name, FILE_WRITE);
        db.create(0, TABLE_SIZE, (unsigned int)sizeof(logEvent));
        Serial.println("DONE");
    }
    deleteAll();
    recordLimit();
    countRecords();
}
char testName[30];

void loop()
{
  if(Serial.available())
  {
    Serial.println("Waiting for name...");
    index = 0;
    for(int i = 0; i < sizeof(testName); ++i)
    {
      testName[i] = (char)0;
    }
    while(Serial.available())
    {
      char character = Serial.read();
      testName[index] = character;
      index++;
    }
    createRecords(testName);
    selectAll();
    delay(1000);
  }
  delay(1000);
 }

void createRecords(char *testName)
{
  Serial.print("Creating Record... ");
  logEvent.id = recnumber;
  logEvent.temperature = random(1, 125);
  strcpy(logEvent.fullname, testName);
  recnumber++;
  EDB_Status result = db.appendRec(EDB_REC logEvent);
}

void selectAll()
{
   for (int recno = 1; recno <= db.count(); recno++)
   {
      EDB_Status result = db.readRec(recno, EDB_REC logEvent);
      if (result == EDB_OK)
      {
        Serial.print("Recno: ");
        Serial.print(recno);
        Serial.print(" ID: ");
        Serial.print(logEvent.id);
        Serial.print(" Temp: ");
        Serial.print(logEvent.temperature);
        Serial.print(" Fullname: ");
        Serial.print(logEvent.fullname);
        Serial.print(" Length: ");
        Serial.println(strlen(logEvent.fullname));
      }
    }
 }

```

Here is the output:

```
Extended Database Library + External SD CARD storage demo

Openning current table... DONE
Truncating table... DONE
Record Limit: 2045
Record Count: 0
Record Count: 0
Waiting for name...
Name received: Kobe Bryant
LogEvent Fullname:
The sentence entered is 11 characters long
Creating Record... Done Creating Record...
Recno: 1 ID: 1 Temp: 64 Fullname: Kobe Bryant Length: 11
Waiting for name...
Name received: Lebron James
LogEvent Fullname: Kobe Bryant
The sentence entered is 12 characters long
Recno: 1 ID: 1 Temp: 64 Fullname: Kobe Bryant Length: 11
Creating Record... Done Creating Record...
Recno: 1 ID: 1 Temp: 64 Fullname: Lebron James Length: 12
Recno: 2 ID: 2 Temp: 78 Fullname: Lebron James Length: 12
Waiting for name...
Name received: Michael Jordan
LogEvent Fullname: Lebron James
The sentence entered is 14 characters long
Recno: 1 ID: 1 Temp: 64 Fullname: Lebron James Length: 12
Recno: 2 ID: 2 Temp: 78 Fullname: Lebron James Length: 12
Creating Record... Done Creating Record...
Recno: 1 ID: 1 Temp: 64 Fullname: Michael Jordan Length: 14
Recno: 2 ID: 2 Temp: 78 Fullname: Michael Jordan Length: 14
Recno: 3 ID: 3 Temp: 29 Fullname: Michael Jordan Length: 14

```

Update: I tried to use `memset` but the result is still the same as above.

# Answer
> 1 votes
I managed to solve the problem. The problem is with the SD card library of Arduino. I downloaded this library sdFat library, included it in the sketch `#include "SdFat.h"`, and defined `SdFat SD`. I also removed the `#include <SD.h>`.

# Answer
> 0 votes
I've just tried to extend one of the examples (with internal EEPROM), and it's working as expected:

```
/*
 EDB_Simple.pde
 Extended Database Library + Internal Arduino EEPROM Demo Sketch

 The Extended Database library project page is here:
 http://www.arduino.cc/playground/Code/ExtendedDatabaseLibrary

 */
#include "Arduino.h"
#include <EDB.h>

// Use the Internal Arduino EEPROM as storage
#include <EEPROM.h>

// Uncomment the line appropriate for your platform
#define TABLE_SIZE 512 // Arduino 168 or greater

// The number of demo records that should be created.  This should be less
// than (TABLE_SIZE - sizeof(EDB_Header)) / sizeof(LogEvent).  If it is higher,
// operations will return EDB_OUT_OF_RANGE for all records outside the usable range.
#define RECORDS_TO_CREATE 10

// Arbitrary record definition for this table.
// This should be modified to reflect your record needs.
struct LogEvent {
  int id;
  int temperature;
  char test[20] = {};
}
logEvent;

// The read and write handlers for using the EEPROM Library
void writer(unsigned long address, byte data)
{
  EEPROM.write(address, data);
}

byte reader(unsigned long address)
{
  return EEPROM.read(address);
}

// Create an EDB object with the appropriate write and read handlers
EDB db(&writer, &reader);

void setup()
{
  Serial.begin(115200);
  Serial.println("Extended Database Library + Arduino Internal EEPROM Demo");
  Serial.println();

  db.create(0, TABLE_SIZE, sizeof(logEvent));

  Serial.print("Record Count: "); Serial.println(db.count());

  Serial.println("Creating Records...");
  int recno;
  for (recno = 1; recno <= RECORDS_TO_CREATE; recno++)
  {
    logEvent.id = recno;
    logEvent.temperature = recno * 2;
    strcpy(logEvent.test, (String{recno*3} + " whatever " + recno).c_str());
    db.appendRec(EDB_REC logEvent);
  }

  Serial.print("Record Count: "); Serial.println(db.count());
  // Thanks to katts0...@gmail.com for the next line
  for (recno = 1; recno <= RECORDS_TO_CREATE; recno++)
  {
    db.readRec(recno, EDB_REC logEvent);
    Serial.print("ID: "); Serial.print(logEvent.id);
    Serial.print(" Temp: "); Serial.print(logEvent.temperature);
    Serial.print(" Data: "); Serial.println(logEvent.test);
  }
}

void loop()
{
}

```

The output:

```
Extended Database Library + Arduino Internal EEPROM Demo

Record Count: 0
Creating Records...
Record Count: 10
ID: 1 Temp: 2 Data: 3 whatever 1
ID: 2 Temp: 4 Data: 6 whatever 2
ID: 3 Temp: 6 Data: 9 whatever 3
ID: 4 Temp: 8 Data: 12 whatever 4
ID: 5 Temp: 10 Data: 15 whatever 5
ID: 6 Temp: 12 Data: 18 whatever 6
ID: 7 Temp: 14 Data: 21 whatever 7
ID: 8 Temp: 16 Data: 24 whatever 8
ID: 9 Temp: 18 Data: 27 whatever 9
ID: 10 Temp: 20 Data: 30 whatever 10

```

---
Tags: arduino-uno, datalogging
---


# Question
Title: How to send HTTP requests to specific port using Ciao?
I currently have a working REST client on my Arduino, but the requests always go to port 80. How do I make it send the request to a specific port?

This is my current code:

```
/*
File: RestClient.ino
This example makes an HTTP request after 10 seconds and shows the result both in
serial monitor and in the wifi console of the Arduino Uno WiFi.

Note: works only with Arduino Uno WiFi Developer Edition.

http://www.arduino.org/learning/tutorials/boards-tutorials/restserver-and-restclient
*/

#include <Wire.h>
#include <UnoWiFiDevEd.h>

void setup() {
  const char* connector = "rest";
  const char* server = "download.arduino.org";
  const char* method = "GET";
  const char* resource = "/latest.txt";

  Serial.begin(9600);
  Ciao.begin();
  pinMode(2, INPUT);
  delay(10000);
  doRequest(connector, server, resource, method);
}

void loop() {
}

void doRequest(const char* conn, const char* server, const char* command, const char* method) {
  CiaoData data = Ciao.write(conn, server, command, method);
  if (!data.isEmpty()) {
    Ciao.println( "State: " + String (data.get(1)) );
    Ciao.println( "Response: " + String (data.get(2)) );
    Serial.println( "State: " + String (data.get(1)) );
    Serial.println( "Response: " + String (data.get(2)) );
  } else {
    Ciao.println ("Write Error");
    Serial.println ("Write Error");
  }
}

```

If I add for example `:8080` to the end of the `server` variable, it does not work.

How do I make that request go to a specific port?

# Answer
You can find a port definition for your Arduino in this path:

/usr/lib/python2.7/ciao/connectors/restserver/restserver.json.conf

```
{
 "name" : "restserver",
 "description" : "REST server connector for the Ciao Core",
 "authors": ["Arduino Team <swdev@arduino.org>;"],
 "repository" : "https://github.com/arduino-org/Ciao",
 "version" : "0.0.2",
 "params" : {
            "port" : 80
             },
 "log" : {
         "level" : "info"
         }
}

```

The confusing part is that your Arduino has a server-client connection to itself from the CPU/Linino server to the MCU/Arduino client.

https://www.arduino.cc/en/Reference/CiaoRestServer
> 0 votes

---
Tags: http, arduino-uno-wifi-dev-ed
---


# Question
Title: How to replace the delay() function in my code?
I'm new to Arduino and I currently have a project that involves the control of an LED via ultrasonic sensor. Basically, if an object passes through the ultrasonic sensor, the LED will be ON for 5 seconds but adding another set of LED and ultrasonic sensor with the same function gives a problem because the other LED won't light up if the other one is ON and vice versa because of the delay whereas what I want is to be able to make them both light up and stay lit for 5 seconds after their respective ultrasonic sensors detect an object. I've tried using the "Blink without delay" example but I can't understand it nor make it work. Please help me guys and thanks for reading. Here is my current code:

```
int trigPin1=2;
int echoPin1=3;

int trigPin2=4;
int echoPin2=5;

int led1=10;
int led2=11;

void setup() {
  Serial.begin(9600);
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
  pinMode(trigPin2, OUTPUT);
  pinMode(echoPin2, INPUT);

  pinMode(led1,OUTPUT);
  pinMode(led2,OUTPUT);
}

void loop() {
  long duration1, distance1;
  digitalWrite(trigPin1, LOW);  // Added this line
  delayMicroseconds(2); // Added this line
  digitalWrite(trigPin1, HIGH);
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin1, LOW);
  duration1 = pulseIn(echoPin1, HIGH);
  distance1 = (duration1/2) / 29.1;

   if (distance1 >= 500 || distance1 <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print ( "Sensor1  ");
    Serial.print ( distance1);
    Serial.println("cm");
       }

  long duration2, distance2;
  digitalWrite(trigPin2, LOW);  // Added this line
  delayMicroseconds(2); // Added this line
  digitalWrite(trigPin2, HIGH);
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin2, LOW);
  duration2 = pulseIn(echoPin2, HIGH);
  distance2= (duration2/2) / 29.1;

  if (distance2 >= 500 || distance2 <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print("Sensor2  ");
    Serial.print(distance2);
    Serial.println("cm");
       }

  if(distance1>20 || distance2>20){
    digitalWrite(led1,LOW);
    digitalWrite(led2,LOW);
  }
  else if(distance1<20){
    digitalWrite(led1,HIGH);
    delay(5000);
  }

  else if(distance2<20){
    digitalWrite(led2,HIGH);
    delay(5000);
  }
}

```

# Answer
> 2 votes
The first set of delaymicroseconds for measuring is fine.

you'll want to replace the `delay(5000)` when switching the leds.

```
  if(distance1>20 || distance2>20){
    digitalWrite(led1,LOW);
    digitalWrite(led2,LOW);
  }
  else if(distance1<20){
    digitalWrite(led1,HIGH);
    delay(5000);
  }

  else if(distance2<20){
    digitalWrite(led2,HIGH);
    delay(5000);
  }

```

you can do that by using a timestamp of when the distance was last high:

```
  if(distance1<20){
    digitalWrite(led1,HIGH);
    timestamp1 = millis();
  }

  if(distance2<20){
    digitalWrite(led2,HIGH);
    timestamp2 = millis();
  }

if(millis() - timestamp1 > 5000){
  digitalWrite(led1,LOW);
}

if(millis() - timestamp2 > 5000){
  digitalWrite(led2,LOW);
}

```

`timestamp1` and `timestamp2` should be globals (or static locals). This code will delay turning off the led to 5 seconds after the sensor last detected something close.

---
Tags: sensors, led, millis
---


# Question
Title: yellow LED not turning off in traffic light simulation
I wanted to make a simulation of a traffic light, and since I don't have any sensors I used a button to change between the different states (red/stop and green/drive). When the states are changing I wanted to have a short yellow blink- just like normal traffic lights work. But in the first state(green), yellow doesn't turn off. In the second the same problem occurs, but if I press the button, that I connected to GPIO pin 2, the LED turns off. It makes no sense to me, as the switch sentence turn off the yellow LED before powering the others (in both cases). In addition, I can't wrap my head around the fact that the yellow LED turns off after I press the button once more, as I only have two cases in the switch sentence, but it now seems like there is three.

```
void loop() {
// Turn the green led on (GPIO PIN 11) if button pressed once. If button is pressed again switch to yellow then to red.

if(switchLedBtn.pressed()) {
colour = colour + 1;
if(colour > 3) {
  colour = 1;
 }
}

switch(colour) {

// Turn off red, turn on yellow in half a second, then power green (green(0), yellow(1) and red(2))
case 1: digitalWrite(ledPins[2], LOW); digitalWrite(ledPins[1], HIGH); delay(500); digitalWrite(ledPins[1], LOW); digitalWrite(ledPins[0], HIGH);
        break;

// Turn green off, turn yellow on for a second, then power red
case 2: digitalWrite(ledPins[0], LOW); digitalWrite(ledPins[1], HIGH); delay(1000); digitalWrite(ledPins[1], LOW); digitalWrite(ledPins[2], HIGH);
        break;

```

# Answer
Your program runs in a tight loop - an *extremely* tight one which does all but nothing in any state but 1 or 2. However what happens in these states is interesting.

Essentially what you have is

1. Quickly check for input - which won't be detected unless the bottom is being held down at this precise narrow slice of time between long delays
2. Turn on an LED, apparently from your comment the yellow one
3. Change the LEDs but recycle so quickly that this fact is generally invisible.

The result of this is that instead of a brief pulse of yellow, you will be seeing near constant yellow, because that is the only part of your loop which takes any time.

Probably what you want to do is to advance the state when you are done with your brief yellow flash. But it's not possible to say what you should advance the state to, since it's unclear how you want this light to work. If it is purely timer-based, then you don't need any input at all; while if the button is supposed to do something but a timer should also be used, then you have a more complicated problem.

Essentially, before you can write any code **you must write in words or diagrams a comprehensive set of "rules" for what the system is supposed to do**.
> 0 votes

---
Tags: led, switch
---


# Question
Title: How to connect 70 analog sensor to a single Arduino (Mega or Uno) device?
I was working on a project in which I need to collect soil moisture data for a farm. For this, I need to collect soil moisture value from 70 sections of the farm on a single Arduino. But, this is not possible as there are just 6 analog pins on Arduino Uno and 16 analog pins on Arduino Mega. I have restrictions on the number Arduino that I can use that is just one due to monetary constrains. The data would be collected at a delay of 5 seconds. The data gathered would be stored on SD card module which would be analyzed later. Any suggestion on how I can collect data from 70 analog sensors on a single Arduino would be highly appreciated. Are there any alternatives that I can use in place of Arduino? I heard that we could do something with AVR atmega Microcontroller, am I correct? I don't know how to use Microcontroller; any useful resources will be highly appreciated. Thank You.

# Answer
There are fairly inexpensive chips called "analog multiplexers" which let you choose one input out of a range (8 or 16 is typical). You could take the reading, then switch to a different input, and take another reading.

I have a page about analog multiplexers.

Example of it in operation:

In this example you have 8 inputs, and by setting the A/B/C pins appropriately, one of the 8 is selected and appears at the O/I pin (output/input).

There is a 16-channel model as well. I see the 16-pin chip (74HC4067) available on eBay for $US 1.26 right now. You can get four of them (which would give you 80 inputs) for $4.88.

Also see the Wikipedia article on multiplexers.

---

> For this, I need to collect soil moisture value from 70 sections of the farm on a single Arduino.

Yes, well how will these sections get their data into one place? That is probably the bigger problem.

You may need to use a lengthy cable using RS485 (balanced signals) or maybe cheap radio transceivers.

Trying to use a "single Arduino" on what might be quite a large farm is the issue. It's not the Arduino's fault. You have to have some way of sending the data from the further points to where it is to be collected.
> 4 votes

# Answer
You should use some cheap chips to collect the data and use only one with big capacity to finally combine and process the data further.

> Consider using a cheap small Arduino to build a "base module" that can do some of the tasks needed, build a bunch of them and hook them up to a R485 bus, and have one master Arduino control them all. That would be a much more flexible and expandable system. The cheapes Arduinos cost around 10$. If you build your own you could probably do it even cheaper.

**Source**:

\[1\] http://forum.arduino.cc/index.php?topic=73861.0 (quote)

\[2\] https://arduino-info.wikispaces.com/RS485-Modules (bus)
> 1 votes

# Answer
Given that good moisture sensors are going to be an order of magnitude more expensive than the logger, I'd suggest that you are giving yourself more problems than it's worth to try to connect that many sensors to the same unit. A Pro-mini based logger rarely comes in \>$25. Even though we can connect that many one-wire sensors to a single logger ( https://thecavepearlproject.org/2015/03/01/using-ds18b20-sensors-to-make-a-diy-thermistor-string-pt-1-the-build/ ) it's not a good idea from the perspective of the amount of data that is lost if you have a single point failure. Generally we only put 10-15 sensors on any one unit, and we try to deploy them in "parallel" sets so that if one multi-sensor unit does fail, we loose spatial resolution, but still have enough information to work with.
> 0 votes

---
Tags: datalogging
---


title: LCD not displaying text

text:
# Question
Title: LCD not displaying text
I am working with an Arduino due and currently using the Arduino liquid crystal library to display data on an LCD screen (mc42004A6wk-bnmlw) which uses the Hitachi HD44780 controller. The LCD has been update to v2 and is now using the Sitronix ST7066U controller.

From what I have read the two controllers are compatible and the liquid crystal library should work for both. I am using the same software and hardware setup as before but the screen will not display anything.

The software I use is quite complex so I moved to a simple hello world program (below) to test and I still have the same issues. Any advice would be greatly appreciated.

```
#include <LiquidCrystal.h>
#include <Arduino.h>

LiquidCrystal lcd(30, 31, 32, 33, 46, 47);

void setup()
{

  pinMode(36,OUTPUT);

  digitalWrite(36, LOW);

  delay(5000);

  // set up the LCD's number of columns and rows:
  lcd.begin(20, 4);

  lcd.clear();

  // Print a message to the LCD.
  lcd.print("hello, world!");
}

void loop()
{

  delay(5000);
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(millis() / 1000);
}

```

# Answer
So after further investigation into the IDE, Libraries, board manager, hardware etc I discovered what was causing the issue.

On the initial hardware design the hardware engineer placed a capacitor on the enable leg between the LCD screen and the microcontroller. I have no idea why as I have not seen this done in any wiring diagrams but removing it has done the trick. The V2 board now works with all the original code and libraries.
> 0 votes

# Answer
Try using this code, I have edited some parts of your code so this should work.

```
#include <LiquidCrystal.h>

const int rs = 30, en = 31, d4 = 32, d5 = 33, d6 = 46, d7 = 47;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup()
{

  pinMode(36, OUTPUT);
  digitalWrite(36, LOW);
  delay(5000);    //Its okay to use delay here since its in the setup() function and will run only once

  // set up the LCD's number of columns and rows:
  lcd.begin(20, 4);

  // Print a message to the LCD.
  lcd.print("hello, world!");
}

void loop()
{
  // set the cursor to column 0, line 1
  // (note: line 1 is the second row, since counting begins with 0):
  lcd.setCursor(0, 1);
  // print the number of seconds since reset:
  lcd.print(millis() / 1000);
}

```

For this Hello World sketch, avoid using `delay();` statement in the `void loop()` as it is not good to use when you have the `millis();` used.

If the above wont work, **check your LCD Wiring**, many problems usually arouse from wrong wirings. Also I may suggest you to use some cheap LCD I2C Backpacks as this will ease the coding and will use less wire and pins on your Arduino. Here is a example

If your'e going to use a I2C LCD Backpack, here is a working sample code.

```
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

#define BACKLIGHT_PIN     13

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C address

// Creat a set of new characters
const uint8_t charBitmap[][8] = {
   { 0xc, 0x12, 0x12, 0xc, 0, 0, 0, 0 },
   { 0x6, 0x9, 0x9, 0x6, 0, 0, 0, 0 },
   { 0x0, 0x6, 0x9, 0x9, 0x6, 0, 0, 0x0 },
   { 0x0, 0xc, 0x12, 0x12, 0xc, 0, 0, 0x0 },
   { 0x0, 0x0, 0xc, 0x12, 0x12, 0xc, 0, 0x0 },
   { 0x0, 0x0, 0x6, 0x9, 0x9, 0x6, 0, 0x0 },
   { 0x0, 0x0, 0x0, 0x6, 0x9, 0x9, 0x6, 0x0 },
   { 0x0, 0x0, 0x0, 0xc, 0x12, 0x12, 0xc, 0x0 }

};

void setup()
{
   int charBitmapSize = (sizeof(charBitmap ) / sizeof (charBitmap[0]));

  // Switch on the backlight
  pinMode ( BACKLIGHT_PIN, OUTPUT );
  digitalWrite ( BACKLIGHT_PIN, HIGH );

  //lcd.begin(16,2);
  lcd.begin(20,4); // initialize the lcd

   for ( int i = 0; i < charBitmapSize; i++ )
   {
      lcd.createChar ( i, (uint8_t *)charBitmap[i] );
   }

  lcd.home ();                   // go home
  lcd.print("LCD TESTER - BY:");
  lcd.setCursor ( 0, 1 );        // go to the next line
  lcd.print ("ABBAS (PRJCT.ME)");
  delay ( 3000 );
}

void loop()
{
   lcd.home ();
   // Do a little animation by writing to the same location
   //for ( int i = 0; i < 2; i++ )
    for ( int i = 0; i < 4; i++ )
   {
      //for ( int j = 0; j < 16; j++ )
      for ( int j = 0; j < 20; j++ )
      {
         lcd.print (char(random(7)));
      }
      lcd.setCursor ( 0, 1 );
       for ( int j = 0; j < 20; j++ )
      {
         lcd.print (char(random(7)));
      }
      lcd.setCursor ( 0, 2 );
       for ( int j = 0; j < 20; j++ )
      {
         lcd.print (char(random(7)));
      }
      lcd.setCursor ( 0, 3 );

   }
   delay (200);
}

```
> 0 votes

---
Tags: lcd, arduino-due
---


# Question
Title: Problem with LED (Builtin) connected to pin 13
This is Aakash. Student of Electrical Engineering in a University. I want to ask some information. Today I Purchased Arduino UNO R3 board. and facing some problem which are :

```
          "**Builtin LED at pin#13 is always ON on my board**".

```

Is there any problem with the board ?

I tried to upload these sketches and got these results:: 1)...with empty setup(){} and empty loop(){}, Still LED is ON. 2)...When I uploaded these command "pinMode(LED\_BUILTIN,OUTPUT);" in setup() and "digitalWrite(LED\_BUILTIN,LOW);" in loop(), LED turned OFF 3)...If i touch pin13 and Ground both by a wet finger at back of board, LED turns OFF. 4)...but on uploading empty or any other code, BUILTIN\_LED turns ON again and do not turns OFF.

Kindly reply me ASAP! So that if i have got faulty Board then i might go for claim.

# Answer
This is a normal thing. All my arduino boards do the same. The reason for this is that the micro controller don't care about the pins that aren't defined in the code. When they aren't defined they all have a HIGH on them. Here is my board with this code:

```
void setup() {
}
void loop() {
}

```
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: can I design a User Interface to run on the arduino and display it with VGA?
I know you can design a user-interface in any language you choose and Link it with a Arduino via serial Port, but I am asking if I can design user-interface to run on the Arduino WITHOUT the need for an external laptop/desktop and display the user interface on a screen (like via VGA) ? and HOW ?

# Answer
> 2 votes
Forget VGA. Arduino is not capable of that.

For display you can use a 16x2 LCD (only chars, not graphics) or an OLED display, which have graphic capabilities. There are in size from 0.96". There BW, but alse color models and touch sensitive ones. For input you use push buttons, or keypad.

Today best option for display is some model with I2C or SPI interfaces (to minimize wiring).

There thousand of projects in Internet. Search "Arduino OLED keypad" and you will find projects like http://www.instructables.com/id/Arduino-OLED-Calculator/:

This hardware impose some limits in the UI (thank god). What you have is a tradicional menu system: you present a menu, user choose an option, Arduino execute it. No help, no dropbox, no autocompletion, nothing, only the most basic "Press 1 for ..."

EDIT:

As Nick Gammon stated, it's possible to drive a VGA display from an Arduino, like this post and this other shows. The resolution are 20 characters wide by 30 characters deep (160 x 480 pixels) for the monochrome version and 120 x 60 pixels for the four colors version.

However, that capabilities doesn't match any of the standard VGA capabilities:

> The VGA supports both All Points Addressable graphics modes, and alphanumeric text modes. Standard graphics modes are:
>
> ```
> 640×480 in 16 colors or monochrome[2] (the latter matching IBM's lesser Multi-Color Graphics Array standard)
> 640×350 or 640×200 in 16 colors or monochrome (EGA compatibility mode)
> 320×200 in 4 or 16 colors
> 320×200 in 256 colors (Mode 13h)
>
> ```

The proposed alternatives achieves less resolution than a 1981 Sinclair ZX-81 (24 lines of 32 chars), takes two timers and half of Arduino RAM minimum (the color example left you with 200 bytes RAM and takes a third timer with it).

So, in practical terms, VGA is not an option.

---
Tags: serial
---


# Question
Title: Passing the result of the variable to another variable
Hello everyone i'm figuring if this variable can be passed to another variable. I'm using RFID RC522 Here is the code:

```
 #include <SPI.h>
    #include <MFRC522.h>
    #define RST_PIN         5           // Configurable, see typical pin layout
    above
    #define SS_PIN          53          // Configurable, see typical pin layout
    above
    MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
    int result = 0;
    // Number of known default keys (hard-coded)
    // NOTE: Synchronize the NR_KNOWN_KEYS define with the defaultKeys[] array
    #define NR_KNOWN_KEYS   8
    // Known keys, see:
    https://code.google.com/p/mfcuk/wiki/MifareClassicDefaultKeys
    byte knownKeys[NR_KNOWN_KEYS][MFRC522::MF_KEY_SIZE] =  {
    {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, // FF FF FF FF FF FF = factory default
    {0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5}, // A0 A1 A2 A3 A4 A5
    {0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5}, // B0 B1 B2 B3 B4 B5
    {0x4d, 0x3a, 0x99, 0xc3, 0x51, 0xdd}, // 4D 3A 99 C3 51 DD
    {0x1a, 0x98, 0x2c, 0x7e, 0x45, 0x9a}, // 1A 98 2C 7E 45 9A
    {0xd3, 0xf7, 0xd3, 0xf7, 0xd3, 0xf7}, // D3 F7 D3 F7 D3 F7
    {0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}, // AA BB CC DD EE FF
    {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}  // 00 00 00 00 00 00
    };
    /*
    * Initialize.
    */
    void setup() {
    Serial.begin(9600);         // Initialize serial communications with the PC
    while (!Serial);            // Do nothing if no serial port is opened (added
    for Arduinos based on ATMEGA32U4)
    SPI.begin();                // Init SPI bus
    mfrc522.PCD_Init();         // Init MFRC522 card
    // Serial.println(F("Try the most used default keys to print block 0 of a
    MIFARE PICC."));
    }
    /*
    * Helper routine to dump a byte array as hex values to Serial.
    */
    void dump_byte_array(byte *buffer, byte bufferSize) {
    for (byte i = 0; i < bufferSize; i++) {
    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
        Serial.print(buffer[i], HEX);
    }
}

/*
 * Try using the PICC (the tag/card) with the given key to access block 0.
 * On success, it will show the key details, and dump the block data on Serial.
 *
 * @return true when the given key worked, false otherwise.
 */
boolean try_key(MFRC522::MIFARE_Key *key)
{
    boolean result = false;
    byte buffer[18];
    byte block = 0;
    byte status;

    // Serial.println(F("Authenticating using key A..."));
    status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, key, &(mfrc522.uid));
    if (status != MFRC522::STATUS_OK) {
        // Serial.print(F("PCD_Authenticate() failed: "));
        // Serial.println(mfrc522.GetStatusCodeName(status));
        return false;
    }

    // Read block
    byte byteCount = sizeof(buffer);
    status = mfrc522.MIFARE_Read(block, buffer, &byteCount);
    if (status != MFRC522::STATUS_OK) {
        // Serial.print(F("MIFARE_Read() failed: "));
        // Serial.println(mfrc522.GetStatusCodeName(status));
    }
    else {
        // Successful read
        result = true;
        //Serial.print(F("Success with key:"));
        dump_byte_array((*key).keyByte, MFRC522::MF_KEY_SIZE);
        //Serial.println();
        // Dump block data
       // Serial.print(F("Block ")); Serial.print(block); Serial.print(F(":"));
        dump_byte_array(buffer, 16);
        //Serial.println();
    }
  //  Serial.println();

    mfrc522.PICC_HaltA();       // Halt PICC
    mfrc522.PCD_StopCrypto1();  // Stop encryption on PCD
    return result;
}

/*
 * Main loop.
 */
void loop() {
  // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent())
        return;
// Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial())
    return;
    // Show some details of the PICC (that is: the tag/card)
   // Serial.print(F("Card UID:"));
    dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
delay(3000);
// Serial.print(F("PICC type: "));
  //  byte piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
    //Serial.println(mfrc522.PICC_GetTypeName(piccType));

    // Try the known default keys

      }

```

I list all of my card's value and i want to create a conditional statement if the result of dump\_byte\_array is the same with my card's value i list. Sample:

```
if ( dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size) && "D4 39 F8 BE" ==
  true ){
        Serial.print("Card 1 Detected");

```

That's what i want to happen but i know that is wrong. Please help me with this. Thank you in advance.

# Answer
Well, `dump_byte_array` is a void function, so you can't compare it to anything.

And this line

```
if (dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size) && "D4 39 F8 BE" == true)

```

is both ilegal and illogical. Ilegal, because you are comparing a pointer (" ("D4 39 F8 BE") against an integer (the *true* value is a int in disguise).

It's illogical, because you are "&&" is the **logical and** operator, not the bitwise *and*.

What you need is a string comparison:

```
if (strncmp(mfrc522.uid.uidByte, "D4 39 F8 BE", mfrc522.uid.size) == 0) {
   Serial.println("Card found");
}

```

That's assuming that uidByte contains the ID.

**The strncmp function**

```
int strncmp ( const char * str1, const char * str2, size_t num );

```

*Compare characters of two strings*

Compares up to num characters of the C string str1 to those of the C string str2.

This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ, until a terminating null-character is reached, or until num characters match in both strings, whichever happens first.

*Parameters*

str1 C string to be compared.

str2 C string to be compared.

num Maximum number of characters to compare. size\_t is an unsigned integral type.

*Return Value*

Returns an integral value indicating the relationship between the strings:

* \<0 the first character that does not match has a lower value in str1 than in str2
* 0 the contents of both strings are equal
* \>0 the first character that does not match has a greater value in str1 than in str2

But you really need to learn C.
> 1 votes

# Answer
Simply rewrite your dump\_byte\_array function as follows

```
bool matchID(byte *buffer, byte bufferSize, byte * match, byte matchSize) {
    if (bufferSize != matchSize) return false;
    for (byte i = 0; i < bufferSize; i++)
        if (buffer[i] != match[i])
            return false;
    return true;
}

```

and call this new function like

```
if ( matchID(mfrc522.uid.uidByte, mfrc522.uid.size, [0xD4, 0x39, 0xF8, 0xBE], 4)) {
    Serial.print("Card 1 Detected");
}

```

As suggested in the comments, what's wrong with memcmp ...

```
bool matchID(byte *buffer, byte bufferSize, byte * match, byte matchSize) {
    if (bufferSize != matchSize) return false;
    return memcmp(buffer, match, bufferSize) == 0;
}

```
> 1 votes

---
Tags: arduino-mega, rfid
---