text:
Code for determining beats per min when timing a wooden clock
I'm new to Arduino and coding but I build wooden clocks.  The biggest problem is timing the clock to the correct beats per min when adjusting pendulum length.  I'm thinking Arduino and an IR sensor?? to detect when the pendulum breaks the beam, then displaying the beats per min real time would be possible.  If not real time then just beats in a variable time period, ie 1 min or 2 or 5 or 10 min.  I've looked for this type of code and circuit but haven't been able to find one.  Any help would sincerely be appreciated.

What kind of accuracy level do you require? Like a few ppm?

No, needs to be down to tenth or hundreth of a min.  What I currently do is use a stopwatch to measure 60 beats (for example) and see what time period that is.  Obviously 60 beats in 1 min would be accurate (however some clocks have 90 beats per min)  If that isn't possible then counting the beats in a 2 or 5 min or 10 min cycle would start narrowing things down.

Better yet: made the Arduino control a weight in the pendulum to adjust (higher/lower) his center of mass and automatically keep it to 60 bps. Arduino, battery and motor can be hidden inside the pendulum bob. That's will be cool: the most precise and stable pendulum wooden clock of the world.

If the accuracy you require is about 1%, that should be doable with any
Arduino. Much higher accuracies would be hard to achieve because most
Arduinos are clocked off a ceramic resonator, and these have a frequency
tolerance of about 0.5%.
Given that your signal is very slow, the simplest approach may be to
poll the pin connected to the sensor and record the time (using
micros()) of the low → high transition. Then you can compute the
beat frequency as the inverse of the time between consecutive
transitions.
There is, however, the possibility that the sensor is not exactly in
the middle of the swing. Then, for better accuracy, I would measure the
time taken by two beats, i.e. a full swing. This way the pssible
asymmetry will not affect the accuracy.

I'd suggest to have the Arduino send a message to the PC when a 'tick' occurs. Then have the PC do the calculations over a larger number of ticks. You can even have the PC measure it's drift using NTP (PC clocks also aren't extremely accurate, but better that the crystal on the Arduino).
The procedure that I used, I found at https://www.logre.eu/wiki/Horloge_analogique_24h/en#Quartz_calibration I ran it for a few hours. Which might also be useful in your case to see if the swing is consistent.
I used this to calibrate my Arduino clock to within a few seconds per year,

Thanks so much for the info and direction to head.  Now I'll figure out if I understood all this wisdom, like I said, new to coding.  Appreciate the quick response.

At that point you might as well just use the PC to record the ticking sound and process it in software.  Or if you can't work in a quiet environment, couple the sensor the PC audio input with a capacitor.


text:
How do I create a constant loop with an event that only occurs once?
I am currently working in void loop() and have setup a distance meter that constantly checks the distance.
Once the distance threshold is met, a function is called. Now I only need this function to be called ONCE. But because the distance meter is constantly scanning (which I need), the function is also being repeatedly called. I tried making some sort of timer but I can't figure it out. Can someone please have a look at this?
if (distance <= 150){
    personPresent();
    }

  if(distance > 150){
    personAbsent();
      }

I need certain events within the if statement to occur only once. E.g., I want to register when there is a personPresent and have that event not fire repeatedly.
In this case, personPresent() is attached to a GPIO pin which triggers a buzzer sound. As it is now, the buzzer keeps on ringing as long as distance is less then 150. I need the buzzer to make a sound only ONCE and then not buzz for at least 5 minutes.

use a "flag" variable to remember that the function has been called

What you want is not to check the distance but to check that the distance condition changed.
static boolean present = false;

Inside loop:
if (present == false && distance <= 150){
    personPresent();
    present = true;
} else if(present == true && distance > 150) {
    personAbsent();
    present = false;
}

static boolean didItAlready = false;

if(distance > 50 && !didItAlready){
     doIt();
     didItAlready = true;
}

You simply need a variable to keep track of whether or not it has been done.  If and when you want to do the action again then set your variable back to false.

You just need a global variable to track whether it is done or not like this...
//  other Codes

bool State=0;

void setup(){

// other Codes...

}

void loop(){

if(distance <= 150 && State==0){

personPresent(); // This function should get executed only once
State=1;

}else if(distance>150 && State==1){

personAbsent(); // This sould also get executed once
State=0;

}

}

The global boolean variable ''' State ''' will keep track of how and when the functions need to be executed once, whenever conditions are met. And the boolean variable changes everytime (distance AND Sate) the conditions are met triggering those functions once per bool update.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
VisualMicro Can't compile in debug ('Serial' was not declared in this scope) for attiny84a
I was working on a project build initialy from the Arduino IDE to program an attiny84a (without a bootloader) using the board from https://github.com/damellis/attiny
I got an atmel-ice recently and I was trying to debug the arduino sketch using it.
I installed AtmelStudio (because I know it has an GUI debugger) and found VisualMicro that should help me to compile arduino sketch.
Unfortunatly as soon as a set the project to debug I got a compilation error :
'Serial' was not declared in this scope

(I don't have this error in Release mode).
My code doesn't use any serial (because I don't have any pin left), so this was wierd. I still tried to add the SoftwareSerial.h include (just in case) without success.
So I created an empty (I mean with only an empty setup() and loop() methods) and it throw the same error.
I tried to setup different versions of arduino IDE into VisualMicro (1.6.13, 1.8.1, 1.8.5 and 1.9 build 34) without success.
Then after a couple of hours I found the .cpp source generated by VisualMicro and it try to use the member "Serial" for some debugging reason.
I would like an easy way to integrate with arduino (all those library and easy to install library) and to be able to debug as well, what can I look for or do?
Thank

I found how to disable the vMicro debugging, in AtmelStudio open the "vMicro" menu then click the "Debugger" item and make sure the option "Atmel Studio Debugger" is checked.
1) Change the optimization flag to a usefull state (-Og or -O0) in order to NOT have "Unknown identifier" or "Optimized away" when looking at variable.
I tried:

Put -Og in the project property "Extra flags" (vMicro)
Before my code I added
#pragma GCC push_options
#pragma GCC optimize ("Og")

then at the end of my code
#pragma GCC pop_option

ANSWER: I probably fuckup in the rebuild because only the line below is enough (in the .cpp file):
    #pragma GCC optimize ("Og")

Replaced -Os in playform.txt (in this case it didn't work at all)

I saw a size changes in my binary (except for the last point), but when running the simulator I still couldn't see any value.
2) Couldn't start a debugging session
(When I try to change the debugging device it always crash AtmelStudio, I think it is because the target IC is force to ATSAM3X8E by the vMicro plugin which isn't supported on my computer, and because it isn't supported I can't change the target IC to attiny84a...)
ANSWER: When creating the project vMicro read the current board selected (yes before you even can select it) to detect if it has to create a 32 bits or 8 bits project
Also you MUST create a project with an .ino (even if it is empty) as the same name as the project in order to be able to compile.

'Serial' was not declared in this scope

This error is not surprising when compiling for ATtiny84 because in Arduino Serial refers to the hardware serial port and ATtiny84 doesn't have one.
But you didn't use Serial in your sketch so why should you get this error? The answer is this magical debug feature of Visual Micro that you desire. It turns out that on AVR microcontrollers such as your ATtiny84 all this actually consists of is Visual Micro automatically inserting various Serial.print() statements into your code, just as we always do manually to debug our code in the good old Arduino IDE:
http://www.visualmicro.com/page/User-Guide.aspx?doc=Debugging-Explained.html
So in fact your sketch is attempting to use Serial without your knowledge or being able to see it! If you turn off debugging you should no longer get that error.
Visual Micro does allow you to change the debugging output to software serial:
http://www.visualmicro.com/page/User-Guide.aspx?doc=Debugging-With-Different-Ports.html
but since you say you have no pins available that may not be any help.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Input 4-digit number using 4*4 keypad and show in serial monitor
#include <Keypad.h>

int myNum[4];

const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad 8,7,6,5
byte colPins[COLS] = {9, 8, 7, 6}; //connect to the column pinouts of the keypad 4,3,2,1
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );

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

void loop() {
  Serial.println("Enter four-digit num -");  // request for input
  for (int i = 0; i < 4;){
    if(keypad.getKey()!= NO_KEY) {
      myNum[i] = keypad.getKey();
      i = i+1;
    }
  }
  Serial.print("Entered number is = ");
  Serial.print(myNum[0]);
  Serial.print(myNum[1]);
  Serial.print(myNum[2]);
  Serial.println(myNum[3]);
  delay(500);
}

I want that when I press a 4-digit number on the keypad it should be shown in the serial monitor. This code gives 0000 when I press any key on keypad.

keypad.getKey() is non-blocking as you can read here: it will return a value immediately, even if no key is pressed.  You have a for loop which will increment i each time, and you also increment it yourself. So what's happening is that your code is immediately making four readings, all of which are no-key-pressed so it doesn't store them, and then printing whatever happens to be in the myNum buffer.
Instead, you need to wait each time until a key is pressed, and only then move to the next digit. There are of course many ways you could do this.  I hope this is clear:
#include <Keypad.h>

int myNum[4];

const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad 8,7,6,5
byte colPins[COLS] = {9, 8, 7, 6}; //connect to the column pinouts of the keypad 4,3,2,1
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );

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

void loop() {
  Serial.println("Enter four-digit num -");  // request for input

  for (int i = 0; i < 4; ++i){
    while((myNum[i] = keypad.getKey())==NO_KEY) {
      delay(1); // Just wait for a key
    }
    // Wait for the key to be released
    while(keypad.getKey() != NO_KEY) {
      delay(1);
    }

  }

  Serial.print("Entered number is = ");
  Serial.print(myNum[0]);
  Serial.print(myNum[1]);
  Serial.print(myNum[2]);
  Serial.println(myNum[3]);
  delay(500);
}

You are welcome. If the answer helps you, please consider accepting it.

when i compile it there is a error code "Serial does not name a type" .

I assumed you had tested your original code, since you described how it didn't work. No?

@kasun That kind of error usually occurs when you try to execute a statement outside of any function. Did you omit a curly brace around setup() or loop()? Show the exact code that gives you the error!

thnks friend . thats { is bother  me

for (int i = 0; i < 4; ++i){
while((myNum[i] = keypad.getKey())!=NO_KEY) {
delay(1); // Just wait for a key
}
}  its not working properly. can u send me a full code for that

Put that in your code where you previously had the for() loop.

I did it but its not working properly. can u send me a whole code.

I've included the rest of the code above and fixed a bug (sorry).  I've also added some code to make sure the first key is released before reading the next key. If it still isn't working, please describe exactly how it behaves and how that is wrong. But it would be better if you tried to debug it yourself - that way you'll understand what it happening.

#include <Keypad.h>

char myNum[4];

const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};
byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad 8,7,6,5
byte colPins[COLS] = {9, 8, 7, 6}; //connect to the column pinouts of the keypad 4,3,2,1
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );

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

void loop() {
  Serial.println("Enter four-digit num -");  // request for input

  for (char i = 0; i < 4; ++i){
    while((myNum[i] = keypad.getKey())==NO_KEY) {
      delay(1); // Just wait for a key
    }
    // Wait for the key to be released
    while(keypad.getKey() != NO_KEY) {
      delay(1);
    }

  }

  Serial.print("Entered number is = ");
  Serial.print(myNum[0]);
  Serial.print(myNum[1]);
  Serial.print(myNum[2]);
  Serial.println(myNum[3]);
  delay(500);
}


text:
ATmega 2560 with Arduino bootloader running issue
I have designed a board based on an ATmega2560 chip and I burned the bootloader by following this tutorial.
Now I am able to load Blinky and other programs using an FTDI cable. But the issue I am facing right now is the controller runs Blinky fine if I leave the FTDI connected there. If I disconnect the FTDI cable and power-cycle the board it is not running Blinky. If I connect the FTDI, right away it starts blinking.

It looks like something is wrong with my RESET pin connection? Here is what my RESET circuitry looks like:

I also have tried by removing D1 diode but no luck !

Looks like something wrong with my RESET pin connection ... how do you know. please post your schematic

I am not having schematic but I have followed the circuit given above and in additional I put 0.1uf to connect RESET pin with FTDI.

What happens if you momentarily short the reset line to ground and then release it?   Also, what is your power source?  Did you have the 5v line from the FTDI connected when it was working?   Try to figure out which connections to the FTDI correlate with it starting to work.

Chris,
I have 12v supply which is then stepped down to 5v. No I am not using power from FTDI connection. It starts running when I connect my board Ground with FTDI Ground Pin and FTDI plugged into my PC. I checked I have ground line common.

The issue was there was some noise on RX Pin of the chip and because of that when it is powered on in bootloader it was stuck at that place. And it was working good with FTDI because RX gets proper connection with my FTDI.
Solution:- Connect 10K pull-down on RX pin resolved this problem.

Or get rid of C6, I have never used that in a design.

C6 was not a problem. I have posted the exact solution I found in this case.


text:
L298 module - unusual power specs
I would like to purchase this dual H-bridge module. I plan on connecting it to an Arduino Uno. In the products datasheet the specified power supply (Vd) is 6.5-12V, and the voltage for the motor control pins is 2.3V HIGH and -0.3V LOW.
My question is whether this product is compatible with the standard 5V of Arduino Uno for both the power supply and logic; i.e. can I connect the Vd to the 5V terminal of the Arduino and the control pins to the digital terminals?
If not, what modifications do I need in order to use this H-bridge with an Arduino?
Note: Originally I bought this cheap module and connected the motor control pins to the Arduino, but each output returned a different output voltage!

Yes, it's compatible with the Arduino, but realistically speaking it is not compatible with motors or batteries.  The L298 (L293, etc) is a terribly lossy, antiquated part based on bipolar transistors, and only keeps showing up as module vendors have latched onto intertia from past usage dating from 20 years ago when there were few alternatives.  Get something modern that uses FET's instead.

That's a very poor datasheet. I think it's using equals signs where it means less-or-equal, so:

High level: 2.3V = Vin = Vss

Intends to say that Vin between 2.3 and Vss will be considered high, and

Low:-0.3V = Vin = 1.5V

Intends to say that Vin between -0.3 and 1.5V will be considered low.
"Vss" in the high level definition is confusing, because in the rest of the datasheet, "VD" is used for the logic voltage and "VS" is used for the motor; you'd expect the upper limit to be the logic voltage.
The diagram at the end of the datasheet shows how it can be used with an Arduino. A 7.5V source is going into the Vin pin (instead of the barrel jack, which is unusual). There's a protection diode on the power input which incurs a ~1V voltage drop, so the Arduino Vin pin should be outputting 6.5V, which drives the board. The digital outs from the Arduino, when driven high, are at 5V, well above the 2.3V threshold given on the datasheet.
I'd recommend powering the Arduino through the barrel jack with a 7.5V or 9V supply to drive the logic side of the board. (Powering through the USB port will put 5V or less on the Vin pin.)
You'll want a more robust supply for the motor side, because the Arduino can't deliver very much current.


text:
Vcc measurement with internal 1.1V reference fails on 3.3V powered Atmega328
I need to monitor a battery plugged to an ATmega running on standalone mode.
I use the "ATmega on a breadboard (8 MHz internal clock)" bootloader.
More info here
When the ATmega is powered with 5V the sketch outputs good values : arround 5100 mV.
But when I power it with 3.3V the sketch gives strange values : arround 178619 mV.
Here is my code Inspired from here
void setup()
{
  Serial.begin(9600);
  Serial.println(F("Internal Voltage Sensor"));
}

void loop()
{
  Serial.println( readVcc());
  delay(1000);
}

long readVcc()
{
  long voltage=0;
  uint8_t wADC;

  // Read 1.1V reference against AVcc
  // set the reference to Vcc and the measurement to the internal 1.1V reference
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  ADCSRA |= _BV(ADEN);  // enable the ADC

  delay(20); // Wait for Vref to settle

  ADCSRA |= _BV(ADSC); // Start conversion
  while (bit_is_set(ADCSRA,ADSC)); // measuring

  // Reading register "ADCW" takes care of how to read ADCL first and ADCH then.
  wADC = ADCW;

  voltage = 11253000L / wADC; // Calculate Vcc (in mV); 1125.3 = 1.1*1023*1000
  return voltage; // Vcc in millivolts
}

I don't understand what's going on. The returned value with Vcc=3.3V should be lower than with VCC=5V. Something like 3300 mV !

Try adding some more Serial.printlns to you code. E.g. Serial.println(wADC);

ADCL is the lower byte, ADCH is the higher byte, and the must be read ADCL first and then ADCH. The ADCW tells the compiler to read the two bytes in the right order. Using ADCW is of course easier, and even better, because it can't go wrong... unless you try to put 16 bits of ADCW into a byte and throw away the higher byte. Make wADC a uint16_t.

Thanks for your answers!
Jot gave the solution: wADC must be a uint16_t.
Here is the corrected code :
void setup()
{
  Serial.begin(9600);
  Serial.println(F("Internal Voltage Sensor"));
}

void loop()
{
  Serial.println(readVcc());
  delay(1000);
}

long readVcc()
{
  long voltage=0;
  uint16_t wADC;

  // Read 1.1V reference against AVcc
  // set the reference to Vcc and the measurement to the internal 1.1V reference
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  ADCSRA |= _BV(ADEN);  // enable the ADC

  delay(20); // Wait for Vref to settle

  ADCSRA |= _BV(ADSC); // Start conversion
  while (bit_is_set(ADCSRA,ADSC)); // measuring

  // Reading register "ADCW" takes care of how to read ADCL first and ADCH then.
  wADC = ADCW;

  voltage = 1125300L / wADC; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000
  return voltage; // Vcc in millivolts
}

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Arduino connection with Arduino
I have 3 Arduino boards, let's call them be A, B, C. I'm connecting A with a bluetooth module and I'm getting the input from the bluetooth module.
Now I want to send output from A using the digital pins and I want the output of A to be the inputs of B and C. The output sent from A will be based on voice input from the bluetooth module. The inputs of B and C will provide output signals to L293D and L298N motor drives. I have only one bluetooth module. Is this possible? Please let me know, it's urgent. I'm working on a project.

No. Simple as that

If you can connect ABC with wires, then it is easy - I use Wire library to send a lot of messages to net of many Arduinos.
Also other protocols are avaiable, like SPI, software serial, ... or if the communication is extremely easy (like just On/Off), then digitalWrite()/digitalRead() would work really easy.
I see the voice input to be more difficult in Arduino-size computers (voice recognition is not easy), but maybe you can process the voice before sending BT (on PC/tablet/phone/...) and then the BT would transfer only simple commands and it would be no problem at all.
If there is something I missed, you may write more, where you see the main problem.


text:
"Soft WDT reset" stack error: RFID-RC522 with NodeMCU
I have been all over the internet to try and find a solution to this, but after one solid week of intense Google searching I have come up with nothing.
What I'm trying to accomplish:
I am simply trying to use the RFID-RC522 NFC reader on an NodeMCU development board (built in ESP8266) with the mfrc522 library.
Problem:
Upon initiating the mfrc522 library, reaching the line mfrc522.PCD_Init(); the Serial outputs the following "error":
Soft WDT reset

ctx: cont
sp: 3ffefa10 end: 3ffefc40 offset: 01b0

>>>stack>>>
3ffefbc0:  00241001 00000001 3ffeec20 40106895
3ffefbd0:  00000002 3ffee9d8 3ffee9f4 40202794
3ffefbe0:  402010b2 00000001 00000032 402010a7
3ffefbf0:  3fffdad0 00000010 3ffee9d8 4020290d
3ffefc00:  402010b2 3ffee9d8 3ffee9d8 40202a01
3ffefc10:  feefeffe 00000000 3ffeebec 40202080
3ffefc20:  feefeffe 00000000 3ffeec08 40203e08
3ffefc30:  feefeffe feefeffe 3ffeec20 40100108
<<<stack<<<
R+⸮⸮⸮

I found a tool that can translate the error EspExceptionDecoder, translated error:
Decoding 10 results
0x40106895: __digitalWrite at C:\Users\my_user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/core_esp8266_wiring_digital.c line 84
0x40202794: MFRC522::PCD_ReadRegister(MFRC522::PCD_Register) at C:\Users\my_user\Documents\Arduino\libraries\MFRC522\src/MFRC522.cpp line 1141
0x402010b2: delay at C:\Users\my_user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/core_esp8266_wiring.c line 54
0x402010a7: delay at C:\Users\my_user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/core_esp8266_wiring.c line 51
0x4020290d: MFRC522::PCD_Reset() at C:\Users\my_user\Documents\Arduino\libraries\MFRC522\src/MFRC522.cpp line 1141
0x402010b2: delay at C:\Users\my_user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/core_esp8266_wiring.c line 54
0x40202a01: MFRC522::PCD_Init() at C:\Users\my_user\Documents\Arduino\libraries\MFRC522\src/MFRC522.cpp line 1141
0x40202080: setup at C:\Users\my_user\OneDrive\Arduino\projekter\RFID_DumpInfo_test/RFID_DumpInfo_test.ino line 53
0x40203e08: loop_wrapper at C:\Users\my_user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/core_esp8266_main.cpp line 57
0x40100108: cont_norm at C:\Users\my_user\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.4.0\cores\esp8266/cont.S line 109

When the mfrc522.PCD_init(); line is commented out the stack-error does not appear.
Reading the NFC tags has worked before on the NodeMCU unit, and I sometimes stubmled upon this error when adding one simple line like var1 = var2; somewhere in the loop, but now the error is there constantly, even with code that once worked - however I did change the pin-loadout, and I suspect that this is the problem.
What I have tried:

With the configurable pins I have tried most combinations I could
think of, trying both the SS and the RST in every available pin.
this Github
example suggets
this
instructables tutorial.
3 different RFID-RC522 modules (same model)
2 different NodeMCU units (same model)

Pin layout:
My pin layout for the RFID-RC522 module is as follows;

SDA (SS): D4
RST: D3
SCK: D5
MOSI: D7
MISO: D6
GND: GND
3v3: 3v3

Arduino project info:

Arduino IDE 1.8.5
Latest MFRC522 from the Library Manager
Board: NodeMCU 1.0 (ESP-12E Module)

Code:
#include <SPI.h>
#include <MFRC522.h>

#define SS_PIN          D4
#define RST_PIN         D3

MFRC522 mfrc522(SS_PIN, RST_PIN);

void setup() {
    Serial.begin(9600);
    delay(100);
    SPI.begin();
  delay(100);
    mfrc522.PCD_Init();
    mfrc522.PCD_DumpVersionToSerial();
    Serial.println(F("Scan PICC to see UID, SAK, type, and data blocks..."));
}

I've been on this issue for days now, and my Google searches tell me that I'm not the only one who has had this problem before. Any input is very welcome.

I have come to the conclusion that using RFID with NodeMCU is not going to work - I can't confirm this, but I'm pretty sure the two libraries (ESP8266 and mfrc522) have some complications caused by one another.
A good workaround is using the TX and RX pins to communicate from an Arduino Nano which has the RFID reader to a NodeMCU board - this way you can send the NFC data to your WiFi board without complications.

can you also try to increase the serial boud rate to fe. 115200 instead of 9600?
In some cases I had some issues with 9600, because some buffers were not cleared fast enough and forces some WDT resets.
Cheers,
Jorgen

now this is interesting!  i had this issue backwards.  I thought that slower was "better".  UPVOTED!  :)


text:
Using malloc() and free() for a stack/linkedlist
I know this question has been asked before, however it was asked two years ago and I have some other constraints to add.
(Previous question here) : Is using malloc() and free() a really bad idea on Arduino?
I understand that dynamically allocating and freeing memory can cause fragmentation, and without an operating system to manage the memory, this fragmentation can reach a point where no memory can be allocated because the current memory is a mess.
That being said, the only memory allocation I plan to do is for a linked list that I am using as a stack. This means that I will only even be adding or removing from one end of the linked list. In the case that the arduino malloc() implementation is 'next fit', is it safe to assume that I can use this linked list safely, since the only element I'll be removing is the next one that fit, and everything else will stay where it is?
tl;dr the two questions I'm asking:
Is the arduino malloc implementation 'next fit'? Where can I read up on this in detail?
AND
A single stack running in a 'next fit' environment will never cause fragmentation, correct?

In such a simple case there's no need for a malloc() style memory allocator, and no reason to suffer the overhead.  Just eternally reserve the entire memory you want and track usage with the pointer of your custom stack.  There's also no reason to make your list linked.

The stack will need to be of modular size. I could allocate a maximum size and expire stack entries, but that would require shifting the entire stack every time an entry is expired, I'm not sure but I would assume that's a fairly large overhead.

You only have so much memory available on the chip.  You can grab all that you'd be willing to let a malloc() try to use, and track varying partial usage of it yourself with a single number.  No "shifting" of anything involved.  Or else there's something you're not telling us.  Take a minute and think about how an actual stack works - does that match what you are doing?  If not, don't call it a stack.

Linked list and stack are two different data structures and it doesn't really make sense to use a linked list to implement a stack, a LIFO queue that is accessed from one end only. I'm not saying that you couldn't do it I'm just saying that from a performance and code stand point it doesn't make much sense.

I'm voting to close this question as unclear, since the asker has failed to specify what they are really trying to acomplish by using a linked list of dynamically allocated elements to emulate a stack.  This smells strongly like an XY problem.

On my answer to the question you are referencing, I state that “If
you use the heap like a stack (last in is first out), then it will
behave like a stack and not fragment.” This seems to be exactly your
usage pattern, thus you should not fear fragmentation. Of course, the
caveat written in Michel Keijzers’ answer applies: you should make sure
that no other part of your code, including libraries, is using
malloc() and free().
Just to give some evidence, the avr-lic documentation provides some
implementation details about malloc:

When allocating memory [...] If nothing could be found on the
  freelist, heap extension is attempted. [...] When deallocating the
  topmost chunk of memory, the size of the heap is reduced.

All this can be seen in action in the source code of malloc() and
free(), which is abundantly commented and quite readable.

Edit 1: From the same section of the avr-libc documentation, we learn
about how realloc() grows a memory chunk:

If [...] the old chunk is at the top of heap, and the above freelist
  walk did not reveal a large enough chunk on the freelist to satisfy
  the new request, an attempt is made to quickly extend this topmost
  chunk (and thus the heap), so no need arises to copy over the existing
  data.

Based on this, I would suggest you use an array, rather than a linked
list, and use realloc() to adjust the size of the array. A linked list
of n objects of size m has a memory cost n × (m+4):
each objects has an overhead of 2 bytes for the linking pointer, plus 2
bytes for malloc()'s internal bookkeeping. The cost of an array would
be only (n × m)+2.
In this case, however, it is essential that no other part of your code
uses malloc(), otherwise realloc() could end up allocating a whole
new array, which would be very costly.

Edit 2: I wrote a small test program that randomly grows and shrinks
a memory buffer. Running the test on an Uno shows that the allocated
memory chunk never changes address even though its size varies wildly.
void setup()
{
    Serial.begin(9600);
}

void loop()
{
    static void *p;
    static size_t sz;
    sz = random(max(sz, 22) - 20, min(sz + 20, 1536) + 1);
    p = realloc(p, sz);
    Serial.print((uintptr_t) p);
    Serial.print("  ");
    Serial.println(sz);
}

You really, really, really don't want to use realloc() for something of substantial size.  In the case where it's safely exclusive, it's unnecessary, and in the case where it's unsafe it fails horribly since the chip likely can't fit a new copy of the whole thing.  This really does not seem to be a situation where dynamic allocation is called for, but if it's going to be used and the allocation grown then a linked list should be used so that it doesn't have to be contiguous.  Otherwise it should be a statically allocated array deterministically reserving the maximum needed size.

Probably it will not be a problem, since when you free memory, those memory sizes will be equal than the memory size you malloc. E.g. suppose one element of a linked list is 24 bytes, if this is freed, the next time when 24 bytes are requested by malloc, it will use that space.
So my assumption it works when you never use free or malloc, EXCEPT when using it for one single linked list with elements that are always equal size.
However, you have to make sure:

You do not free memory elsewhere (with different size)
You do not malloc memory elsewhere (with different size)
All libraries you use do not call a malloc/free under water.

Also, you can do an easy check by malloc/free and fill one item a lot of times one element (thus adding and removing it), and checking the memory usage is similar (or it does not crash to have a very simple test).
Btw, afaik Arduino pointers use 2 bytes, so this can cause quite some memory. If you use max. 256 elements, consider using indices, but in this case you have to write your own 'linked list' library (e.g. when removing, you have to move all subsequent indices).

That's a good point about the libraries, and I'll keep that in mind as I develop.

I haven't checked Arduino libraries, but I assume these do not use malloc/free, but in your case it might be important.

The standard Arduino String class uses realloc().

There are many implementations of malloc() and AFAIK, none is specified in the standard. So, while you could get lucky and and find that your preferred environment uses a malloc() algorithm compatible with your intended use, your code will not be known portable to another, unspecified, environment, and even a compiler or library revision to your preferred environment could break you code.
You'd be better off to write an allocator that works as you need it to work. Whether you need a linked-list or an array of fixed size blocks to accomplish your stack structure, using a getStackFrame(), freeStackFrame() pair of functions, written and controlled by you, will avoid some potential nasty surprises.


text:
Use of array in case statement
I want to know how I can use case statement for each array.
Below is my code:
int incomingByte = 0;

void setup()
{
  Serial.begin(115200);
  for (int thisPin = 2; thisPin < 6; thisPin++)
  {
    pinMode(thisPin, OUTPUT);
  }
}

void loop()
{
  int button1[] = {0xFF, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05};
  int button2[] = {0xFF, 0x04, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06};
  int button3[] = {0xFF, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08};
  int button4[] = {0xFF, 0x04, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C};

  if (Serial.available() > 0)
  {
    incomingByte = Serial.read();
  }

  switch (incomingByte)
  {
    case button1:
      digitalWrite(2, HIGH);
      break;
    case button2:
      digitalWrite(3, HIGH);
      break;
    case button3:
      digitalWrite(4, HIGH);
      break;
    case button4:
      digitalWrite(5, HIGH);
      break;
    default:
      for (int thisPin = 2; thisPin < 6; thisPin++)
      {
        digitalWrite(thisPin, LOW);
      }
  }
}

Not checked/compiled, just to give an idea.
/* One button message is 12 bytes, it is assumed that all received messages are 12 bytes. If note, you have to check later differently. */
#define MSG_SIZE 11
byte incomingBytes[MSG_SIZE]; /* Storage for 11 bytes */
byte index = 0; /* Current byte to set within incomingBytes */

void setup()
{
  Serial.begin(115200);
  for (int thisPin = 2; thisPin < 6; thisPin++)
  {
    pinMode(thisPin, OUTPUT);
  }
}

void loop()
{
  if (Serial.available() > 0)
  {
    /* Store the next incoming byte. Assume 0xFF is the start of a message. */
    byte incoming_byte = Serial.read();
    if (incoming_byte == 0xFF)
    {
      index = 0;
    }

    incomingBytes[index] = incoming_byte;
    index++;
    if (index >= MSG_SIZE)
    {
       check_message();
       index = 0;
    }
  }
}

/* Checks which button is pressed and performs an action based on the
pressed button. */
void check_message()
{
  case check_button_pressed())
  {
    case 1:
      digitalWrite(2, HIGH);
      break;
    case 2:
      digitalWrite(3, HIGH);
      break;
    case 3:
      digitalWrite(4, HIGH);
      break;
    case 4:
      digitalWrite(5, HIGH);
      break;
    default:
      for (int thisPin = 2; thisPin < 6; thisPin++)
      {
        digitalWrite(thisPin, LOW);
      }
  }
}

/* Checks which button is pressed by comparing 11 incoming bytes to the
four buttons to be checked. Returns -1 for an illegal message/unsupported
button and 1, 2, 3 or 4 for the pressed button. */
int check_button_pressed()
{
  int button_pressed = -1;
  if ((incomingBytes[0] == 0xFF) &&
      (incomingBytes[1] == 0x04) &&
      (incomingBytes[3] == 0x00) &&
      (incomingBytes[4] == 0x00) &&
      (incomingBytes[5] == 0x00) &&
      (incomingBytes[6] == 0x00) &&
      (incomingBytes[7] == 0x00) &&
      (incomingBytes[8] == 0x00) &&
      (incomingBytes[9] == 0x00))
  {
    if ((incomingBytes[2] == 0x01) && (incomingBytes[10] == 0x05))
    {
      button_pressed = 1;
    }
    else if ((incomingBytes[2] == 0x02) && (incomingBytes[10] == 0x06))
    {
      button_pressed = 2;
    }
    else if ((incomingBytes[2] == 0x04) && (incomingBytes[10] == 0x08))
    {
      button_pressed = 3;
    }
    else if ((incomingBytes[2] == 0x08) && (incomingBytes[10] == 0x0C))
    {
      button_pressed = 4;
    }
  }
  return button_pressed;
}

I'd add something to explicitly re-sync the stream when 0xFF is received, to handle variable length messages and cases where the serial connection is established in mid-message, but otherwise this is a good approach.

True, this is in case all messages are same length. But I don't know what the start of a message is, probably 0xFF. If so, if character is encounter, set Index to 0

@RussellBorogove I adapted the code for it.

yw ... if it is helpful, you can upvote the helpful answers, and select one which you consider best to answer your question (and press accept).

case doesn't work like that; it can only switch on a single integer. Are you trying to pattern-match those sequences of bytes? You'll have to use some sort of state machine instead, keeping track of what bytes you've received and where in the expected pattern you are.

Can you give me some hints? I am a newbie and i don't know much about Arduino. Thanks

As mentioned it won't work.
But also note you read a single byte, but your arrays have eleven items in them.  You should probably read  11 bytes and use a comparison routine.  (memcmp, etc.)


text:
Meaning of part number suffix on top of atmega2560 chip
I have been working on creating a stand alone atmega2560 arduino. When trying to program it with a serial adapter using the rx and tx pins nothing was happening. After a lot of debugging I found the problem was with the chip.
I found that the ones that worked said atmega2560 16AU 0721, the ones that did not work said Atmega2560 16AU 1241. When looking on eBay, i noted that the Atmega2560 16AU comes with many different versions of those last four numerals, does anyone know what the last four digits on top of the atmega2560 16AU mean?

Since you have an ICSP header please use my chip detector sketch to report on the chip. It will tell you if it responds (thus proving the chip is more-or-less OK) plus the fuse settings, and what bootloader is installed. You can edit this information into the question.

1241 = 41st week of 2012. 0721 is 21st week of 2007.

indeed the problem was with the Bootloader. I was using the default one available in the Arduino IDE. I changed to use the one create by Nick Gamon, https://github.com/nickgammon/arduino_sketches , and problem solved. I can now program the ATMEGA2560 via serial.

The last four digits are a date code - the date of manufacture.
It's in the form YYWW where YY is the last two digits of the year, and WW is the week number.
So 0721 is the 21st week of 2007, and 1241 is the 41st week of 2012.

The data sheet (or supplemental product-line documentation) will specify the formal package marking codes, but for an ATmega, the 16AU is part of the variant specification but the following would appear to be date or lot codes.
These are probably not your problem.
More likely, the chip you are trying to interact with via the serial port

does not have a bootloader flashed (normally they are sold blank)
has a bootloader which requires a different baud rate
is fused for a clock source you are not providing
has the brownout detector set lower than the supply you are providing
is improperly or incompletely soldered
is damaged

While there was the infamous case of Sparkfun being sold a reel of power supply chips falsely marked as ATmega328's, this is still a relatively unlikely possibility compared to the more likely ones above, especially the simple lack of a bootloader.  And a date code is no proof of authenticity - though if you ended up co-mingly inventory from various sources/purchases, it might help you with preliminary sorting them.

Thanks Chris...I used the iCSP header to install the same bootloader in both chips. I have several chips of the one that do not work, and it is the same problem with all of them, so I do not think it is a defective chip. I also checked all connections and soldering. I will check the baud and clock.

That information belongs in the body of your question - use the edit button.

You should use the ISP to load a sketch which tries the other serial ports and produces output without needing input.  Also which toggles pins at a known rate, and then measure that rate and see if it is correct...

I think Chris is very likely right about the clock source. The default for the low fuse byte is for the "divide clock by 8" bit to be programmed, which means that you would be able to interface via ICSP, but to use the bootloader the baud rate would be 8 times too slow.

Any suggestion to  fix this problem? I have installed the bootloader available in the arduino IDE in both chips.


text:
Portal gun sound effects and lights
I'm building a portal gun from the game Portal and I'm struggling with the wiring for the lights and sound. I've the lights working using the first image from Instructables and adding more LEDs shouldn't be a problem. I'm trying to add the SD card and speaker so when you flick the switch, as well as the lights changing, the firing sound is played. Image 2. everything is wired quite nicely the only change is I'm using pin 10 not 4 on the memory card.

This is my code and it all compiles fine and seems to make sense to me but I'm new to programming.
The lights work but none of the sounds play. I've formatted the SD card and also made sure the .wav files are the right format: mono 8 bit 16000 Hz. I can't work out what's wrong and why I can't get it to play the sounds.
I also have an Adafruit amp just in case it isn't loud enough but not a clue how to wire it in.
#include <pcmRF.h>
#include <TMRpcm.h>
#include <SD.h>                       // need to include the SD library
#define SD_ChipSelectPin 10            // using digital pin 10 on arduino uno 328, can use other pins
#include <SPI.h>

void setup()
{
  // put your setup code here, to run once:
  TMRpcm tmrpcm;
  tmrpcm.speakerPin = 9;          //5,6,11 or 46 on Mega, 9 on Uno, Nano, etc

  Serial.begin(9600);
  if (!SD.begin(SD_ChipSelectPin))
  {
    Serial.println("SD fail");
    return;
  }
  tmrpcm.setVolume(6);
  tmrpcm.play("1.wav");
  tmrpcm.play("2.wav");

  //set the switch input, pin 8, as an
  pinMode(8, INPUT);

  //set both the LED pins, pin 5 and 6 as OUTPUTs
  pinMode (5, OUTPUT);
  pinMode (6, OUTPUT);
}

void loop()
{
  TMRpcm tmrpcm;
  int switchValue = digitalRead(8);
  if (switchValue == 1)
  {
    digitalWrite(5, HIGH);
    digitalWrite(6, LOW);
    tmrpcm.setVolume(6);
    tmrpcm.play("4.wav");
  }
  else
  {
    digitalWrite(6, HIGH);
    digitalWrite(5, LOW);
    tmrpcm.setVolume(6);
    tmrpcm.play("5.wav");
  }
}

Well, that first image really sums up Instructables nicely... shudder

At a guess I would say your main problem is you are defining your TMRpcm objects within the setup and loop functions, which means that as soon as that function exits the TMRpcm objects will be disposed of. I.e., it won't work. It may start playing a sound in setup(), but it will stop (and maybe even crash completely) before you even have a chance to hear it.
Your TMRpcm object must be declared globally for you to have any hope of making it work.
TMRpcm tmrpcm;

void setup() {
    // ....
    tmrpcm.speakerPin=9;
    tmrpcm.setVolume(6);
    tmrpcm.play("1.wav");
}

etc.
Another thing to note is that TMRpcm plays the sounds asynchronously. That is, it doesn't wait while it plays the sound, so if you play one sound and then another sound the second sound will start before the first one has even begun playing, so you'll never hear the first one.  Instead, if you want to play sounds sequentially, you should for the first sample to finish using something like:
while (tmrpcm.isPlaying()) {
    delay(1);
}

which will stop your sketch running until the last sound has finished.  Including the delay(1) is a good idea since it allows yield() to execute allowing anything that needs it to run (not really a problem on an Uno, but on things like an ESP8266 it's absolutely critical or you get a watchdog timeout).

Thank you :) it's working, although now it loops the wav over and over i only need it to do it once. Is there a quick way of fixing that?

You need to learn how to recognise when the switch changes position - that is, the moment in time when it changes from LOW to HIGH, and only play at that point.


text:
This logic level converter does not want to work
I got this logic level converter to be able to use my lcd but I can't figure out how to get it to work, the problem is that the current is not passing through. This is the model: TXS0108E

Any help is appreciated.
[EDIT]
A few Combinations that I have tried:

And I tried to swap the voltages, same wiring as in the pictures but 3.3v instead of 5v and vice versa.

Could you tell what you tried? Did you pull the OE pin HIGH?

@Gerben okay, i will add a few photos with what i have tried

@Gerben I made the edit

Assuming your lines saying "3.3V" are connecting to a 3.3V power supply, your first picture is correct. VA => 3.3V, OE => 3.3V, VB => 5V and GND => GND.

@Majenko the 3.3V are connected to the lcd, the 5v is connected to the 5v Pin on the arduino.

Where is the 3.3V coming from?

The GNDs for the 3.3V and 5V are connected? I.e. not from isolated sources. If missing the connections you made for testing? For example, connect GND to A1 and read voltage on B1. Connect Vcc-A to A1, and read voltage at B1

@Majenko the 3.3V is connected to the lcd, i want to lower the voltage from the arduino (5v) to 3.3v

@Gerben well, the lcd is connected to GND on the arduino and the GND on the board is connected to the arduino aswell

@Gerben This isn't the first time, and I doubt it'll be the last time, where I have seen someone assume that a logic translator like this magically provides a regulated voltage out from VCCA...

@Majenko sorry about the silly mistake, i'm still learing. I am working on a project for physics.

@xM0nSt3r It's ok - as I said, I've seen it before. You're not the first, so don't beat yourself up about it :)  Maybe I should design and sell a 5V -> 3.3V logic level shifter with built-in regulator. And maybe a 3.3V -> 5V shifter with built-in 3.3V->5V boost regulator for users of 3.3V Arduinos...

@Majenko that would help avoid these questions :)) start working then :P

The TSX0108 doesn't magically provide you with a regulated voltage. You have to provide the voltage, the TSX0108 merely switches it.
As you can see from the datasheet, the basic wiring is:

In the circuit above the 1.8V connection is your 3.3V connection, and the 3.3V is your 5V connection.
You must provide both the 3.3V and 5V power sources.

and how do i provide 3.3 v from an lcd?

By connecting it to a 3.3V power source - such as the 3.3V pin of the Arduino.

so i provide 3.3v and 5v from the arduino, and then that regulates the data pins voltage?

Crudely speaking, yes. It's just a set of switches. A signal coming in through an A pin switches the voltage provided at B to the matching B pin. A signal coming in through a B pin switches the voltage provided at A to the matching A pin.


text:
Arduino Nano wih mfrc522 warning error
UPDATE
I have managed to get rid of the WARNING: Communication failure, is the MFRC522 properly connected?. Unfortunately, that did not fix the firmware error it now says 0x80. I have now also tried using different IDEs from arduino in the hopes of fixing this, still nothing. The connection error between the reader and the arduino has come back as well.
Furthermore...
*****************************
MFRC522 Digital self test
*****************************
Firmware Version: 0x92 = v2.0
-----------------------------
Only known versions supported
-----------------------------
Performing test...
-----------------------------
Result: DEFECT or UNKNOWN

would this now mean that my device is a defect?
Also, that version has gone back to showing unknown and the other hexadecimal codes.
I have just bought the parts. The arduino nano v3 and the MFRC522 based RFID reader. I have followed the typical pin layout after downloading the library from arduino. When I go to test one of the examples I get a warning within the arduino serial monitor :
Firmware Version: 0xFF = (unknown)
WARNING: Communication failure, is the MFRC522 properly connected?
Scan PICC to see UID, SAK, type, and data blocks...

I try to scan one of the existing cards but nothing happens. It either stats that it is version 0xFF or 0x0. I am new with this and this is my first 'project'. the pins are defined.

I have 3.3V on the reader to 3v3 on the arduino
I have RST on the reader to D9 on the arduion
I have GND on the reader to GND on the arduino (on the same side as the 3v3 is )
I have MISO on the reader to D12 on the arduino
I have MOSI on the reader to D11 on the arduino
I have SCK on the reader to D13 (on the same side as the 3v3 is)
I have SDA on the reader to D10 on the arduino
The code I am using is from the arduino library manager:
  /*
  * --------------------------------------------------------------------------------------------------------------------
  * Example sketch/program to test your firmware.
  * --------------------------------------------------------------------------------------------------------------------
  * This is a MFRC522 library example; for further details and other examples see: https://github.com/miguelbalboa/rfid
  *
  * This example test the firmware of your MFRC522 reader module, only known version can be checked. If the test passed
  * it do not mean that your module is faultless! Some modules have bad or broken antennas or the PICC is broken.
  * NOTE: for more informations read the README.rst
  *
  * @author Rotzbua
  * @license Released into the public domain.
  *
  * Typical pin layout used:
  * -----------------------------------------------------------------------------------------
  *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
  *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
  * Signal      Pin          Pin           Pin       Pin        Pin              Pin
  * -----------------------------------------------------------------------------------------
  * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
  * SPI SS      SDA(SS)      10            53        D10        10               10
  * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
  * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
  * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3              15
  */

 #include <SPI.h>
 #include <MFRC522.h>

 constexpr uint8_t RST_PIN = 9;     // Configurable, see typical pin layout    above
 constexpr uint8_t SS_PIN = 10;     // Configurable, see typical pin layout    above

 MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

 /**
  * Check firmware only once at startup
  */
 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 module

Serial.println(F("*****************************"));
Serial.println(F("MFRC522 Digital self test"));
Serial.println(F("*****************************"));
mfrc522.PCD_DumpVersionToSerial();  // Show version of PCD - MFRC522 Card Reader
Serial.println(F("-----------------------------"));
Serial.println(F("Only known versions supported"));
Serial.println(F("-----------------------------"));
Serial.println(F("Performing test..."));
bool result = mfrc522.PCD_PerformSelfTest(); // perform the test
Serial.println(F("-----------------------------"));
Serial.print(F("Result: "));
if (result)
  Serial.println(F("OK"));
else
  Serial.println(F("DEFECT or UNKNOWN"));
Serial.println();
 }

 void loop() {} // nothing to do

This happens when you wrongly interconnect the pins. are you using i2c comm ?

Or SPI communication ?

What are they? I am really new to this

The communication method used by your module with arduino. Its either SPI or I2C. This error happens when these comm. pins are wrongly connected.

I am not sure what one it uses, I just connected the pins directly to each other using F-F jumper cables

Put your schematic in the question.

Put your code too

You are using SPI comm. The code is fine too. Usually this "communication failure" happens due to wrong pin connections. Say for eg. If MOSI and MISO are interchanged. Check all connections, ground and VCC connections once more. I have also seen that soldering the pins of MFRC522,  instead of simply connecting by wire has solved this issue most of the time. Another work around is repeatedly calling PCD_init() function even after failing result inside loop() . And see whether its working. If none of these worked, hard luck. I think its firmware issue or defective board.

Ugh... Looks like I have a faulty board :( Thank you for your help

Anyway try both the methods...especially soldering method. These are really delicate and cheap modules. Lotta defective boards are there in the market.


text:
Ethernet shield compatibility
Does anyone know if there is an Ethernet shield is compatible with the Arduino Ethernet shield (R3)? The R3 does not seem to be in production anymore and I need a replacement shield. Found some from Velleman, or maybe Ethernet Shield 2?

Arduino Ethernet Shield R3
Arduino Ethernet Shield 2
Velleman Ethernet Shield

Will you kindly provide a link to the Velleman shield?

Added links to the boards

No, it is not compatible.  It uses the ENC28J60 chip from Microchip, whereas the others all use the W5100 Wiznet chip. A very different chip.
You can use it if you refactor all your code to use the Ethercard library instead of the Ethernet library.
There are cheap Chinese (or other far east) clones of the Ethernet Shields, that use the W5100 (or a counterfeit copy) that people have varying amounts of luck with if you really need W5100 compatibility. I have one, but have had problems with it starting up properly sometimes and needs a bit of a kick with the reset button.

UIPEthernet library https://github.com/ntruchsess/arduino_uip for the ENC28J60. I didn't try it yet


text:
How to create a log file document which is not editable by a word processor on SD card
I'm using a Arduino Mega 2560  and SD card shield to make an industrial logging panel. Is there any way to write log data document in a read-only type file like a pdf on SD card so that the contents cannot be edited once created by word processing software? The data has to presented as a document on a windows machine.
Thanks in advance for your time – if I’ve missed out anything, over- or under-emphasized a specific point let me know in the comments.

Comments are not for extended discussion; this conversation has been moved to chat.

There is no such thing as a file that cannot be edited.
If a file can be read it can be edited.
However, there are ways of making it possible to know if a file has been edited - i.e., to integrity check the file. To make it hard to edit a file and maintain the intrinsic integrity of the file.
The simplest method is to create a checksum of the data in the file and store that in the file as well. If the data is, for example, a CSV file, you could include in each row a checksum of the data in that row as an extra column. If the data gets changed the checksum will no longer match. Of course, that doesn't preclude someone calculating the new checksum and entering that.  So maybe adding a checksum of all the checksums at the end of the file as well so you know if any checksums have changed.
Again, it's possible for someone to recalculate that checksum as well.
The most secure method is to digitally sign the file (in the way the PGP or GnuPG does). Without the private key, it's impossible to re-sign the file after modification. However, that kind of operation is comparatively heavyweight and not something an Arduino is particularly suited to doing (I'm not sure if it's even physically possible given the lack of resources an Arduino has).


text:
PROGMEM doesn't cause Sketch size to change
I'm trying to pinpoint some strange behaviour involving the use of PROGMEM and the size of a Sketch.
I've written a library that contains a number of functions, in addition to several large global byte arrays and 32-bit uint arrays. These arrays are stored in PROGMEM using the pgmspace library. The library compiles fine, and all code works properly when uploaded to an Arduino.
I'm performing testing on the functions using a testing sketch that in turn uses my library. In order to test the performance, I've been switching between using PROGMEM and not using PROGMEM in the library (all arrays are under 2KB). When using PROGMEM, it drops the Global Variable dynamic memory count by the expected amount... but the the sketch program size remains either constant, or seems to arbitrarily increase or decrease by a very small amount, depending on the function. For example, a uint8_t byte[256] array, when moved to the PROGMEM, causes the Global Variable size to go down by about 256 bytes... but the sketch size only increases by about 12 bytes.
Each entry in the array is unique and is accessed, so the compiler shouldn't be optimizing it away. I tried just using avr-size directly on the ELF file, but the sketch size was the same. I can't tell if the data is being stored in PROGMEM all the time (even when not declared as PROGMEM, due to some sort of issue with PROGMEM in libraries?), or if PROGMEM data simply isn't being counted as part of the sketch size, or ??? I have tried moving the functions directly out of the library into the sketch, changing data types, adding/removing static and const declarations... but the lack of change in sketch size continues to confuse me. Any help would be greatly appreciated.

That is a whole point to not having constant data in the RAM. However they must be stored somewhere, they're just not copied into the RAM.

all constant data are part of the sketch. where else should they be? in runtime they are loaded into RAM. PROGMEM directive prevents the loading into RAM.

Ah, so either way, the storage size required remains constant? Now it makes sense.


text:
Confusion with Serial Communication
Is a buffer used for outputting data from the arduino?
OR
Is the output from the arduino buffered before sending it to Computer?
Is it the same buffer that is used to store the incoming data and the data that we send back from the arduino?
Eg- If am sending a text through the Serial Monitor to the arduino and I am also doing Serial.println("sth") then are they both using the same buffer?
How can i relate Serial buffer with these processes
Please Help!
Arduino Noob
EDIT-1
Can you please explain about the TX buffer overflow

Duplicate of https://arduino.stackexchange.com/questions/1726/how-does-the-arduino-handle-serial-buffer-overflow?s=1|104.2134 and more literally if less informatively  https://arduino.stackexchange.com/questions/16312/is-the-serial-buffer-going-from-arduino-to-pc-and-from-pc-to-arduino-different

Is it the same buffer that is used to store the incoming data and the data that we send back from the arduino?

there are two buffers RX buffer and TX buffer.

Is a buffer used for outputting data from the arduino? OR Is the output from the arduino buffered before sending it to Computer?

TX buffer holds the data until they can be send. Data are send from TX buffer by interrupt routine.

Can you please explain about the TX buffer overflow

TX buffer overflow doesn't happen, because it is easy to handle the situation.
The interrupt routine can send the data only at set baud rate. If the program fills the buffer faster then the interrupt empties the buffer, then the TX buffer fills, but the write function knows that the buffer is full and waits in a while cycle until there is space for that one byte to write.

Can you please explain about TX buffer overflows

This is incorrect.  The TX buffer does not overflow, rather attempted writes to the Serial object block until there is space.  Unfortunately, speculation about this is yet one of the many consequences of the Arduino documentation failing to state the information needed by serious programmers in fine print at the bottom of its its beginner-friendly pages.

https://arduino.stackexchange.com/questions/1726/how-does-the-arduino-handle-serial-buffer-overflow

I edited the section about the overflow, to not only explain what overflow is, but how it is avoided


text:
Integer looping in EEPROM Read
I am reading data from a 24LC1025 over I2C with an Arduino and then outputing that data to my PC through the Serial interface. The EEPROM chip is seperated into two pages and at address 65535 [0x0FFFF] it switches over to the second page sending [0x10000 through 0x1FFFF] I had it working by reading each address with a random read:
#include <Wire.h>

byte i2c_eeprom_read_byte( int deviceaddress, unsigned long eeaddress ) {
    byte rdata = 0xFF;
    Wire.beginTransmission(deviceaddress);
    Wire.write((eeaddress >> 8)); // MSB
    Wire.write((eeaddress & 0xFF)); // LSB
    Wire.endTransmission();
    Wire.requestFrom(deviceaddress,1);
    if (Wire.available()) rdata = Wire.read();
    return rdata;
}

void setup() {
  Wire.begin(); // initialise the connection
  Serial.begin(9600);
  delay(100); //add a small delay
  Serial.println("Arduino Group Delay Read Program");

  for (unsigned long i = 0; i < 128000; i++){
    Serial.print(i);
    Serial.print(",");
    byte a = i2c_eeprom_read_byte(0x50, i);
    Serial.println(a, BIN);
  }
}

void loop() {
  //
}

To reduce overhead and speed up the process I am now using the code below:
#include <Wire.h>

byte bytes[32];

void i2c_eeprom_read_buffer( int deviceaddress, unsigned long eeaddress, byte *buffer, int length ) {
    Wire.beginTransmission(deviceaddress);
    Wire.write((eeaddress >> 8)); // MSB
    Wire.write((eeaddress & 0xFF)); // LSB
    Wire.endTransmission();
    Wire.requestFrom(deviceaddress,length);
    int c = 0;
    for ( c = 0; c < length; c++ )
        if (Wire.available()) buffer[c] = Wire.read();
}

void setup() {
  Wire.setClock(400000); // 400kHz
  Wire.begin(); // initialise the connection
  Serial.begin(250000);
  delay(100); //add a small delay
  Serial.println("Arduino Group Delay Read Program");

  for (unsigned int i = 0; i < 128000;){
    i2c_eeprom_read_buffer(0x50, i, (byte *)bytes, 32);
    for (int j = 0; j < 32; j++){
      Serial.print(i);
      Serial.print(",");
      Serial.println(bytes[j], BIN);
      i++;
    }
  }
}

void loop() {
  //
}

Unfortunately, the program now loops at the page boundary back to the start of the address range. Here is a sample of the output:
65500,1110100
65501,1101000
65502,1101001
65503,1110011
65504,100000
65505,1101001
65506,1110011
65507,100000
65508,1100100
65509,1100001
65510,1110100
65511,1100001
65512,100000
65513,1100110
65514,1110010
65515,1101111
65516,1101101
65517,100000
65518,1110100
65519,1101000
65520,1100101
65521,100000
65522,1100101
65523,1100101
65524,1110000
65525,1110010
65526,1101111
65527,1101101
65528,0
65529,11111111
65530,11111111
65531,11111111
65532,11111111
65533,11111111
65534,11111111
65535,11111111
0,0
1,0
2,1
3,110000
4,111000
5,111001
6,110110
7,110001
8,111001
9,1000001
10,101110
11,1011000
12,110001
13,110001
14,1010110
15,1011001
16,110001
17,110111
18,110100
19,110001
20,1110100
21,1101000
22,1101001
23,1110011
24,100000
25,1101001
26,1110011
27,100000
28,1100100
29,1100001
30,1110100
31,1100001
32,100000
33,1100110
34,1110010
35,1101111
36,1101101
37,100000
38,1110100
39,1101000
40,1100101
41,100000
42,1100101
43,1100101
44,1110000
45,1110010
46,1101111
47,1101101
48,0
49,111001
50,100010
51,11010010
52,110101
53,1001000
54,11101011
55,11000000
56,110101
57,11101011
58,1011100
59,10010100
60,110101
61,100000
62,10100011
63,1110110
64,10110100
65,10110001
66,1111010
67,11100000
68,10110110
69,101100
70,11010110

I could see how an error in the code could cause the second page to display the first page's values, but there is nothing in the code that should cause the counter itself to loop. Any idea what could be causing this?
Edit:
For anyone who is working a similar issue, here is the code that I ended up with once I solved this issue and then dealt with the page boundary problem (line 4):
#include <Wire.h>

byte i2c_eeprom_read_byte( int deviceaddress, unsigned long eeaddress ) {
  byte rdata = 0xFF;
   if( eeaddress > 65535 ){
    deviceaddress = deviceaddress | B00000100;
    eeaddress = eeaddress & 0xFFFF;
    }
  Wire.beginTransmission(deviceaddress);
  Wire.write((eeaddress >> 8));   // MSB
  Wire.write((eeaddress & 0xFF)); // LSB
  Wire.endTransmission();
  Wire.requestFrom(deviceaddress,1);
  if (Wire.available()) rdata = Wire.read();
  return rdata;
}

void setup() {
  Wire.setClock(400000);
  Wire.begin(); // initialise the connection
  Serial.begin(115200);
  delay(100); //add a small delay
  Serial.println("Arduino Group Delay Read Program");

  for (unsigned long i = 0; i < 128000; i++){
    Serial.print(i);
    Serial.print(",");
    byte a = i2c_eeprom_read_byte(0x50, i);
    Serial.println(a, BIN);
  }
}

void loop() {
}

Note that this last code will work with the i2c_eeprom_read_buffer function as well as long as you add the if statement starting at line 4.

for (unsigned int i = 0; i < 128000;){

An unsigned int can only count from 0 to 65536 on an 8-bit system...  You need that to be an unsigned long, or better, a uint32_t (better because it's guaranteed to be an unsigned 32-bit value on any platform regardless of how wide its registers are).


text:
Help with Serial.print()
How does the Serial.print() transmit the data? Can you please explain this with respect to TX buffers?
Also, What would happen if i try to output the data that is greater than 64 bytes? How is this transmitted?
And please explain the difference with Serial.write()
Thanks!

is it your home work from school?

No how can that be a homework I was just just curious about serial communications. AND BTW I DONT DO homeworks

@Juraj i was reading this https://arduino.stackexchange.com/a/14405/41798 and was curious

you could look into the source code. class Print has all the print functions implemented using write function. HardwareSerial only implements write byte function, which adds a byte into TX buffer

Print is base class of the hierarchy Print <- Stream <- HardwareSerial

and in hierarchy Print <- Stream <- Client <- EthernetClient, the EthernetClient writes the byte into buffer for sending over network

if the TX buffer of Serial is full, the write function waits in a while loop until one byte can be added to buffer

Serial.print() feeds the data into the TX buffer one character at a time (through the Print class's inherited .write() function which HardwareSerial implements). If there isn't enough room in the TX buffer for the next character it waits for there to be room available.
Characters are removed one at a time from the TX buffer and sent through the physical UART by the UART's TX interrupt.
To put it in more detail:

When you call Serial.print() it's actually calling Print.print(), because Print is a parent class of the HardwareSerial class.
Print.print() repeatedly calls Print.write() for each character to print.
Print.write() is a pure virtual function (which means it's only got the definition in the Print class and child classes must implement it).
HardwareSerial.write() implements the Print.write() function which takes the character and (with possible blocking while waiting for space) adds it to the TX buffer.
Serial is an instance of the HardwareSerial class.

Serial.write() adds a byte to TX buffer

@Juraj Serial.print() is actually Print.print() which calls Print.write() which is a pure virtual function implemented by the HardwareSerial child class.

I didn't say something else


text:
Why is my keypad requiring a double-click only on the first row to register?
I have a keypad that is connected to my Arduino and each time a key is pressed, the number should be outputted to an LCD screen. The issue is that after the screen is cleared, and a new ID is being entered, any number on the first row will not trigger a keypress event but only on its first click. If you press it twice, it works completely fine. I am using the Keypad library and here is my code. Thanks for any help!

#include <ESP8266WiFi.h>
#include <Keypad.h>
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

#define I2C_ADDR    0x3F // <<----- Add your address here.  Find it from I2C Scanner
#define BACKLIGHT_PIN     3
#define En_pin  2
#define Rw_pin  1
#define Rs_pin  0
#define D4_pin  4
#define D5_pin  5
#define D6_pin  6
#define D7_pin  7

const char* ssid     = "**";
const char* password = "**";

const char* host = "**";
const char* getSystem = "**";
const char* apiKey = "**";
const char* systemIdentifier = "**";

const byte n_rows = 4;
const byte n_cols = 3;

char keys[n_rows][n_cols] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

byte rowPins[n_rows] = {D2, D3, D4, D5};
byte colPins[n_cols] = {D6, D7, D8};

int n = 1;
String idNumber;

boolean checkingIn = false;

LiquidCrystal_I2C  lcd(I2C_ADDR, En_pin, Rw_pin, Rs_pin, D4_pin, D5_pin, D6_pin, D7_pin);
Keypad myKeypad = Keypad( makeKeymap(keys), rowPins, colPins, n_rows, n_cols);

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

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  lcd.begin (16, 2);

  // Switch on the backlight
  lcd.setBacklightPin(BACKLIGHT_PIN, POSITIVE);
  lcd.setBacklight(HIGH);
  lcd.home ();

  lcd.print("Connecting");

  while (WiFi.status() != WL_CONNECTED) {
    lcd.print(".");
    delay(500);
  }

  setLCD("Please Enter ID#", 0);
  setLCD("                ", 1);

  delay(500);
}

void loop() {
  if (!checkingIn) {
    char myKey = myKeypad.getKey();
    Serial.print(myKey);
    if (myKey != NULL && (String)myKey != "*" && (String)myKey != "#") {
      Serial.print("Key pressed: ");
      Serial.println(myKey);
      idNumber += (String)myKey;
      setLCD(idNumber, 1);
    } else if ((String)myKey == "*" && idNumber.length() > 0) {
      idNumber = idNumber.substring(0, idNumber.length() - 1);
      setLCD("                ", 1);
      setLCD(idNumber, 1);
    } else if ((String)myKey == "#") {
      setLCD("                ", 0);
      setLCD("                ", 1);
      setLCD(" Checking in... ", 0);
      checkIn();
    }
  }
}

void setLCD(String text, int line) {
  lcd.setBacklight(HIGH);
  lcd.setCursor(0, line);
  lcd.print(text);
}

void checkIn() {
  checkingIn = true;
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    setLCD("                ", 1);
    setLCD("    Failed!     ", 0);
    return;
  }

  // We now create a URI for the request
  String url = "/assets/api.php?SYSTEM=";
  url += getSystem;
  url += "&API_KEY=";
  url += apiKey;
  url += "&SYSTEM_IDENTIFIER=";
  url += systemIdentifier;
  url += "&ID=";
  url += idNumber;

  // This will send the request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");
  unsigned long timeout = millis();
  while (client.available() == 0) {
    if (millis() - timeout > 1000) {
      setLCD("                ", 1);
      setLCD("    Failed!     ", 0);
      client.stop();
      return;
    }
  }

  // Read all the lines of the reply from server and print them to //Serial
  while (client.available()) {
    String line = client.readStringUntil('\r');
    if (line.indexOf("[response|failed]") > -1) {
      setLCD("Invalid Login...", 0);
      setLCD("                ", 1);
    } else if (line.indexOf("*") > -1) {
      setLCD("Welcome:        ", 0);
      setLCD("                ", 1);
      setLCD(line, 1);
    }
    //Serial.println(line);
  }
  idNumber = "";
  delay(750);
  checkingIn = false;
  setLCD("Please Enter ID#", 0);
  setLCD("                ", 1);
}

Why are you using D4, D5 and D6 for both the lcd and the keypad? That won't work, surely?

Which Arduino is it?

@NickGammon It's IC2, completely different protocol so yes, that works. Also, Wemos D1 WiFi

So just to be clear, D4 and D4_pin are completely different pins? That's kind-of confusing isn't it?

Yes, and because this is not production code, it's not that big of a deal at one point it will be changed but right now it is the way that it is and I understand it. Don't worry about that part. If you don't have any clues to what the issue is, I don't think it is necessary for you to continue commenting.

I think a minimal, complete, verifiable example would be useful here. It'll be easier for people to understand so you'll attract more help, and very likely you'll figure it out yourself in the process of creating it.

@NickGammon - If the LCD is using I2C then I didn't think it used the other pins designations?

You have three major things here: LCD, keypad, WiFi. Possibly they are interacting with each other (for example, sharing the same pin by accident). If that was the case displaying something on the LCD might change how the keypad is configured. If you think the problem is simply the keypad, make up a small example that tests that theory out. Then add in the LCD stuff. Finally add in the WiFi stuff.

if (myKey != NULL && (String)myKey != "*" && (String)myKey != "#") - this is using the String class quite unnecessarily here. That does dynamic memory allocation and you may eventually get heap fragmentation. Why not: if (myKey != 0 && myKey != '*' && myKey != '#') ?


text:
Emergency Vehicle - Make two LEDs flash with buttons and a passive buzzer change sound
My Dad and I are just learning how to use my new UNO.
We have learned how to make leds flash at the touch of a button. We have also learned how to make a passive buzzer sound at the touch of a button and change tone to sound like a police car.
We have just learned that we cant run more than one loop so we have combined the buzzer code and the LED code twice (for blue and red LEDs) and it works... but the delay on the LEDs is ruining the buzzer sound. Is there anything we can do?
The code is below.
Thank you!
Code:
int buzzerPin = 9;    // the number of the buzzer pin
int BlueLEDpin = 5;   // the number of the blue LED pin
int RedLEDpin = 7;    // the number of the Red LED pin
float sinVal;         // Define a variable to save sine value for buzzer
int toneVal;          // Define a variable to save sound frequency for buzzer

void setup() {
  pinMode(buzzerPin, OUTPUT); // Set Buzzer pin to output mode
  pinMode(BlueLEDpin, OUTPUT); // Set Blue LED pin to output mode
  pinMode(RedLEDpin, OUTPUT); // Set Red LED pin to output mode
}

void loop() {
    Buzzer();
    BlueLED();
    RedLED();

}

void Buzzer() {
  for (int x = 0; x < 360; x++) {       // X from 0 degree->360 degree
    sinVal = sin(x * (PI / 180));       // Calculate the sine of x
    toneVal = 2000 + sinVal * 500;      // Calculate sound frequency according to the sine of x
    tone(buzzerPin, toneVal);           // Output sound frequency to buzzerPin
    delay(1);
  }

 }

  void BlueLED() {
  digitalWrite(5, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1);              // wait for a second
  digitalWrite(5, LOW);    // turn the LED off by making the voltage LOW
  delay(1);              // wait for a second
}

void RedLED() {
  digitalWrite(7, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1);              // wait for a second
  digitalWrite(7, LOW);    // turn the LED off by making the voltage LOW
  delay(1);              // wait for a second
}

+1 for nicely formatted code ... would give you another, if i could, for keeping comments and code separate ... code that is joy to look at

Wow, thanks. We are feeling very proud right now.

We made it better with Nathan's pointer.
We learned how to make a class but the LEDs flashed together so we learned how to make another class (with Public and Void Update in the class - caught us out at first that bit). One class starts with state HIGH and the other with state LOW so the LEDs alternate. When we press all three buttons we get the two tone buzzer, and the alternating LEDs.
Using this method we can add as many new LEDs as we like.
Here is the code we wrote:
/*
  Jacob & Dad’s Police Car light and sounds
*/

int buzzerPin = 9;
float sinVal;
int toneVal;

class FlashingLED_A
{
    int ledPin;
    long OnTime;
    long OffTime;
    int ledState;
    unsigned long previousMillis;
  public:
  FlashingLED_A(int pin, long on, long off)
  {
    ledPin = pin;
    pinMode(ledPin, OUTPUT);
    OnTime = on;
    OffTime = off;
    ledState = LOW;
    previousMillis = 0;
  }

 void Update()
  {
    // check to see if it's time to change the state of the LED
    unsigned long currentMillis = millis();

    if((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
    {
        ledState = LOW;  // Turn it off
      previousMillis = currentMillis;  // Remember the time
      digitalWrite(ledPin, ledState);  // Update the actual LED
    }
    else if ((ledState == LOW) && (currentMillis - previousMillis >= OffTime))
    {
      ledState = HIGH;  // turn it on
      previousMillis = currentMillis;
      digitalWrite(ledPin, ledState);
    }
  }

};

class FlashingLED_B
{
    int ledPin;
    long OnTime;
    long OffTime;
    int ledState;
    unsigned long previousMillis;
  public:
  FlashingLED_B(int pin, long on, long off)
  {
    ledPin = pin;
    pinMode(ledPin, OUTPUT);
    OnTime = on;
    OffTime = off;
    ledState = HIGH;
    previousMillis = 0;
  }

 void Update()
  {
    // check to see if it's time to change the state of the LED
    unsigned long currentMillis = millis();

    if((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
    {
        ledState = LOW;  // Turn it off
      previousMillis = currentMillis;  // Remember the time
      digitalWrite(ledPin, ledState);  // Update the actual LED
    }
    else if ((ledState == LOW) && (currentMillis - previousMillis >= OffTime))
    {
      ledState = HIGH;  // turn it on
      previousMillis = currentMillis;
      digitalWrite(ledPin, ledState);
    }
  }

};

FlashingLED_A led1(5, 100, 400);
FlashingLED_B led2(7, 100, 400);

void setup() {
  pinMode(buzzerPin, OUTPUT);
}

void loop() {
  Buzzer();
    led1.Update();
    led2.Update();
}

void Buzzer() {
  for (int x = 0; x < 360; x++) {
    sinVal = sin(x * (PI / 180));
    toneVal = 2000 + sinVal * 500;
    tone(buzzerPin, toneVal);
    delay(1);
  }
 }

Is the only difference between FlashingLED_A and FlashingLED_B the fact that A starts LOW and B starts HIGH?  If so then I would add an extra parameter to the class constructor and just use one of the classes.

Your problem is the delay() in your BlueLED() and RedLED() calls. To get more "simultaneous" activities, you'd need to use timer interrupts to implement those delays. It's a lot more complex conceptually, but the right way to do it.

Thanks very much Harper; that was very helpful. We followed your advice and have just solved it!!! Thanks!

That was quick work! Glad you got it going.

We have done it. Thanks for the help Harper Shelby.
We combined the Blink Without Delay example with our original code:
int buzzerPin = 9;    // the number of the buzzer pin
const int BlueLEDpin = 5;
const int RedLEDpin = 7;
float sinVal;         // Define a variable to save sine value
int toneVal;          // Define a variable to save sound frequency
int BlueLEDState = LOW;
int RedLEDState = HIGH;
unsigned long previousMillisBlue= 0;
unsigned long previousMillisRed= 0;
const long interval = 200;

void setup() {
  pinMode(buzzerPin, OUTPUT); // Set Buzzer pin to output mode
  pinMode(BlueLEDpin, OUTPUT);
  pinMode(RedLEDpin, OUTPUT);
}

void loop() {
    Buzzer();
    BlueLED();
    RedLED();

}

void Buzzer() {
  for (int x = 0; x < 360; x++) {       // X from 0 degree->360 degree
    sinVal = sin(x * (PI / 180));       // Calculate the sine of x
    toneVal = 2000 + sinVal * 500;      // Calculate sound frequency according to the sine of x
    tone(buzzerPin, toneVal);           // Output sound frequency to buzzerPin
    delay(1);
  }

 }

  void BlueLED() {
  unsigned long currentMillisBlue = millis();

  if (currentMillisBlue - previousMillisBlue >= interval) {
    previousMillisBlue = currentMillisBlue;
    if (BlueLEDState == LOW) {
      BlueLEDState = HIGH;
    } else {
      BlueLEDState = LOW;
    }

    digitalWrite(BlueLEDpin, BlueLEDState);
  }

}

void RedLED() {
  unsigned long currentMillisRed = millis();

  if (currentMillisRed - previousMillisRed >= interval) {
    previousMillisRed = currentMillisRed;
    if (RedLEDState == LOW) {
      RedLEDState = HIGH;
    } else {
      RedLEDState = LOW;
    }

    digitalWrite(RedLEDpin, RedLEDState);
  }

}

Firstly, congratulations! you've taken your first step into the very rewarding world of micro-controllers. I teach robotics at a local university, so it's always nice to see when the light-bulb goes on and people start understanding.
As mentioned above, the blink without delay code is a good start. Good code should also be expandable in case later you want to add another light or 10, and this is where coding every line can get very large. There are many other methods for doing this sort of task, however you might want to have a look at this series of tutorials. Multitasking with the Arduino.
The benefit to the state machine approach used in that example is it becomes very easy later on to change your code; if you want to have more lights flashing in sequence (like the knight-rider lights) or more sirens, it becomes easier to include. In your second code, the void redLED() and void blueLED() codes contain mostly the same lines; you could make an object called 'LED' and then just make as many instances of this as you need, all working at different speeds and different pins (the example on the website should provide this much. The buzzer can probably reuse the servo sweep part of the code). You could also for example, program 4 different types of siren as a switch:case, and after the elapsed time, switch between them.
Another more advanced method would be to include a real-time operating system. An RTOS makes it very easy to have multiple independent tasks running. Each light could be on its own task and the siren on a third, and the system would keep each working, effectively simultaneously. This approach then has advantages if you want to change the timing of one light; it gets changed in one place without fear of needing to change the whole code. Information on FreeRTOS on the arduino can be found here. There is an example at the bottom of the page which includes both Blink and analog read examples.
These are fairly advanced topics, but I think you and your dad will get there. Once again, congratulations.

Thank you very much Nathan! We will look in to this next, and the website link you gave us looks great.

This is probably a bit advanced but...
You could use a base class and pointers to the derived LED and Buzzer classes to reduce you loop function to a loop.  You won't gain much at this level, but as you add more objects, such as the flashing headlights and mirror lights, maybe even a rear facing message board you will make life easier for your self.
/*
Jacob & Dad’s Police Car light and sounds
*/

class BaseOutputObject
{
protected:
    int Pin;
public:
    BaseOutputObject(const int& pin)
        : Pin(pin)
    {
        pinMode(Pin, OUTPUT);
    }
    virtual void Update()
    {
    }
};

class FlashingLED : public BaseOutputObject
{
    long OnTime;
    long OffTime;
    int ledState;
    unsigned long previousMillis;
public:
    FlashingLED(const int& pin, const long& on, const long& off, const bool& startLow = true)
        : BaseOutputObject(pin)                     // Call base class constructor
        , OnTime(on)                            // Use initialisers rather than assignments
        , OffTime(off)
        , ledState(startLow ? LOW : HIGH)
        , previousMillis(0)
    {
    }

    void Update()
    {
        // check to see if it's time to change the state of the LED
        const unsigned long currentMillis = millis();           // Make it const because it won't change within this call of the function.

        if (currentMillis - previousMillis >= OnTime)
        {
            ledState = (ledState == LOW ? HIGH : LOW);  // Toggle the state.
            previousMillis = currentMillis;  // Remember the time
            digitalWrite(Pin, ledState);  // Update the actual LED
        }
    }
};

class Buzzer : public BaseOutputObject
{
    float SinValue;
    int ToneValue;
public:
    Buzzer(const int& pin)
        : BaseOutputObject(pin)
        , SinValue(0.0f)        // Always initialise variables, in case you change the code later.
        , ToneValue(0)
    {
    }

    void Update()
    {
        for (int x = 0; x < 360; x++)
        {
            SinValue = sin(x * (PI / 180));
            ToneValue = 2000 + SinValue * 500;
            tone(Pin, ToneValue);
            delay(1);
        }
    }

};

// The objects could be declared dynamically, but thats not a great idea on embedded systems.
FlashingLED ledOne(5, 100, 400);
FlashingLED ledTwo(7, 100, 400);
Buzzer buzzer(9);
enum { LED_ONE, LED_TWO, BUZZER, MaxObjects };
// Have to have pointers to the objects to allow you to cast them down to the base objects.
BaseOutputObject* objects[MaxObjects] = {  &ledOne, &ledTwo, &buzzer};

void setup()
{
}

void loop()
{
    for (int index = 0; index < MaxObjects; ++index)
    {
        objects[index]->Update();
    }
}


text:
Segmentation fault at Serial.begin()
I try to communicate with my Arduino clone (Elegoo Uno R3) from Arduino IDE (v1.8.4 installed by dnf from repos) at Fedora 27. Compiling and upload of normal example code works well. However, as I try to start any serial communication (e.g. for debug), the compiler fails returning following segfault:
"/usr/bin/avr-gcc"  -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p  -o "/tmp/arduino_build_407070/AnalogReadSerial.ino.elf" "/tmp/arduino_build_407070/sketch/AnalogReadSerial.ino.cpp.o" "/tmp/arduino_build_407070/../arduino_cache_983152/core/core_arduino_avr_uno_1621df717313d057c92202babd71649a.a" "-L/tmp/arduino_build_407070" -lm
lto1: internal compiler error: Segmentation fault
Please submit a full bug report,
with preprocessed source if appropriate.
See <https://bugzilla.redhat.com/> for instructions.
lto-wrapper: fatal error: /usr/bin/avr-gcc returned 1 exit status
compilation terminated.
/usr/lib/gcc/avr/6.3.0/../../../../avr/bin/ld: error: lto-wrapper failed
collect2: error: ld returned 1 exit status
exit status 1
Error compiling for board Arduino/Genuino Uno.

I found similar issue here https://github.com/sudar/Arduino-Makefile/issues/486 However, that solution deals with Arduino-Makefile software that is little bit complex for me.
I would appreciate any help either how to solve the segfault itself, or how to easily use Arduino-Makefile (I would like to compile from Arduino IDE or any user-friendly IDE).

What IDE version are you running? And how did you install it?

How did avr-gcc find its way into /usr/bin?  How exactly have you installed Arduino?  Are you intentionally using an avr-gcc different than the one packaged with it, or is that an accidental case of a system version overriding Arduino's?

Edited the question - version 1.8.4, installed from repos. I didn't setup any magic with avr-gcc - I did not change anything.

@ChrisStratton which arduino provided /usr/bin/arduino, then find /usr/bin/arduino -name avr-gcc did not output anything. ls -l /usr/bin/avr-gcc gives -rwxr-xr-x. 2 root root 830016 Aug  2 20:40 /usr/bin/avr-gcc and /usr/bin/avr-gcc --versiongivesavr-gcc (Fedora 6.3.0-3.fc27) 6.3.0`

@ChrisStratton I installed using sudo dnf install arduino. The blink works as it should. I also tested a switch and it works as well. Is it possible to download the binary and run it along the redhat version?

Do not install from repos. Download the official tarball from Arduino.

If you install the download in a unique path, probably, but safer to remove the redhat version with their package manager.  This looks to be the same as the bug the Arduino-Makefile project is talking about, applying to at least the fedora type avr-gcc package over a wide range of versions.  You might be able to fix it if you can get the IDE to add the build flag they discuss, but simpler just to use the working download from Arduino unless you particularly want to avoid that.

Thanks for help! The official Arduino binaries did the trick :) Could you please transform the comment into an answer as I could then upvote and accept it? Thanks a lot.

There's a new version of the avr-gcc package that's currently available in the updates-testing repo that should fix the problem. You can install/update it by enabling the updates-testing repo, or grabbing the rpm from koji (https://koji.fedoraproject.org/koji/buildinfo?buildID=1013122)


text:
How to add additional sensors [Arduino]
I am new to Arduino.
I have currently connected a FSR sensor to the TOUT pin of ESP WROOM-02.
How do I add additional FSR sensor to ESP WROOM-02?

TOUT: it can be used to test the power-supply voltage of VDD3P3 (Pin3 and Pin4) and the input power voltage of TOUT (Pin6). These two functions cannot be used simultaneously. Why did you connect a FSR sensor to TOUT?

An FSR (Force Sensing Resistor) varies in resistance as force or pressure is applied.  Most often such devices are connected to the positive power rail and the ADC input of a embedded micro controller.  At the same time a second known fixed resistor is connected to the opposite power rail (ground) and the same ADC input.  This forms a resistor divider network where the ADC in the embedded micro controller can measure the force applied to the FSR by measuring the voltage of the resistor divider.
To measure 2 or more FSRs using the same ADC input, consider connecting one lead of each FSR to a digital input/output pin of the embedded micro controller. Then connecting the other lead of each FSR to the ADC input.  To measure the force on the 1st FSR, configure the connected digital pin as a high ouput using software.  So that all the other FSRs do not influence the measurement, configure all the other digital pins to have high impedance.  Often this can be done by programming these other digital pins as inputs.  Cycle through all FSRs in a similar fashion using software.


text:
Multiple LED on arduino
I am currently trying to control multiple LEDs with one Arduino Mega 2560 board. However, since each LED needs 3.6 volts and the board only supplies 5V I cannot make more than one light up.
Is there a way to increase to output voltage of the Arduino board ? Or perhaps of using arduino to turn on or off a battery that has a high enough voltage to power multiple LED ?
Thanks for your help

please explain why you think that you can only light up one LED with the Arduino.

Connect the LED in parallel, not in serie!

Each pin on any Arduino (with some exceptions) can only handle 40mA MAX. Even the 5V and similar output sources can't handle more than 600mA, So I suggest you use them to power a MOSFET or Darlington to connect them in appropriate series and parallel connection counts.
Both the above transistors can handle high voltage, but you need to choose ones that correspond to a voltage that an Arduino can provide.
This is the most robust method if you want all the LEDs to light up at the same time. However for array addressable LEDs you might need extra BJTs coupled with resistors for each led, maybe along with two decided that would be appropriate for your application.

If you connect them in parallel instead of series you'll be able to turn them on and off with 3.6 volts (5 volts through an appropriate dropping resistor), assuming the Arduino can supply the current. Here's a general explanation of the difference.

yes I had actually tried in parallel and it had not worked but today I figured out that one wire had a problem. It all works now thanks