text:
How to get a feedback that something connected to an Arduino is working?
Assume you have an Arduino Uno board, the board is connected to some sensors, maybe a stepper motor or something, it does not matter.
How to get feedback or diagnostics or something that all the things are working, or if not then get feedback that are not working?

It all depends on what the devices are and how they work. As an example, you could add current shunts to the motor connections and sense the current flowing through the motor.

with sensors you can check if the values are in expected range

moving parts can be checked with optical or electromagnetic sensors

there is nothing special for Arduino. it is common design of a system

OP asked how to provide feedback that there is or isn't a problem, not how to diagnose one. That's pretty straightforward, and I'd be happy to offer an answer if this were re-opened. Voting to do so....

Thank you all for the comments , have a ncie day , i think i got it :D

There is no general mean of error detection in microcontrollers, so also not for an Arduino. Problems can occur at many points, extremely depending on how your project works. Think about a sensor, that is connected over some network bus; the sensor itself may fail, but also the network bus, so that you are not able to connect to the sensor anymore. Also the Arduino has no possibility to report errors to you, that you didn't anticipated in your sketch (like the log files on a PC would do). So there is not one answer for it. Here are some possibilities (some of them already described in previous answers):

Check the output of library functions for error messages. Many (but not all) libraries return status codes from their important functions. For example: The Wire.endTransmission() function will return a status code, with which you can determine, if the transmission succeded and what might have gone wrong.
Check sensors for expected values. If the values go out of range (for example a temperature of -20°C where you would expect room temperature) you can be pretty sure, that something is wrong with the sensor (assuming it worked properly before).
Add sensors to your project, to sense, if it is working as expected, and program the Arduino to do the corresponding actions on failure (for example an alarm)

The first two options are simple, the third can get very complex and expensive and is normally only used, if the project really demands sensing malfunction electronically (like for a robot, that could hurt humans, when moving in the wrong direction).

To expand on Juraj's answers, tackle this question from the user's point of view. What does all things are working mean for them? Does the temperature you read from a sensor have to be within .2C of a reference value? The stepper has to move a thing from defined positions A to B?
Based on the answers to questions like this, which is sort of a black-box testing approach, think about how to obtain reference values, then write tests in your Arduino to check if they are met. You might have to move your system into a defined testing stage first, like move the steppers to a defined starting point, then go test.


text:
Collecting data from a timer interrupt and storing it into an array
My question is: how can I use an ISR and store the data I get from my analog inputs into an array for easier data analysis.
More specifically, I want to collect my data using an ISR function (internal timer interrupt), then store the collected data into an array. This way I can analyze the data more easily.
I have posted the code below. I have posted code showing how I implemented my ISR without storing the data into an array. I was wondering I anyone could help me out with this (how to store that data into an array). Thank you.
const int A0_pin = PC0;
const int A1_pin = PC1;

const uint16_t t1_load = 0;
const uint16_t t1_comp = 3173;

float count = 0;
float num = 0;

void setup() {

  //Set A0 and A1 pins as inputs
  DDRC &= ~(1 << A0_pin);
  DDRC &= ~(1 << A1_pin);

  //Reset Timer1 Control Reg A
  TCCR1A = 0;

  //Set CTC mode
  TCCR1B &= ~(1 << WGM13);
  TCCR1B |= (1 << WGM12);

  //Set to prescaler of 256
  TCCR1B |= (1 << CS12);
  TCCR1B &= ~(1 << CS11);
  TCCR1B &= ~(1 << CS10);

  //Reset Timer1 and set compare value
  TCNT1 = t1_load;
  OCR1A = t1_comp;

  //Enable Timer1 compare interrupt
  TIMSK1 = (1 << OCIE1A);

  //Enable global interrupt
  sei();

  Serial.begin(9600);
  Serial.println("CLEARDATA"); //clears up any data left from previous projects
  Serial.println("LABEL,TIME,TIMER,AVG,GAUGE0, GUAGE1"); //always write LABEL, so excel knows the next things will be the names of the columns
  Serial.println("RESETTIMER"); //resets timer to 0
}

void loop() {
}

ISR(TIMER1_COMPA_vect) {
  TCNT1 = t1_load;
  float Gauge0 = analogRead(A0_pin);
  float Gauge1 = analogRead(A1_pin); //44

  //conversion of read data, to voltage range (0-100 percentVolts)
  float gauge0 = Gauge0 * (100.0 / 1023.0);
  float gauge1 = Gauge1 * (100.0 / 1023.0);
  float add = gauge0 + gauge1;
  float AVG = ((gauge0 + gauge1) / 2);

  Serial.print("DATA,TIME,TIMER,");
  Serial.print(add);
  Serial.print(",");
  Serial.print(gauge0);
  Serial.print(",");
  Serial.println(gauge1);
}

In the code, I want to store the gauge1 and the gauge0 values into an array essentially.

How many interrupts/second do you expect? Using Serial.print() in the interrupt routine is introducing a significant performance penalty, especially since you've set the communication speed to only 9600 baud.

Storing the data into arrays is not an end in itself. The question is:
what do you want to do with these arrays? The way to proceed depends on
that purpose.
If you want the data acquisition (analogRead()) and the processing
(computation and printing) to proceed in parallel, then you will need
the arrays for buffering the data between those two processes. As
mentioned by Michel Keijzers in his answer, you will have to research
the concept of ring buffer.
There is a ring buffer implementation in the Arduino core you can use as
inspiration: when reading data from the Serial port, the incoming bytes
are received by an ISR and stored in a ring buffer. The
Serial.read() method can then be used to retrieve these bytes
and process them outside the interrupt context.
Another option is to alternate between an acquisition phase and a
processing phase. This can be an interesting approach if the acquisition
rate is too fast for the processing to be performed in real time. In
this case, you do not need a ring buffer. Instead, you have the ISR fill
the arrays and, when they are full, the main program can take on and
start the processing. For coordinating these jobs, you just need a
boolean to keep track of whether you are performing the acquisition
phase or the processing phase. Note that, since accessing a boolean is
an atomic operation, you do not need to disable interrupts for this.
Here is an example implementation of this strategy. The variable
sampling_done is used to coordinate the two processes:
const size_t sample_count = 256;

volatile int gauge0[sample_count];
volatile int gauge1[sample_count];
volatile bool sampling_done = false;

ISR(TIMER1_COMPA_vect) {
    if (sampling_done) return;  // nothing to do

    static size_t sample_idx = 0;
    gauge0[sample_idx] = analogRead(A0);
    gauge1[sample_idx] = analogRead(A1);
    if (++sample_idx >= sample_count) {
        sample_idx = 0;  // prepare for next round
        sampling_done = true;
    }
}

void process_samples(int Gauge0, int Gauge1) {
    // Whatever needs to be done with the samples:
    // computation, printing...
}

void loop() {
    if (sampling_done) {
        for (size_t i = 0; i < sample_count; i++) {
            process_samples(gauge0[i], gauge1[i]);
        }
        sampling_done = false;  // start next sampling round
    }
}

Now some random remarks:

There is no need to sei() in setup(): interrupts have already been
enabled by the Arduino core initialization.

Do not reset TCNT1 within the ISR: this is handled automatically by
the CTC mode. If you do this in software, you risk missing timer
ticks.

Do not store the readings in float variables: they take twice the
memory of an int and all operations on floats are incredibly slow
compared to the equivalent operations on ints.

The scale factor for converting the readings to percent scale is
100.0/1024: the maximum possible analog reading (1023) is one ADC
step below the reference voltage: see the datasheet.

You should remove unused variables as soon as they become unused
(count, num, AVG). Once you do that you should notice you do not
need floats at all.

Thank you for the suggestions. A few side notes: what do you mean by  process_samples(gauge0[i], gauge1[i]);

@DemaGovalla: I mean “do whatever you want with the samples”. See amended answer.

You can create two arrays, e.g.:
#define MAX_LENGTH 20

volatile float _gauge0[MAX_LENGTH];
volatile float _gauge1[MAX_LENGTH];

volatile int _filled = 0;

The _filled value shows that _gauge0 is filled from 0 upto (excluding) _filled.
So when adding two values you use:
_gauge0[_filled] = some value;
_gauge1[_filled] = some_other_value;
_filled++;

After processing, you reset _filled to 0 to refill both arrays again.
Because the Arduino has a limited amount of SRAM it's best to use a fixed array size (20 in this case). You have to make it volatile as it's used from within the ISR.
I'm not sure what you want to do with the data. If you want to gather like 20 (or a fixed amount of values), you can use the above.
If you need a continuous amount of memory and get the last x results, you can better use a so-called ring buffer (search for this, there are many articles about it).
Note that because of the limited amount of SRAM, it might be best not to store calculated values (like average and sum), unless you need the highest performance. This is a tradeoff which I cannot make as I don't know your requirements.
While processing, you use noInterrupts() before and interrupts after the processing of the data, otherwise interrupts will continue during processing. Make sure the handling of the processing takes as less time as possible as you might miss interrupts. Preferably only do the calculations and switch on interrupts before sending results via serial for example.

You would likely need to read _filled when processing the data, so it too should be volatile.

@EdgarBonet Good point, I updated my answer.

My DaquinOscope https://www.daqarta.com/dw_rroo.htm  uses the open-source DaqPort sketch https://www.daqarta.com/dw_rraa.htm to sample in batches, then transfer the data to the host in one high-speed blast.  It takes 1024 total samples, which in your case of 2 channels would be 512 per channel. It stores only the raw data, unscaled... the host is the place for that. The host processes and displays the results in real time. Since this uses a UNO with only 2K RAM, tricky array storage was required to fit in 1024 samples.  In 8-bit mode this is just a 1024-byte array, but for 10-bit it uses a supplemental array of 256 bytes.  On each sample the low byte is stored in the 1024-byte array, and the upper 2 bits are shifted into a 4-sample byte of the 256-byte array.  Feel free to download and use Daqarta for this... no charge for Arduino use. You may want to do this just to work out other issues even if you plan to later use your own host software.  Or you can use Daqarta macros to do whatever you ultimately want.

source: Stack Exchange

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

sort: votes


text:
3.3 V Arduino Pro Mini and nRF24L01 issues
I have a 3.3 V Pro Mini connected to nRF24l01 as xmtr. The nRF24L01 does not respond to the Pro Mini. Any help will be appreciated.
I have attached the print detail output:
Transmitter 2  Started
STATUS       = 0xff RX_DR=1 TX_DS=1 MAX_RT=1 RX_P_NO=7 TX_FULL=1
RX_ADDR_P0-1     = 0xffffffffff 0xffffffffff
RX_ADDR_P2-5     = 0xff 0xff 0xff 0xff
TX_ADDR      = 0xffffffffff
RX_PW_P0-6   = 0xff 0xff 0xff 0xff 0xff 0xff
EN_AA        = 0xff
EN_RXADDR    = 0xff
RF_CH        = 0xff
RF_SETUP     = 0xff
CONFIG       = 0xff
DYNPD/FEATURE    = 0xff 0xff
Data Rate    = 1MBPS
Model        = nRF24L01
CRC Length   = 16 bits
PA Power     = PA_MAX

Transmitter 2 Started
STATUS       = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1     = 0xe8e8f0f0e2 0xc2c2c2c2c2
RX_ADDR_P2-5     = 0xc3 0xc4 0xc5 0xc6
TX_ADDR      = 0xe8e8f0f0e2
RX_PW_P0-6   = 0x20 0x00 0x00 0x00 0x00 0x00
EN_AA        = 0x3f
EN_RXADDR    = 0x03
RF_CH        = 0x73
RF_SETUP     = 0x07
CONFIG       = 0x0e
DYNPD/FEATURE    = 0x03 0x06
Data Rate    = 1MBPS
Model        = nRF24L01+
CRC Length   = 16 bits
PA Power     = PA_MAX
voltage = 3.97 V
0
RSLT (1 = success) 0
Data Sent 3.00  0.00  3.97
voltage = 3.85 V
voltage = 3.79 V
voltage = 3.75 V
voltage = 3.73 V
0
RSLT (1 = success) 0
Data Sent 3.00  0.00  3.73
voltage = 3.70 V
voltage = 3.68 V
voltage = 3.65 V
voltage = 3.62 V
0
RSLT (1 = success) 0
Data Sent 3.00  0.00  3.62
voltage = 3.58 V
voltage = 3.54 V
voltage = 3.50 V
voltage = 3.45 V
0

The top transmitter output is before I changed the nRF24L01 module which appeared to be bad.
The second transmitter started output. Module is good but nRF24L01 would not connect to receiver with 3.3 V Pro Mini. It connects if I use a Nano.

Transmitter 2 is not connected properly. Unwire and rewire it.

voltage = 3.97 V 0 RSLT (1 = success) 0 Data Sent 3.00 0.00

nrf24l01 is a 3.3V device, Where'd that come from?

LM317T set to 3.25 Volts and 220uF tantalum on the nrf24L01.
Pro mini and nrf24L01 powered by 3.25V works a treat. :-)
Problem with arduino nano is that the USB from laptop is 5V and that is a killer for the nrf24L01!
If using serial.write to send data to a serial monitor through the nano's USB insure that the power and levels are not 5V on the nrf24L01.

Promini 3.3V regulator is also only good for 150mA. I think the nrf24L01 needs more current than that.

Only the high-power version needs more current. What matters is stable voltage but this guy has wiring issues.

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


text:
Wake up from sleep from pressed button?
#include <avr/sleep.h>
#include <avr/power.h>
//This sketch is a metronome, in which each led pin shows one beat.

const int speaker = 13;  //speaker at pin 13
int ts = 6;  //highest led pin
int count = 3;  //"beat 1 pin"
const int keyPin = 11;  //button to change time signature
const int keyPinR = 10;  //button to change rhythm
const int keySwitch = 2;  //sleep mode/wake up button

//All pins below use a pull-up resistor, so the states are inverted
int buttonState = LOW;
int buttonState2 = LOW;
int switchState = LOW;
int silentState = LOW;

int bpm = 120;  //you do not need to know this,
//it's just a variable for the potentiometer to change the tempo

int rthm = 1;  //rhythm
volatile int pressed = 0;
long silent = p;

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

   for(int thisPin = 3;thisPin <= ts;thisPin++)
   {
      pinMode(thisPin,OUTPUT); //initialize thisPin as an output
      pinMode(8, INPUT); //potentialmeter for changing temp
      //Pin 9 to 11, along with pin 2, are all push buttons with pull-up     resistors
      for(int i = 9; i<=11; i++)
      {
         pinMode(i, INPUT);
         digitalWrite(i, HIGH);
      }
         pinMode(2, INPUT);
         digitalWrite(2,HIGH);
   }
}

void loop()
{
   turnOn();
}

void turnOn()
{
    buttonState = digitalRead(keyPin);//key for
    buttonState2 = digitalRead(keyPinR);
    switchState = digitalRead(keySwitch);
    silentState = digitalRead(9);
    //Serial.println(switchState);
    if(switchState==LOW&&pressed==0)
    {
       sleep_enable();
       set_sleep_mode(SLEEP_MODE_PWR_DOWN);
       attachInterrupt(digitalPinToInterrupt(0), interrupt, LOW);
       sleep_cpu();
       //Serial.println(switchState);
    }
    else {
       //The beat starts at pin 3, runs in consecutive pins,
       //and ends at pin 8 at maximum
       if(buttonState==LOW)
       {  //changing time signature - up to 5 beats
           ts++;
           if(ts==8)
           {
              ts = 3;
              //8 - 3 = 5 beats max
           }
        }
        if(buttonState2==LOW)
        {  //changing rhythm - quarter note to eighth, then
          //triplets and sixteenths, back to quarter notes
          rthm++;
          if(rthm==5)
          rthm = 1;
 }

    if(silentState==LOW){//if silent key pressed, go to silence (only LED's showing)
    silent++;
  }

  //The RUN code
  for(int thisPin = 3;thisPin <= ts;thisPin++)
  //LED's blinking beats (thisPin - LED pin (beat number + 2))
 {

 for(int r = 1; r<=rthm; r++)
 {//nested loop for the rhythm
   bpm = pulseIn(8, HIGH);//pin 8 - tempo potentialmeter
   digitalWrite(thisPin,HIGH);//each LED blinks

   pinMode(13,OUTPUT); //pin 13 - speaker

   if(silent%2==0)//Press once, tone, press again, no tone
     noTone(13);
 else
 if(count == 3&&r==1). //first beat is higher
 tone(13,4400,80);
 else if(r==1). //downbeats slightly lower
 tone(13,2500,80);
 else
 tone(13,2200,60);  //off beats even lower
 delay((bpm-52)/rthm);
 digitalWrite(thisPin,LOW);  //turn each off as we proceed to the next beat (LED)
 pinMode(13,INPUT);  //speaker input
}
count++;  //beat++

if(count >ts){//go back to count
count = 3;
}

   }
  }
 }

void noSound()//silence the speaker
{
  noTone(13);
}

void interrupt()//this is where the sleep interrupt starts -               //how can i press it to wake up???
{
    sleep_disable();
    detachInterrupt(0);
    if(switchState==HIGH){
       pressed = 1;
       Serial.println(switchState);
       turnOn(); //go back to the main functional method (?????)
     }
 }

Once the keySwitch button is pressed (pin 2), the arduino goes to sleep; however, the only way to turn it on is by resetting everything. How can I just wake up the Arduino, keeping every state as before the sleep interrupt?

attachInterrupt(digitalPinToInterrupt(0), interrupt, LOW);

should be either
attachInterrupt(0, interrupt, LOW);

or
attachInterrupt(digitalPinToInterrupt(2), interrupt, LOW);

As pin 0 is not an interrupt pin. Also the button is connected to pin 2, not pin 0. digitalPinToInterrupt(0) would actually return -1.

It would be a lot more useful if you explained your apparent theory that the wrong pin is being monitored rather than just proposing an unexplained change to the code.

@ChrisStratton thanks for the suggestion. MikeZhou; you are welcome.

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


text:
Arduino not in sync unique error

When I try uploading to my Arduino/Genuino UNO I get the following not in sync error with "unique" resp(resp=0X54) or (resp=0X81) please solve ... I have to submit my project tommorow......

error message:
  avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x54
  avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x54
  avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x54
  avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x54
  avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x54
  avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x54
  avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x54
  avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x54
  avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x54
  avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x54
  Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

[![enter image description here][2]][2]

I think this is more likely to get an accurate answer on the stackexchange Arduino forum. So would you ask it there? Have you tried something much simpler, like uploading the 'Blink' example?

Are you able to compile code? Are you using arduino board? If yes, disconnect external circuitry and try uploading the code. If it works, re-check your external circuit. If it doesn't, replace your arduino. If you are not using arduino board, let us know. Also, it's always a good idea to show us the circuit/ schematic etc. Help us help you.

Have you previously successfully loaded a program using this same computer and same Arduino? Is it possible that the software has changed since then? Have you access to a 2nd Arduino or 2nd computer? Is this computer in a classroom? Please post the whole text of the new error message.

NOTE
That schematic shows you are trying to power the motors from the Arduino's 5V power supply. That is a 'bad idea' unless they are good quality, low-current, motors.
The electrical noise from the motors may cause the Arduino to reset, and run the same program from the beginning until it reaches the part where the motor's electrical noise resets it.
Worse, current drawn if the motors stall may damage the Arduino's power supply. The Arduino's voltage regulator is supposed to protect itself from damage, but it doesn't always succeed. This is rare, but I have had students break it.
I have elevated this comment to an answer to warn other people against trying to use the schematic in the question.

uare a genius .. after 2 hours of research, i found that my arduino is bricked and the bootloader is curropt. i ave to buy avr usbasp cuz that is the cheapest . to reupload the bootloader ........thanks ...........................

It is possible to get the same chip working if you try re uploading the bootloader to it. I have seen it in a few cases. Use the arduino bootloader burning guide to do so.

@AnirudhRaghavanS - if you already have access to another Arduino, you can use that to reload the bootloader.

@gbulmer  i dont have another arduino so the cheapest programmer in the the market is avr usbasp which costs around 3 dollars , so i am thinking of buying that stuff, anyway thanks

@whickeyjack i dont have another arduino so the cheapest programmer in the the market is avr usbasp which costs around 3 dollars , so i am thinking of buying that stuff, anyway thanks – Anirudh Raghavan S just now

@gbulmer and whiskeyjack\ , please give me your facebook id, i want to have you as a guide for my arduino project

You have a BT module attached to Arduino Tx Rx pins. That's the culprit. Disconnect anything from Tx and Rx pins of arduino while uploading code. Once the code has been uploaded, re-connect the BT module.
Edit:
Since this didn't solve your problem, you need to pin point the issue. If you have removed everything from Arduino and still not able to upload the code - either your drivers are not up to date or your arduino is faulty.
Test the arduino:
Try uploading blinky sketch. Didn't succeed? Restart arduino IDE and try again. Didn't succeed? Restart PC and try again. Didn't succeed? Re install arduino and try again? Didn't succeed? Try on a friend's PC? No luck? Arduino is faulty.
Note: This answer is for the exact schematic you have given. If you have done something else, there might be other reasons why you are not able to upload the code. Post a real picture of what exactly you are doing and we might be able to help you further.

Yup. You beat me to it, but that's all I would have written too. +1

So you get the same error with ALL wires disconnected except for the USB lead? Are you SURE you have selected the correct board and port? If you have. I would disconnect the Arduino from the USB port, reboot the PC, and try loading Blink. It is possible (but unusual) that you have damaged the Arduino's Rx or Tx pin or the USB-to-UART's pins.

@gbulmer - What sorcery is this? Are you a mind reader or something? :)

@Whiskeyjack - I teach Arduino stuff every week to children from 12-16. These incantations become reflexes :-)

Attach the real image. You might be hiding too much useful info by assuming we don't need that to answer your question. For ex - Whether you are using arduino UNO or Arduino Pro mini, whether you bought one or made one using atmega 328.

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


text:
How to monitor a sensor for specific period
As noted in earlier posts, I am building a model railroad crossing gate signal, complete with gate arms, flashers and sound. Although I haven't settled on exactly how I am going to implement detection of the train entering the zone, determining when its completely passed the entry sensor, tripped the exit sensor and completely passed the exit sensor to re-open the gate, I am researching using RFID for this now.
My thought is to have an RFID card in every car of all my rolling stock. Therefore, I want to read all the ID's of the cars as they go buy and for this particular need, always store the latest ID in a variable so that once the whole train has passed by, the last ID in the variable SHOULD be the ID of the last car in the train. I would also have a counter incrementing for each unique ID read so I can use that as a secondary check for the exit routine (check that the exit RFID reader gets the same car count as the entry reader). The exit reader would also match its exitTag to the entryTag from the entry reader.
I am implementing a state machine to control all this functionality but the problem lies in the RFID reading, I need a way to determine when the reader has read all the train cars tags. I thought the easiest way to do this was to use the elapsedMillis library and monitor for some interval where no card was read (two seconds? that would be way more than the time between two train cars) and once met, change state.
That is proving more problematic than I thought. Here is my latest attempt.
I also think it might be better if the tag reading method only returned the last tag ID AFTER ITS DETERMINED NO MORE TAGS TO BE READ so that the code in the case statement is not the code that's running continuously.
Note: I am using the Adafruit RFID shield and Mifare Classic 1k S50 IC 13.56MHz RFID cards.
Any thoughts appreciated
case CrossingZoneState::CROSSINGZONE_RFIDDETECTED:
    if (crossingZoneEntered == true)
    {
        // only thing we do here is monitor and identify the RFID tags of each car to determine last cars tag id
       //well, this doesnt work
        if (timeElapsedBetweenCardReads <= readerInactiveInterval) //only read cards that are continuous, once interval is surpassed change state
        {
            //do all the tag reading in here
            tag = IndentifyTag(entryRFIDReader);
            readCount += 1;

            if (tag != priorTag)
            {
                tagCount += 1;
            }
            priorTag = tag;
            timeElapsedBetweenCardReads = 0;   // reset the counter to 0 so the counting starts over...
        }
        // need to figure out how to determine no more cards are being read and change state and crossingZoneEntered back to false
    }

    if (crossingZoneExited == true)
    {

    }
    break;

IdentifyTags method:
uint32_t IndentifyTag(Adafruit_PN532 rfidReader)
{
    uint8_t tagID[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
    uint8_t tagIDLength; // Length of the UID (4 or 7 bytes depending on ISO14443A card type)
    uint32_t rfidCardID = tagID[0];
    boolean success = rfidReader.readPassiveTargetID(PN532_MIFARE_ISO14443A, &tagID[0], &tagIDLength);
    if (success) {
        // Display some basic information about the card for testing
        Serial.println("Found an ISO14443A card");
        Serial.print("  UID Length: "); Serial.print(tagIDLength, DEC); Serial.println(" bytes");
        Serial.print("  UID Value: "); rfidReader.PrintHex(tagID, tagIDLength);

        if (tagIDLength == 4)
        {
            // Mifare Classic card
            rfidCardID <<= 8;
            rfidCardID |= tagID[1];
            rfidCardID <<= 8;
            rfidCardID |= tagID[2];
            rfidCardID <<= 8;
            rfidCardID |= tagID[3];
            Serial.print("Mifare Classic card #");
            Serial.println(rfidCardID);
        }
        Serial.println("");
    }
    return rfidCardID;
}

Full switch statement:
switch (state)
{
case CrossingZoneState::CROSSINGZONE_CLEAR:
    // only thing we do here is monitor the zone entry sensor
    if (digitalRead(entrySensorPin) == HIGH) {
        crossingZoneEntered = true;
        state = CrossingZoneState::CROSSINGZONE_ACTIVATEGATES;
    }
    break;
case CrossingZoneState::CROSSINGZONE_ACTIVATEGATES:
    // Do these once: turn on the flashers, put down the arms and turn on the crossing gate bells
    if (didOnce = false)
    {
        // turn on flashers
        // turn on sound
        // lower gate arms
        didOnce = true;
        state = CrossingZoneState::CROSSINGZONE_READENTRYRFID;
    }
    break;
case CrossingZoneState::CROSSINGZONE_READENTRYRFID:

    // only thing we do here is monitor and identify the rfid tags of each car to determine last cars tag id
    // need to figure out how to determine no more cards are being read and change state
        if (timeElapsedBetweenCardReads <= readerInactiveInterval) //only read cards that are continuous, once interval is surpassed change state
        {
            //do all the tag reading in here
            entryTag = IndentifyTag(entryRFIDReader);
            readCount += 1;

            if (entryTag != priorTag)
            {
                entryTagCount += 1;
            }
            priorTag = entryTag;
            timeElapsedBetweenCardReads = 0;   // reset the counter to 0 so the counting starts over...
        }
        else {
            //change state now that entry rfid tag reader is finished
            state = CrossingZoneState::CROSSINGZONE_OCCUPIED;
        }

    break;
case CrossingZoneState::CROSSINGZONE_OCCUPIED:
    // only thing we do here is monitor the zone exit sensor
    if (digitalRead(exitSensorPin) == HIGH) {
        state = CrossingZoneState::CROSSINGZONE_READEXITRFID;
    }
    break;
case CrossingZoneState::CROSSINGZONE_READEXITRFID:
    if (timeElapsedBetweenCardReads <= readerInactiveInterval) //only read cards that are continuous, once interval is surpassed change state
    {
        //do all the tag reading in here
        exitTag = IndentifyTag(entryRFIDReader);
        readCount += 1;

        if (exitTag != priorTag)
        {
            exitTagCount += 1;
        }
        priorTag = exitTag;
        timeElapsedBetweenCardReads = 0;   // reset the counter to 0 so the counting starts over...
    }
    else {//check tags and count now that entry rfid tag reader is finished
        if (entryTagCount == exitTagCount && entryTag == exitTag)
        {
            state = CrossingZoneState::CROSSINGZONE_DEACTIVATEGATES;
        }
    }
    break;
case CrossingZoneState::CROSSINGZONE_DEACTIVATEGATES:
    // Do these once: turn off the flashers, raise the arms and turn off the crossing gate bells
    if (didOnce = true)
    {
        // turn off flashers
        // turn off sound
        // raise gate arms
        didOnce = false;
    }
    break;
case CrossingZoneState::CROSSINGZONE_ERROR:
    boolean success = writeToFileOnSD(modelRRErrorLogFile, "ModelRRXingErrorLog.txt", "error string");
    break;
}

What kind of RFID reader and tags are you using? What exactly happens when you try your current code?

I am using the Adafruit RFID shield and Mifare Classic 13.56 Hz cards. @TisteAndii  ... I can read the tags but there a number of problems. 1. I run the train by the reader, (there are three cars with rfid tags) it reads the first tag 3-5 times but doesn't read the rest. I get why it might read a tag more than once as it passes by, and I handle that in IndentifyTags(), but its not reading tags 2 & 3

I thought about using a while loop, i.e. in psudecode while(Im reading tags) {//put the tags in a variable and increment the counter} and once im not reading tags (the elapsedtime is more than the inactive interval) then move on

Provide the whole switch statement. What exactly is crossingZoneEntered and crossingZoneExited? What do they represent in terms of your train's movements? Is this code for the entry reader or the exit reader?

@TisteAndii...Full switch added to original post

It stopped reading the other tags only after you added the IF block in the switch statement? You're sure that the other tags have 4-byte UIDs? If the answer is yes to these questions, then try my answer.

Here is a solution I found on one of the forums, I modified/simplified it to suit, but it does what you are after.
I use a cheap MP3 player and small amp that runs all the time with the speaker output switched by a baby relay controlled by the UNO R3 and IR sensors from Ebay, you should be able to convert this for use on your player.
It runs the 4 steps you described.
code attached.
(could not figure out how to get code into a box-very confusing..please enlighten me,,,,and what is a back tick??)
#include <Servo.h>

Servo gate1servo;// create servo object to control crossing gate 1
//ASSUMPTION Gate is down at position gatedownposition and up at position gateuppostion
Servo gate2servo; // create servo object to control crossing gate 2
unsigned long previousMillisSERVOSTART=0; //FLASH Millis() setup
int intervalSERVOSTART = 1000;
unsigned long previousMillisFLASH=0;  //FLASH Millis() setup
int intervalFLASH = 250;
int gateup  =  120;  // servo position for gate up
int gatedown = 30;
int gatepos; // variable to store the servo gateposition
int gp = 120;  // servo position for gate down
int sensor1 = 5; // IR sensor pin Assumption== Pin goes LOW when train detected
int sensor2 = 6; // IR sensor pin Assumption== Pin goes LOW when train detected
int led1 = 10;  // Led 1 pin first alternating flasher
int led2 = 11;  // Led 2 pin first alternating flasher
int gates_started = 0; // this says if the crossing is active

int entering_sensor = 5; //this will tell which sensor was triggered first
int leaving_sensor = 6; // this will tell which sensor shows train leaving
int flash_state = 0;

void setup() {
   Serial.begin(9600);
  gate1servo.attach(3);// attaches the servo on pin 3 to the servo object
  gate2servo.attach(4);// attaches the servo on pin 4 to the servo object
  gate1servo.write(gp);//start assuming no train
  gate2servo.write(gp);//start assuming no train
  pinMode(sensor1, INPUT);
  pinMode(sensor2, INPUT);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  digitalWrite(led1, LOW);// Start with all flashers off
  digitalWrite(led2, LOW);
}

void loop() {
    if ((digitalRead (sensor1)==LOW)&& (gates_started==0)) {//read sensor 1, if LOW ...do it
        gates_started = 1;
        leaving_sensor = sensor2;
    }
    if ((digitalRead (sensor2)==LOW)&& (gates_started==0)) {//read sensor 2, if LOW ...do it
        gates_started = 1;
        leaving_sensor = sensor1;
    }
    unsigned long currentMillisFLASH = millis();                                                      // get current time stamp, only need one for all if-statements
    if ((unsigned long)(currentMillisFLASH - previousMillisFLASH) >= intervalFLASH) {// time between button presses
       flash_state = ~flash_state;
       digitalWrite(led1, flash_state);                                           //toggle flash_state
      digitalWrite(led2, ~flash_state);
      previousMillisFLASH = currentMillisFLASH;
  }

  unsigned long currentMillisSERVOSTART = millis();                                                     // get current time stamp, only need one for all if-statements
  if ((unsigned long)(currentMillisSERVOSTART - previousMillisSERVOSTART) >= intervalSERVOSTART) {      // time between button presses
    for(gp = gatedown ; gp <= gateup ; gp++) {                                                          // goes from gatedown  degrees to gateup degrees
      gate1servo.write(gp);                                                                             // tell servo to go to gateposition in variable 'gateposition'
      gate2servo.write(gp);

  previousMillisSERVOSTART = currentMillisSERVOSTART;
 }
 Serial.println(gp);
}
}

@Doug...Thanks for this. I edited your code input. All code lines need 4 spaces in from left margin and it will format properly. Ill test this later today or tomorrow.

Your algorithm is the probably the problem. Use this entry case instead:
case CrossingZoneState::CROSSINGZONE_READENTRYRFID:

    entryTag = IndentifyTag(entryRFIDReader);
    if (!entryTag) {   // zero is usually returned if no card is detected
        readCount += 1;   // seems u want to count number of reads

        if (entryTag != priorTag) {
            entryTagCount += 1;
            priorTag = entryTag;  // update priorTag
        }
        timeElapsedBetweenCardReads = 0;   /// reset the counter when u read ANY tag; negate the effects of reading a card more than once

    }
    // only check timeout if you didnt read ANY tag at all
    else if (timeElapsedBetweenCardReads >= readerInactiveInterval){
        //change state now that entry rfid tag reader is finished
        state = CrossingZoneState::CROSSINGZONE_OCCUPIED;
    }

    break;

Something similar for the exit:
case CrossingZoneState::CROSSINGZONE_READEXITRFID:
    exitTag = IndentifyTag(entryRFIDReader);
    if (!exitTag) {   // zero is usually returned if no card is detected
        readCount += 1;   // remember this variable is shared with the other case

        if (exitTag != priorTag) {
            exitTagCount += 1;
            priorTag = exitTag;  // update priorTag
        }
        timeElapsedBetweenCardReads = 0;

    }
    else if ((timeElapsedBetweenCardReads >= readerInactiveInterval) &&
             (entryTagCount == exitTagCount) && (entryTag == exitTag)){
        //change state now that entry rfid tag reader is finished
        state = CrossingZoneState::CROSSINGZONE_DEACTIVATEGATES;
    }
    break;

And in the OCCUPIED case:
case CrossingZoneState::CROSSINGZONE_OCCUPIED:
    // only thing we do here is monitor the zone exit sensor
    if (digitalRead(exitSensorPin) == HIGH) {
        state = CrossingZoneState::CROSSINGZONE_READEXITRFID;
        timeElapsedBetweenCardReads = 0;   // reset the counter to prepare for exit case
        priorTag = 0;  // just in case
    }
    break;

I'm on vacation. I'll test when I return next week. Thanks for the answer.


text:
Creating date string for error log
Well, googling didn't do much to help me here and I'm shocked that something I can do in two lines of code in C#
DateTime dateTime;
string text = dateTime.ToLongDateString();

is this difficult for Arduino, but how do you get a string version of a date time stamp?
I want the current date and time as a string in this format

May 4, 2016 17:15:33

Since I can't use any of the C++ includes, like ctime, I'm not sure how to accomplish this.

I found a great library for this very purpose!  https://github.com/PaulStoffregen/Time

But I can't get any of the examples to work on an Uno

Which examples did you try? What results did you get?

What time do you want to get? The Arduino has no concept of the time, unless you add an RTC module, and then it is down to whatever library the RTC module uses.

I wasn't aware of that. So an additional hardware piece(RTC) is required to capture time? I'll look into that

That's right. The processor chip costs about $US 2. It doesn't include a real-time clock. If it did, how would you set it? And if it did, you would need a battery on the board to keep it powered when you unplug it from the USB/power. There is no battery there.

You need additional hardware like a RTC for example an DS1307 or on the other hand an arduino/shield with ethernet or wifi so you could get the time by NTP another option might be DCF77 time via the air - sorry forgot GPS could also be used to get the time .... the rest then should be simple creating a string.


text:
Proper way to run functions in loop
I am having a problem getting my functions to run properly from the loop.
I am building a model railroad crossing gate and need to run the 4 processes once the sensor signals the train entering the crossing zone. For right now I need to learn how to "function" in C++ running in loop, as I'm a C# ASP.Net guy.
My thought process was in loop to

Check entry sensor, this is all the loop should ever do UNTIL its tripped
Once tripped, run the 4 processes functions (close the gates, turn on the sound, turn on the flashers, power down the road that crosses the tracks)
After the entry sensor is tripped and the processes run (the sound and flashers should operate continuously until the exit sensor is cleared) the exit sensor must be monitored, and once its tripped, its monitored until it goes static again indicating the train has cleared. Then the 4 process are run to shut down the flashers, shut the sound, power up the road and raise the gates.

Right now I'm just trying to get the sound functioning properly. Right now, as the code stands, it plays for a split second then stops. I need that file playing until I call the function to stop it.
Here is the code so far. I've removed the includes and defines for brevity.
// These are the pins used for the music maker shield
#define SHIELD_RESET  -1      // VS1053 reset pin (unused!)
#define SHIELD_CS     7      // VS1053 chip select pin (output)
#define SHIELD_DCS    6      // VS1053 Data/command select pin (output)

// These are common pins between breakout and shield
#define CARDCS 4     // Card chip select pin
// DREQ should be an Int pin, see http://arduino.cc/en/Reference/attachInterrupt
#define DREQ 3       // VS1053 Data request, ideally an Interrupt pin

// create shield-example object
Adafruit_VS1053_FilePlayer musicPlayer = Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

//global variables required
boolean crossingSignalInOperation = false;
boolean signalEntrySensor = false;
boolean signalExitSensor = false;
boolean debugMode = false;

boolean checkEntrySensor() {
    //check entry sensor, if tripped return true otherwise false
    /*if () return true;
    return false;*/
    return true;  //hardcoded for testing
}

void setup() {
    // put your setup code here, to run once:
    Serial.begin(9600);
    debugMode = true;   //set this to false once code is fully operational
    //initialise music maker shield
        if (!musicPlayer.begin()) {
            if (debugMode)
            {
                Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
            }

        while (1);
    }
    // 1st parameter is left, second parameter is right
    musicPlayer.setVolume(20, 20);
    if (debugMode)
    {
        Serial.println(F("VS1053 found"));
    }

    // initialise the SD card
    SD.begin(CARDCS);

    //ensure our global booleans all start false
    crossingSignalInOperation = false;

}

void loop() {
    // put your main code here, to run repeatedly

    signalEntrySensor = checkEntrySensor();
    if (signalEntrySensor == true) {  //only want to catch the FIRST time it senses
        if (crossingSignalInOperation == false)
        {
            //crossing signal is inactive, activate it
            // turn the sound on and return the music player object
            Adafruit_VS1053_FilePlayer mp = onSignalSound(musicPlayer,"trainxng.mp3");

            while (mp.playingMusic) {
                // file is now playing in the 'background' so now's a good time
                // to do something else
                if (!crossingSignalInOperation)
                {
                    crossingSignalInOperation = true;
                    //run the other three processes
                    //offRoadPower();
                    //lowerSignalArms();
                    //startSignalFlashers();

                }
            }
        }
    }
 }

Here are the functions;
Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer mp, const char* fileName) {
    // Play the train crossing sound file
    if (debugMode)
    {
        Serial.println(F("Playing track - "));
        Serial.print(fileName);
    }
    //all sound files are on the micro sd card on the music player shield
    if (!mp.startPlayingFile(fileName)) {
        Serial.println(F("Could not open file "));
        Serial.print(fileName);
        while (1);
    }
    return mp;
}
boolean offSignalSound(Adafruit_VS1053_FilePlayer mp) {
    if (mp.playingMusic)
    {
        mp.stopPlaying();
        return true;
    }
    return true;
}

Any assistance would be appreciated.
Update:
New version using the state machine methodology suggested by JRobert and Edgar
Any comments on structure?
// include SPI, MP3 and SD libraries
#include <SPI.h>
#include <Adafruit_VS1053.h>
#include <SD.h>
// include AccelStepper libraries
#include <MultiStepper.h>
#include <AccelStepper.h>
using namespace std;
/*-----( Declare Enums & Constants )-----*/
// Arduino Digital I/O pin numbers for MEGA
//note: digital pins 30-45
//MEGA is a MUST for this project
enum {
    Relay1 = 30, Relay2 = 31, Relay3 = 32, Relay4 = 33, Relay5 = 34, Relay6 = 35,
    Relay7 = 36, Relay8 = 37, Relay9 = 38, Relay10 = 39, Relay11 = 40,
    Relay12 = 41, Relay13 = 42, Relay14 = 43, Relay15 = 44, Relay16 = 45
};

enum { RELAY_OFF = HIGH, RELAY_ON = LOW };

enum {
    CROSSINGZONE_CLEAR, // no train in crossing area, also initialized state
    CROSSINGZONE_OCCUPIED, // train detected by the entry sensor
    CROSSINGZONE_EXITING  // train detected by the exit sensor, when sensor clears state = CLEAR
};

 enum {
     EXITSENSOR_CLEAR, // no train has passed the crossing gate exit sensor
     EXITSENSOR_ENTERED, // train detected by the exit sensor
     EXITSENSOR_WAITINGTOCLEAR // train passed by the exit sensor, when sensor clears state = CLEAR

 };

byte state = CROSSINGZONE_CLEAR;
 //*-----( Declare Variables )-----*/
// hardware is an optocoupler 16 channel 12V relay
const byte relays[] = { Relay1,Relay2,Relay3,Relay4,
Relay5,Relay6,Relay7,Relay8,
Relay9,Relay10,Relay11,Relay12,
Relay13,Relay14,Relay15,Relay16 };
enum { maxRelayCount = sizeof relays / sizeof relays[0] };

byte entrySensorPin = 26;
byte exitSensorPin = 28;
const char* soundFile = "trainxng.mp3";
boolean debugMode = true;
boolean exitSensorTripped = false;

// These are the pins used for the music maker shield
#define SHIELD_RESET  -1      // VS1053 reset pin (unused!)
#define SHIELD_CS     7      // VS1053 chip select pin (output)
#define SHIELD_DCS    6      // VS1053 Data/command select pin (output)
// These are common pins between breakout and shield
#define CARDCS 4     // Card chip select pin
// DREQ should be an Int pin, see  http://arduino.cc/en/Reference/attachInterrupt
#define DREQ 3       // VS1053 Data request, ideally an Interrupt pin

AccelStepper gateMotor1Left(AccelStepper::DRIVER, 4, 3);  // 1=Stepper driver option, 4=Step pulse pin, 3=Direction
AccelStepper gateMotor1Right(AccelStepper::DRIVER, 6, 5);  // 1=Stepper driver option, 6=Step pulse pin, 5=Direction
AccelStepper gateMotor2Left(AccelStepper::DRIVER, 8, 7);  // 1=Stepper driver option, 8=Step pulse pin, 7=Direction
AccelStepper gateMotor2Right(AccelStepper::DRIVER, 10, 9);  // 1=Stepper driver option, 10=Step pulse pin, 9=Direction
Adafruit_VS1053_FilePlayer musicPlayer =
    Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

class CrossingGate {
  public:
    // hmm voids or booleans?
    boolean GateFlashersOn(byte relayNumber) {
        digitalWrite(relayNumber, RELAY_ON);
        //need a check here to ensure its set LOW which is inactive for these relays
        return true;
    }
    boolean GateFlashersOff(byte relayNumber) {
        digitalWrite(relayNumber, RELAY_OFF);
        //need a check here to ensure its set HIGH which is inactive for these relays
        return true;
    }
    boolean GateArmFlashersOn(byte relayNumber) {
        digitalWrite(relayNumber, RELAY_ON);
        //need a check here to ensure its set LOW which is inactive for these relays
        return true;
     }
     boolean GateArmFlashersOff(byte relayNumber) {
         digitalWrite(relayNumber, RELAY_OFF);
        //need a check here to ensure its set HIGH which is inactive for these relays
        return true;
    }
    boolean GatesUp(byte relayNumber) {
        digitalWrite(relayNumber, RELAY_ON);
        //need a check here to ensure its set LOW which is inactive for these relays
        return true;
    }
    boolean GatesDown(byte relayNumber) {
        digitalWrite(relayNumber, RELAY_OFF);
        //need a check here to ensure its set HIGH which is inactive for these relays
        return true;
    }

};

 class CrossingGateRoad {
   public:
       void PowerOn(byte relayNumber) {
           digitalWrite(relayNumber, RELAY_ON);

       }
       void PowerOff(byte relayNumber) {
           digitalWrite(relayNumber, RELAY_OFF);

       }
};
//  Sensor methods
int CheckEntrySensor(byte esp) {
    if (digitalRead(esp) == HIGH)
    {
         state = CROSSINGZONE_CLEAR;
         return CROSSINGZONE_CLEAR;
    }
    else {
        state = CROSSINGZONE_OCCUPIED;
        return CROSSINGZONE_OCCUPIED;
    }
     return -1;
}
int CheckExitSensor(byte xsp) {
    if (digitalRead(xsp) == HIGH && state == CROSSINGZONE_OCCUPIED)
    {
        state = CROSSINGZONE_OCCUPIED;
        return CROSSINGZONE_OCCUPIED;
    }
    else if(digitalRead(xsp) == LOW && state == CROSSINGZONE_OCCUPIED)
    {
        state = CROSSINGZONE_CLEAR;
        return CROSSINGZONE_OCCUPIED;
    }
    return -1;
}

boolean CrossingBellsOn(Adafruit_VS1053_FilePlayer & mp, const char* soundFile) {
    if (!mp.startPlayingFile(soundFile)) {
        Serial.println("Could not open file trainxng.mp3 using the passed in object");
        while (1);
    }
    return true;
}
boolean CrossingBellsOff(Adafruit_VS1053_FilePlayer & mp) {
    if (mp.playingMusic) {
        mp.stopPlaying();
         return true;
    }
    if (mp.stopped())
    {
        return true;
    }
    return false;
}

CrossingGate xGate1Left;
CrossingGate xGate1Right;
CrossingGate xGate2Left;
CrossingGate xGate2Right;

CrossingGateRoad xGateRoad;

void setup() {
    Serial.begin(9600);
    // Set max speed. Steps per second
    gateMotor1Left.setMaxSpeed(500);
    gateMotor2Left.setMaxSpeed(500);
    gateMotor1Right.setMaxSpeed(500);
    gateMotor2Right.setMaxSpeed(500);
    // set motor acceleration
    gateMotor1Left.setAcceleration(35);
    gateMotor2Left.setAcceleration(35);
    gateMotor1Right.setAcceleration(35);
    gateMotor2Right.setAcceleration(35);
    // set motor speeds
    gateMotor1Left.setSpeed(20);
    gateMotor2Left.setSpeed(20);
    gateMotor1Right.setSpeed(20);
    gateMotor2Right.setSpeed(20);

    Serial.println("Adafruit VS1053 Library Test");
    // initialise the music player
    if (!musicPlayer.begin()) { // initialise the music player
         Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
        while (1);
    }
    Serial.println(F("VS1053 found"));
    //musicPlayer.sineTest(0x44, 500);    // Make a tone to indicate VS1053 is working
    // check the card reader
    if (!SD.begin(CARDCS)) {
        Serial.println(F("SD failed, or not present"));
        while (1);
    }
    Serial.println("SD OK!");
    // Set volume for left, right channels. lower numbers == louder volume!
    musicPlayer.setVolume(20, 20);

    // This option uses a pin interrupt. But DREQ must be on an
    //  interrupt pin. For Uno/Duemilanove/Diecimilla that's Digital #2 or #3
    // See http://arduino.cc/en/Reference/attachInterrupt for other pins
    // * This is the preferred method
    if (!musicPlayer.useInterrupt(VS1053_FILEPLAYER_PIN_INT))
        Serial.println(F("DREQ pin is not an interrupt pin"));

}
void loop() {

    switch (state) {
        case CROSSINGZONE_CLEAR:
          // Check entry sensor. If tripped, turn on the sound.
         if (CheckEntrySensor(entrySensorPin) == 1) {
            // first go around i'll try to tun all these here otherwise
            // I will break out to more states
            //these happen instantly
            xGateRoad.PowerOff(relays[0]);
            xGate1Left.GateArmFlashersOn(relays[1]);
            xGate1Right.GateArmFlashersOn(relays[2]);
            xGate2Left.GateArmFlashersOn(relays[3]);
            xGate2Right.GateArmFlashersOn(relays[4]);
            xGate1Left.GateFlashersOn(relays[5]);
            xGate1Right.GateFlashersOn(relays[6]);
            xGate2Left.GateFlashersOn(relays[7]);
            xGate2Right.GateFlashersOn(relays[8]);
            //these take some time
            xGate1Left.GatesDown(relays[9]);
            xGate1Right.GatesDown(relays[10]);
            xGate2Left.GatesDown(relays[11]);
            xGate2Right.GatesDown(relays[12]);
            //this is the last process, if it completes change state
            if (CrossingBellsOn(musicPlayer, soundFile)) {
                state = CROSSINGZONE_OCCUPIED;
            }
        }
        else {
            state = CROSSINGZONE_CLEAR;
        }
        break;
    case CROSSINGZONE_OCCUPIED:
        // Once zone is occupied, monitor the exit sensor
        if (CheckExitSensor(exitSensorPin) == 0) { // Exit sensor not tripped yet
            state = CROSSINGZONE_OCCUPIED;
        }
        else {
            exitSensorTripped = true;
        }
        if (exitSensorTripped)
        {
             // need to code here to wait until Exit Sensor has 1500 milliseconds where its clear
            // to indicate that the last car of train has passed it
            // if above set exitSensorTripped back to false and state to EXITING
            state = CROSSINGZONE_EXITING;
        }
        break;
    case CROSSINGZONE_EXITING:
        // Check if the train has cleared, then shut the sound.
        if (CheckExitSensor(exitSensorPin) == 1) {
            // first go around i'll try to tun all these here otherwise
            // I will break out to more states
            //these happen instantly
            xGateRoad.PowerOn(relays[0]);
            xGate1Left.GateArmFlashersOff(relays[1]);
            xGate1Right.GateArmFlashersOff(relays[2]);
            xGate2Left.GateArmFlashersOff(relays[3]);
            xGate2Right.GateArmFlashersOff(relays[4]);
            xGate1Left.GateArmFlashersOff(relays[5]);
            xGate1Right.GateArmFlashersOff(relays[6]);
            xGate2Left.GateArmFlashersOff(relays[7]);
            xGate2Right.GateArmFlashersOff(relays[8]);
            //these take some time
            xGate1Left.GatesUp(relays[9]);
            xGate1Right.GatesUp(relays[10]);
            xGate2Left.GatesUp(relays[11]);
            xGate2Right.GatesUp(relays[12]);
            //this is the last process, if it completes change state
            if (CrossingBellsOff(musicPlayer)) {
                state = CROSSINGZONE_CLEAR;
            }
        }
        break;
    }
}

What do the debugging prints show?

Just checked this last versions of your code. Looks to me like it should work, but I have a bunch of comments and suggestions: the code would be clearer if you get rid of unused stuff (EXITSENSOR_*, maxRelayCount, GateFlashersOff(), the AccelSteppers). The state should have the proper enum as its type instead of byte. Do not change the state in the checkSensor() methods. Failure of playing the sound should not prevent the state to become OCCUPIED...

...exitSensorTripped is useless: case CROSSINGZONE_OCCUPIED: if (CheckExitSensor()) state = CROSSINGZONE_EXITING; break; is enough. The various else { state = the_current_state; } are useless. The return values of the CrossingGate methods are never checked. The pin numbers should be private data of CrossingGate rather than method parameters. Only two methods are needed in CrossingGate: open() and close(), the details can be taken care of by the class.

@Edgar... I did some refactoring on plane ride home. I had already removed the EXITSENSOR...ENUM and refactored my other enums to use C++11 style i.e. enum class CrossingRoadState {blah = 0,blah1 = 1}. The problem in the exiting zone is that 2 things have to happen. The exit sensor trips BUT then I have to monitor it to capture when two full seconds of HIGH (which I believe is inactive) THEN set back to Clear, as once exit sensor is tripped the train is still passing it making the sensor bounce back and forth HIGH/LOW.

Re. " The return values of the CrossingGate methods are never checked." I already changed all the methods in the class to voids from booleans.

Elaborating on JRobert's answer, which I think is definitively the way
to go. Here is a typical way of writing a state machine with only three
states:

No train in the area. You are monitoring the entry sensor.
You have detected the train on the entry sensor. You started playing
the sound. You are monitoring the exit sensor.
You have detected the train on the exit sensor. You are still
monitoring the same sensor in order to know when the train clears the
area.

Notice that the actions you perform (starting and stopping the sound
for instance) are not associated with a particular state but with a
transition between states: you start the sound on the 1 → 2
transition and stop it on 3 → 1.
Here is the code for loop():
void loop() {
    static enum {
        NO_TRAIN,        // no train in the area
        TRAIN_ENTERED,   // train seen by the entry sensor
        TRAIN_EXITING    // train seen by the exit sensor
    } state = NO_TRAIN;  // initial state

    switch (state) {
        case NO_TRAIN:
            // Check entry sensor. If tripped, turn on the sound.
            if (checkEntrySensor()) {
                musicPlayer.startPlayingFile("trainxng.mp3");
                flashers.turnOn();
                gates.close();
                road.powerDown();
                state = TRAIN_ENTERED;
            }
            break;
        case TRAIN_ENTERED:
            // The exit sensor must be monitored.
            if (checkExitSensor()) {
                state = TRAIN_EXITING;
            }
            break;
        case TRAIN_EXITING:
            // Check if the train has cleared, then shut the sound.
            if (!checkExitSensor()) {
                musicPlayer.stopPlaying();
                flashers.turnOff();
                gates.open();
                road.powerUp();
                state = NO_TRAIN;
            }
            break;
    }
}

This may be a bit oversimplified: if an action need some time, you may
have to create an extra state for it. For example, in order to avoid
blocking the program while the barrier goes down, you can split the
transition NO_TRAIN → TRAIN_ENTERED in two:
NO_TRAIN → LOWERING_BARRIER → TRAIN_ENTERED

and the action “lower the barrier” is itself split into “start lowering
the barrier” (on the first transition) and “stop lowering the barrier”
(on the second transition).

Thank you for the example. I've followed essentially the same path except I have it broken down to 12 states as there are other processes that need to run when the entry sensor trips

@dinotom: If those processes can be started fast, and you can afford waiting for them, you can live with only three states. See amended answer.

Although I am traveling and don't have the hardware to test this with me. I've updated the post to include the new state machine code. Any comments appreciated.

This is a classic state-machine problem. That isn't the only way to do it but it's just made for this kind of problem, one in which only certain external events are interesting at a given time; and when such an event occurs, the controller must tweak the outside world in some way, and then start paying attention to a different set of interesting events.
Does playing a sound file totally occupy the Arduino until the sound is done? And if so, can your process tolerate the controller being unresponsive for the duration of the sound track? Because otherwise you'll need something more capable than an Arduino, or you'll need to be able to program the Arduino to feed the sound in small pieces to a buffered sound card, so it (the Arduino) can continue monitoring the interesting set of possible events while the sound is playing. That probably means some clever programming with the SimpleTimer library or similar, or using interrupt service routines to inform some part of your code when an event occurs. Probably the ideal cases would be to have a "sound machine" that can play 'n' different tracks, and would do so autonomously when told to start playing track 'j'. Begins to sound like another MCU just handling sound, doesn't it?
Update:
Look up state machine diagrams - basically circles representing states and arrows representing transitions to a new state in response to an events. There are several ways to put the state machine's control of the external equipment; my choice is that each state "does something" then "waits for something to happen", where something to happen may include a clock signal indicating the event(s) it was waiting for didn't happen (i.e. a timeout). Look at some state diagrams to get an idea how they are used, then start diagramming your own project.
I draw the "happy path" straight down the page - that path that represents the normal or expected operation - with less usual or error paths drawn to either side. At that point you should be pretty confident in your algorithm.
There are several ways to code state machines - that'll be a further discussion.

the way I've defined the shield, uses its interrupts and other events and processes can occur while its playing (at least according to the documentation) Any examples or references to point me to for the state machine method or operating this ?

I found something to work from.

State 0: pinging entry sensor to determine when it changes state (S)
State 1: crossing gate sound playing (T)
State 2: crossing gate arms lowering (T)
State 3: crossing gate flashers flashing (T)
State 4: road power turned off (T)
State 5: pinging exit sensor to determine when it changes state (S)
State 6: once triggered, continue pinging exit sensor to determine when it changes back (S)
State 7: crossing gate sound off (T)
State 8: crossing gate arms raising (T)
State 9: crossing gate flashers off (T)
State 10: road power turned on, return to state 0 (T)....You agree with these states?

Would love some guidance on this as I've never coded a state machine before.Ill work on it tonight and tomorrow. Ill create a new post sometime late tomorrow if I run into trouble.

Sure, see my profile.

I think your problem here is that you are using multiple instances of Adafruit_VS1053_FilePlayer.
Namely:
Adafruit_VS1053_FilePlayer musicPlayer = Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

That's two already.
Then you pass a copy here:
Adafruit_VS1053_FilePlayer onSignalSound(Adafruit_VS1053_FilePlayer mp, const char* fileName) {

And return another copy:
return mp;

All this creating/destroying copies is probably stopping the playback of the current copy.
I've reworked your code to avoid all that:
#include <Adafruit_VS1053.h>

// These are the pins used for the music maker shield
#define SHIELD_RESET  -1      // VS1053 reset pin (unused!)
#define SHIELD_CS     7      // VS1053 chip select pin (output)
#define SHIELD_DCS    6      // VS1053 Data/command select pin (output)

// These are common pins between breakout and shield
#define CARDCS 4     // Card chip select pin
// DREQ should be an Int pin, see http://arduino.cc/en/Reference/attachInterrupt
#define DREQ 3       // VS1053 Data request, ideally an Interrupt pin

// create shield-example object
Adafruit_VS1053_FilePlayer musicPlayer (SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

//global variables required
boolean crossingSignalInOperation = false;
boolean signalEntrySensor = false;
boolean signalExitSensor = false;
boolean debugMode = false;

boolean checkEntrySensor() {
    //check entry sensor, if tripped return true otherwise false
    /*if () return true;
    return false;*/
    return true;  //hardcoded for testing
}

void setup() {
    // put your setup code here, to run once:
    Serial.begin(9600);
    debugMode = true;   //set this to false once code is fully operational
    //initialise music maker shield
        if (!musicPlayer.begin()) {
            if (debugMode)
            {
                Serial.println(F("Couldn't find VS1053, do you have the right pins defined?"));
            }

        while (1);
    }
    // 1st parameter is left, second parameter is right
    musicPlayer.setVolume(20, 20);
    if (debugMode)
    {
        Serial.println(F("VS1053 found"));
    }

    // initialise the SD card
    SD.begin(CARDCS);

    //ensure our global booleans all start false
    crossingSignalInOperation = false;

}

void loop() {
    // put your main code here, to run repeatedly

    signalEntrySensor = checkEntrySensor();
    if (signalEntrySensor == true) {  //only want to catch the FIRST time it senses
        if (crossingSignalInOperation == false)
        {
            //crossing signal is inactive, activate it
            // turn the sound on and return the music player object
            onSignalSound(musicPlayer,"trainxng.mp3");

            while (musicPlayer.playingMusic) {
                // file is now playing in the 'background' so now's a good time
                // to do something else
                if (!crossingSignalInOperation)
                {
                    crossingSignalInOperation = true;
                    //run the other three processes
                    //offRoadPower();
                    //lowerSignalArms();
                    //startSignalFlashers();

                }
            }
        }
    }
 }

void onSignalSound(Adafruit_VS1053_FilePlayer & mp, const char* fileName) {
    // Play the train crossing sound file
    if (debugMode)
    {
        Serial.println(F("Playing track - "));
        Serial.print(fileName);
    }
    //all sound files are on the micro sd card on the music player shield
    if (!mp.startPlayingFile(fileName)) {
        Serial.println(F("Could not open file "));
        Serial.print(fileName);
        while (1);
    }
}
boolean offSignalSound(Adafruit_VS1053_FilePlayer & mp) {
    if (mp.playingMusic)
    {
        mp.stopPlaying();
        return true;
    }
    return true;
}

Untested, because I don't have the hardware, but that should work better.
The Adafruit_VS1053_FilePlayer object is passed by reference to the function, which avoids another copy being made. We are using the original one at global scope, so we don't keep creating and discarding copies. In fact, since we are using the global one you could avoid passing it to the function at all.

Ok. I see your point . 2 things, the Adafruit library defines the object the way I wrote it... Adafruit_VS1053_FilePlayer musicPlayer =
Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);    Unless that's a C++ specific way of declaring variables? That wouldn't fly in C#

And what is the ampersand for in the sound on function music player parameter?

Opening port
Port open
VMDPV_1|1_VMDPV
VS1053 found
Playing track -
trainxng.mp3.... is the out put to the serial mointor, but the file still only plays for a split second, with your changes

Unless there is something different about C++ vs C# my function is of type Adafruit_VS_FilePlayer, not creating a new one and I'm passing in the originally created one, so not creating another one there either. My code and your update are both functioning identically. And mine is returning the original instance

The ampersand passes a variable by reference. Normally variables are passed by value. To pass by value a copy is made. I'm passing in the originally created one - a copy of the original one. And why return it? You already have it at global scope. My code and your update are both functioning identically - you are running my code exactly as posted?


text:
Connect Arduino Uno to server using oneM2M platform
I have an Arduino Uno that doesn't have any Wi-Fi. After putting the sensor there, I've found out that it is quiet impossible to connect to localhost for oneM2M platform.
Is there any possibility that I can connect to localhost using just the blue cable below which will also being used for uploading the code? Any help will be much appreciated!

there was an attempt to make TCP over Serial. I don't know if it works. https://playground.arduino.cc/Code/SerialIP

You can not do it without a special software running on the computer. I mean special as in someone will need to write it since there likely isn't something available that you can find.
The most practical solution is to either use an ethernet shield on the Uno. Or use a board like the Wemos D1 Mini (an ESP8266 based board) that can do Wifi. It can run under the Arduino platform. And they are dirt cheap.
https://wiki.wemos.cc/products:d1:d1_mini
https://wiki.wemos.cc/doku.php
https://wiki.wemos.cc/products:d1_mini_shields:dht_shield

So what you mean here is it is impossible to connect to server without the wifi thingy (ESP8266) ?

Wifi or ethernet. Ethernet is a wired connection, it would go into a router. I prefer WiFi as it is more convenient. And not all that hard to do. There are a lot of examples that can be the foundation for what you want to access.


text:
Can 2 H-Bridges be controlled by one Arduino?
The three motors are from windshield wipers, with one of the brushes disconnected in each. The controllers are BTS7960 43A modules
One bridge for two drive motors (speed and direction), and the second bridge for a third [modified servo-like] motor (for Ackerman steering).
Is this possible/recommended?

Yes. Why would you suppose it wasn't?

never seen it before, always one arduino one driver.

That's because for many projects one driver is enough.

@Majenko i see. at the risk of noob-shaming, can you please give an extremely brief review of the project. it's three wiper motors; 2 behind for drive and one front like an RC car servo for steering. input from an on-board ROS computer to the arduino (USB), to each BTS7960 bridge for movement control. and controlling four separated strips of WS2812B smart LEDs
recap: can one arduino work with 1) continuous USB input from a computer 2)controlling 2 separate h-bridges 3) controlling smart LED strips 4)all at the same time

There is absolutely no difference between using one and using two drivers. It's just the number of pins of the different types that you need.

many thanks @Majenko

Yes you can connect 2 H-bridges to a single arduino. Just make sure that you have enough power for the arduino and the motors and also check if you have enough pins (I/O and PWM) for using the H-bridges.


text:
STM32YYXX chip series is not defined in boards.txt
The STM32YYXX chip series is not defined in boards.txt? How can I solve this? I am using Windows 10 with Arduino IDE 1.6.6

what boards.txt?

Did the answer help? If so then please upvote and mark as the accepted answer. If you found an alternative method, then please post that as an answer and mark that as the accepted answer.

Overview
Following the guide Getting Started on the STM32 page on Github: Arduino core support for STM32 based boards:

This repo is available as a package usable with Arduino Boards
  Manager.
Use this link in the "Additional Boards Managers URLs" field:
https://github.com/stm32duino/BoardManagerFiles/raw/master/STM32/package_stm_index.json
For full instructions on using the "Boards Manager", see the Getting
  Started page.

Thanks to Juraj's comment for the tip

this is not the current STM boards package. ST Microelectronic took over the development github.com/stm32duino/Arduino_Core_STM32 stm32duino.com/viewtopic.php?f=16&t=4671

Step by Step
The process is as follows (screenshots from OS X, but on Windows/Linux the process is the same):
Adding the URL in the preferences dialog (one URL per line)

Boards Manager menu

Boards Manager dialog

Boards Manager dialog - STM32 Core Boards installed

Boards Manager dialog - Boards installing

Boards Manager dialog - Boards installed

Here are the newly installed boards in the menu

As a comparison, these are the boards installed using the deprecated manual process described below:

Deprecated method

From STM32 - installation

Prerequisites
If your STM32 board does not have a bootloader yet and you want to be able to program it over USB, you'll have to upload
  the STM32duino bootloader to flash memory. See Burning the
  bootloader.
Arduino and Arduino_STM32

Download and install the official Arduino IDE. Versions 1.6.10 till 1.8.5 have been reported to work fine.

If you already have the Arduino IDE installed and it's a newer version, see the Boards Manager package method of installation.

Note: this method is deprecated and not supported in forum!

Run Arduino IDE, and open the menu Tools -> Boards -> Boards Manager. Install the "Arduino SAM Boards" package (includes the
  Arduino Due) from the list of available boards. This installs compiler
  support for ARM Cortex-M3.
Download a zip file containing the Arduino STM32 files from here.
Unzip the content of the zip file, and place the Arduino_STM32 folder to [Arduino sketches folder]/[hardware]/[Arduino_STM32].
  Create the 'hardware' folder if it does not exist yet.

Example how the path should look like:
  C:\Users\<user>\Documents\Arduino\hardware\Arduino_STM32

As an aside, for anyone using OS X, from Installation on OSX

Installation on OSX

Arduino_STM32 folder must be placed inside
  ~/Documents/Arduino/hardware (note. if the hardware folder doesn't
  exist you will need to create it)
So you should get ~/Documents/Arduino/hardware/Arduino_STM32
Note.  DFU util binaries
  have now been added to the repo, in tools/macosx/dfu-util, so there is
  no longer a need to install Homebrew to then install dfu-util, or to
  compile dfu-util from source.

I recommend the Boards Manager package method of installation.

It says that the Boards Manager method is depreciated. Is that incorrect?

this is not the current STM boards package. ST Microelectronic took over the development https://github.com/stm32duino/Arduino_Core_STM32 http://stm32duino.com/viewtopic.php?f=16&t=4671

You should post that as an answer then, as mine seems to be out of date.

If the downvoter could explain why the downvote or better still post an answer then that would be most helpful. A warm thanks.

@Juraj - I think I may may encounter a similar issue as the OP, I need to code up (what I believe to be) a Maple Mini board, but which has been customised with a 303 rather than a 103... and there doesn't seem to be that option available after installing the package, using the method described in my answer (I haven't tried your github link yet).I may need to post my own (similar) question.

the ST package has Boards Manager installation and is up-to-date. with F303 too

Ah OK, thanks. I'll give it a go. If that all works fine, I might update/correct my answer with your (github) suggestion, and credit your comment for it, if you don't mind...?


text:
Why do I have to burn the code to make it run?
Why do I have to burn the code twice to actually burn it on to the Arduino board? I have to execute this command twice - only then is the chip getting programmed.
I'm using this command to burn the program into the Arduino Uno board using a Rasp Pi 3, via SSH from Windows 10.
avr-gcc -mmcu=atmega328 filename.c | avr-objcopy -O ihex -j .text -j .data a.out a.hex | avrdude -C avrdude.conf -v -p atmega328p -c arduino -P /dev/ttyACM* -b 115200 -D -U flash:w:a.hex:i

Please post any messages you get from the burning process (amend your question to do this).

why do you use | between the commands?

to execute those three separate command in one single time. @Juraj

On a Unix shell, separating commands with the pipe character (|) means
“run these commands in parallel, feeding the standard output of each one
to the standard input of next one”.
In this context, it makes no sense to use pipes, as both avr-objcopy and
avrdude read their data from files, not from stdin. Furthermore, running
these in parallel means that avrdude will not have access to a.hex
when it starts.
The solution is to run the commands sequentially instead of in
parallel. Type and run one command at a time.
Alternatively, if you really want to have everything in a single line,
separate the commands with a semicolon (;, meaning “run the next
command when the previous one is done”) or, better yet, double ampersand
(&& = “run the next command only if the previous one exits
successfully”).

correct me,
so in the first burn it is the previous a.hex file and while on the second burn it gets the new one. right?

@user137442: Probably something like that, although it's hard to know exactly. Avrdude may be burning the hex file from the previous run of the pipe, or from the one before if the previous run could not build an hex file, or it may fail because it finds an incomplete hex file which is in the process of being written... By starting the three commands in parallel, you are at the mercy of unpredictable, timing-dependent behavior.

thank you so much Bonet.
I tried && and it is working fine in the first burn only.
In your answer you said somthing like "In this context, it makes no ......... a.hex when it starts"
Can you explain this?

@user137442: Many Unix utilities (sort, split, sed, head...) default to processing the data that comes into their standard input and write the results to standard output. These are meant to be combined with pipes. The commands you are using do not work this way so, when using avr-gcc, avr-objcopy and avrdude, it makes no sense to use pipes.

Thank you. I haven't understood all but i can see where it is going wrong. Thank you so much


text:
Help with NodeMCU based smart switch
The project I'm planning is to use a NodeMCU at each electrical board in house to control lights and fans via relays. Each MCU will communicate via MQTT over WiFi to a Raspberry Pi 4 from where I can control all lights and fans in the house. My doubt is:
Can the 3.3V NodeMCU drive a 5V relay like this 1 Channel 5V Relay Module with Optocoupler since I can't find any 3.3 V relays in India. Or must I use a logic level shifter? Or just use an ESP32 board (double price).

not drive, which means that the NodeMCU would supply power to the relay solenoid , but control, which means that the NodeMCU would operate a relay driver circuit

in my experience, 3.3v compat with those types of relay modules (i've tried 4 or 5 styles) will vary; some will be fine, some won't like it at all, and some will be spotty. For lower wattage loads like lighting, you can actually just use a triac-based optocoupler, some of which handle a few 100ma.

You don't need the typical level shifter. A.simple little transistor in combination is totally sufficient for the signal line of the relay module. Then you only need to provide 5V power (with which you can power the relay and the NodeMCU)

The relay I linked to couldn't be operated with 3v3 from the NodeMCU board. I was powering the NodeMCU via a breadboard power supply that had both 3v3 and 5v output (https://www.electronicscomp.com/mb102-breadboard-power-supply-module). I connected the Vcc and GND of relay to 5V supply on that module. the IO pin relay was connected to NoddeMCU. It worked fine and NodeMCU could switch it on and off.


text:
Smoke coming out of Arduino Uno R4 Minima
My Arduino Uno R4 Minima started smoking after connecting to a computer. I disconnected it and visually checked it and I saw this bubble as shown on this photo.

Can I recover my Uno from this to still use it or do I have to throw it away?

Was anything else connected?

Can the computer still talk to the board? If not, then it's probably dead. You could repair it by replacing the IC, if you are handy with a hot air gun. If not, I still wouldn't throw it away, it might be useful for parts.

did you place the board on top of something metallic?

did you power the board with an external power supply connected  to the barrel jack?

That buck converter ISL854102  appears well protected against abuse and tolerates back feeding so it is difficult to imagine what happened here and what else may have been damaged by this incident. Datasheet: https://www.renesas.com/us/en/products/power-power-management/dc-dc-converters/step-down-buck/buck-regulators-integrated-fets/isl854102-wide-vin-12a-synchronous-buck-regulator .

The marked IC is burnt. You should complain to the seller and claim warranty. if it is still within the warranty period. If you are very skilled at soldering. You can try to replace the IC.

If the OP damaged it through misuse then why would the seller be liable?

That's  the buck-converter that connects to the external power supply.
The board should still work when powered by the USB cable.
Remove R11 to isolate the blown circuit if you like.
https://docs.arduino.cc/resources/schematics/ABX00080-schematics.pdf

This should be the accepted answer, IMHO.

It smokes powered by USB.


text:
Arduino Uno to Arduino Uno Word.doc file transfer
I have written a 2 sets of code for the transmitter and receiver section. I am trying to send a word document file from 1 arduino uno to the next arduino uno through serial TX and RX. The file is initially loaded into a micro sd card module at the transmitter section. I would like to transfer that file to the receiver section's sd card module. I am able to receive an empty word document at the receiver section. There is no information in the document. I would like some help with this. I will attach the transmitter and receiver code below.
Transmitter code:
#include <SD.h>
#include <SPI.h>

File fileIn;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
   while (!Serial){
    ; //  wait for serial port to connect. Needed for native USB port only
  }
  Serial.print("Initializing SD card...");
  if(!SD.begin(4)){
    Serial.println(F("Initialization failed!"));
    return;
  }
  Serial.println("Initialization done.");
  if(!SD.exists("student.txt")){
    fileIn = SD.open("student.txt", FILE_WRITE);
    fileIn.println(F("abc.txt"));
  }
  fileIn = SD.open("student.txt", FILE_READ);

  while(fileIn.available()){
    Serial.write(fileIn);
  }
  delay(1000);
  fileIn.close();
}

void loop() {
  // put your main code here, to run repeatedly:

}

Receiver code:
#include <SD.h>
#include <SPI.h>

File fileOut;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  while (!Serial){
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.print("Initializing SD card...");
  if(!SD.begin(4)){
    Serial.println(F("Initialization failed!"));
    return;
  }
  Serial.println("Initialization done.");
  if(SD.exists("student2.txt")){
    SD.remove("student2.txt");
  }
  fileOut = SD.open("student2.txt", FILE_WRITE);

  while(fileOut.available()){
    Serial.write(fileOut);
  }
  delay(1000);
  fileOut.close();
  Serial.println("It worked!");
}

void loop() {
  // put your main code here, to run repeatedly:

}

  while(fileOut.available()){
    Serial.write(fileOut);
  }

This doesn't quite do what you think it does.
Instead you should send the file length first and then do:
for(unsigned long size = 0; i< fileLength; i++){
    Serial.write(fileOut.read());
}

You should also investigate some kind of rate limiting to avoid overwhelming the reciever and having to drop some bytes.

Is it possible to read the line and take that as a file length in the 1st arduino and how would I implement this with the receiver arduino?

File has a size() member function. And just send 4 bytes with the length before you send the rest of the file. on the recieve side the first 4 bytes read will be the size of the file you will be recieving.


text:
Code is not working (Matrix keypad)
I am new to Arduino. I am learning from Arduino Cookbook. I was using tinkercad.com for running my Arduino code. But it is not working.
The Serial monitor should show the key which I have pressed on the keypad.
I think there is some syntactical error in the code, I believe the connection is all right.
Any suggestion will be appreciated.
Please look into this:
const char keymap[4][4]={
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
 };
const int rpin[]={9,8,7,6};
const int cpin[]={5,4,3,2};
void setup()
{
  Serial.begin(9600);
  Serial.println("Program starting");//for debugging purpose and canbe removed later
  for(int i=0;i<4;i++)
  {
    pinMode(rpin[i],INPUT);
    digitalWrite(rpin[i],HIGH);
  }
  for(int j=0;j<4;j++)
  {
    pinMode(cpin[j],INPUT);
    digitalWrite(cpin[j],HIGH);
  }
}
void loop()
{
  char key=getkey();
  if(key!=0)
  {
   Serial.println(key);
  }
}
char getkey()
{
  char key=0;
  for(int i=0;i<4;i++)
  {
    digitalWrite(rpin[i],LOW);
    for(int j=0;j<4;j++)
    {
      if (digitalRead(cpin[j])==LOW)
      key=keymap[i][j];
    }
    digitalWrite(rpin[i],HIGH);
  }
  return key;
}

and the connection pic:

update 1:

The serial monitor is blank.

The serial monitor should provide the key pressed on it.

I think so software problem.

In my opinion, it may be some syntactical error.

To verify serial communication is working, add this line after your Serial.begin() statement: Serial.println("Program starting");. Let us know whether you see that line printed when you open the Serial Monitor.

No, instead i have used internal pull-up.

@per1234 it is working.

Please update the question with the full description of what you mean by "not working". Note that you already have 2/5 close votes on this question.

@per1234 is it okay? Or else should I provide more.

Add in the Serial test line to your code and note that part is printed so that people know your Serial communications is working correctly. You could add a comment to that line to remind yourself that it's only there for debugging and can be removed later to save memory. Your question should stand by itself without needing to read the information in the comment thread.

@per1234, Any solution?

Check pin modes. Should be INPUT_PULLUP and OUTPUT. Also consider debouncing.

@MikaelPatel, It is still not working.

"I think there is some syntactical error in the code" In that case the code wouldn't even compile.

Cited comment:

Check pin modes. Should be INPUT_PULLUP and OUTPUT. Also, consider
  debouncing. – Mikael Patel

Please, try:
const char keymap[4][4]={
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
 };
const int rpin[]={9,8,7,6};
const int cpin[]={5,4,3,2};
void setup()
{
  Serial.begin(9600);
  Serial.println("Program starting");//for debugging purpose and canbe removed later
  for(int i=0;i<4;i++)
  {
//Should be INPUT_PULLUP and OUTPUT
    pinMode(rpin[i],OUTPUT);
    pinMode(cpin[i],INPUT_PULLUP);
  }
}
void loop()
{
  char key=getkey();
  if(key!=0)
  {
   Serial.println(key);
   delay(200);              // Also, consider debouncing.
  }
}
char getkey()
{
  char key=0;
  for(int i=0;i<4;i++)
  {
    digitalWrite(rpin[i],LOW);
    for(int j=0;j<4;j++)
    {
      if (digitalRead(cpin[j])==LOW)
      key=keymap[i][j];
    }
    digitalWrite(rpin[i],HIGH);
  }
  return key;
}

I tested this code and it works. And the debouncing time can be lowered to something like 10.

@gre_gor , for what purpose do you reduce to 10?

So it's faster to respond.

@gre_gor , to manually control the buttons, a 0.2-second delay is acceptable. And 0.01-second delay may not be enough.


text:
RS485 message edit on the fly between EV charger and energy meter
I am trying to connect Feyree smart EV charger with Dynamic Load Balancing to DTSU666 smart meter via RS485.
Dynamic Load Balancing is a function of EV charger that lets you dynamically change charger output depending on reading from your energy meter (home consumption) to limit total consumption to a set current.
The only issue is selectable current range on EV charger is 20-100 A. I want to use this setup with solar panels so it can limit charging current depending on solar power in a way that total power output from my house (on bidirectional energy meter) is balanced to 0 A (no power pulled from grid and no power going to the grid, all excess power going to EV charger).
This means I would need to set DLB current on charger to 0 A so it could balance out nicely, but like I said the settable range is from 20 A to 100 A.
What's the easiest way to add constant value to the RS485 message on the fly? Can I put MKR 485 Shield between charger and meter and code it to simply add 20 A to the reading from meter? then I would set limit current on EV charger to 20 A and it could balance out and work as I intend?

This is more about electrical side of it than Arduino.

We can't really come up with a HW/SW design for you. If you have a HW design, or code, already, and have a certain issue, then we might be able to help with that. Please [edit] and update your question, if possible.

FWIW, what is the Feyree model number exactly? I have found user guides for F-MBM22 and EV Charging station but neither of those seem to have RS-485. I can see that there are at least a couple of other models (an 11 kV/16A/three phase, a 7.6KW/11KW/22KW model and another 7.6kW model), but can't find PDFs for those.

https://www.feyree.com/s/product-detail?productId=23010223118846420
This is the charger in question.

I believe you need to use RS485.h library.  https://github.com/arduino-libraries/ArduinoRS485/blob/master/src/RS485.h

Sounds like you want to do, what is effectively, a "man-in-the-middle" attack.
However, to do that, surely you would need two MAX3157 devices (and thus two MKR 485 shields)? One talking to the charger and one talking to the meter, with the Arduino "injecting" the "20A" message into messages from the meter to the charger. Yes, it sounds possible.
However, if you tried to use two MKR 485 shields (assuming that they are stackable), you will quickly discover that both shields use D6 and D7 for TX and RX - you can not configure this using jumpers or from software. So there would be a conflict - you wouldn't be able to address the shields independently.  Therefore, a design using the MKR 485 doesn't seem possible. You need to think of something else.
Maybe you could design a custom PCB, or breadboard, using two MAX 3157 ICs (and not the MKR 485 shields), that you can enable and address independently, using additional digital pins for the addressing. Alternatively, use one shield in conjunction with an additional custom circuit for the other MAX 3157.

I expect RS485 devices to use specific communication protocols, which frequently have some addressing feature. So one bus suffices, if EV charger and energy meter are set to different addresses. The Arduino will play the role of the EV charger for the energy meter, and vice versa. The MITM attack works then on the protocol level, not the electrical level.

That's really helpful. I know that power meter is addressable, not sure about the charger. So basically I need to use MAX 3157 to read needed registers from power meter and store it in Arduino's memory as a float (adding 20A in the meantime). Then charger needs to speak with Arduino (via another MAX 3157 or using addressing) and ask for these registers thinking it speaks with power meter, correct?

RS-485-based protocols are typically single master: the master queries a slave, and the slave responds only when it has been addressed. If you add an Arduino that can behave as a master, then you will risk collisions on the bus. Collision detection and mitigation can be implemented, but I doubt the charger does that.

@EdgarBonet I stand corrected respective the single bus. Thanks!

@thebusybee: If the charger sends its requests on a predictable timing, maybe the Arduino could manage to send its own requests in-between the ones from the charger, and your scheme could still work.


text:
Using Excel to communicate to an Arduino to light 20 LEDs
I want to show progress on a wall using LEDs from data added in an Excel speed sheet.
I want to have about 20 different LEDs maybe more. Can this be done with an Arduino Uno?

You need to find out, if you can send data via Serial COM port in Excel via its macro language. I don't know and it would be out of scope here (since we are experts in Arduino, not Excel). If Excel is capable of that, there is no reason why it shouldn't work.

Just googled it, if you write code in Excel VBA you can absolutely use a serial com port. So yes, it can be done

To add to that which chrisl has explained on the Excel side - on the Arduino side you would need a sketch that then reads the serial port and receives the info sent from Excel, decodes that data and triggers the LEDs correspondingly. If you can write that sketch and then have issues, then you can ask a more focused question regarding the Arduino code. However, as it stands, aside from just asking whether it can be done (to which the answer is "yes"), your question is otherwise too broad (if you also want to know how to do it).

Also, to light 20 LEDs you might need a multiplexer or decoder, as there probably aren't enough pins on an Arduino Uno for a one-pin-per-LED solution. Although, you could use an Arduino Mega, which has loads of pins - so you could have more than 20 LEDs (54 in fact) and still use a one-pin-per-LED solution.

@Greenonline The Uno has 20 pins: 0 to 13, A0 to A5. A bigger issue might be current consumption. Also a much better response would be to post an answer. Do you want this site littered with unanswered questions?

We get pestered by the Stack Exchange bot if questions go unanswered. So @chrisl and Greenonline, please help out by making actual answers.

@NickGammon -  I understand what you mean, but: D0 and D1 would be used by the serial port that the user needs; Every time I (or anyone) posts an answer it gets down votes by the (not so) mystery voter (we all know who it is); The question was about to be closed; The close vote limit needs to be increased from 3 to 5; The question was vague and/or broad, so an answer would have had to be long and rambling, thus it seemed better to offer a little partial guidance in the comments rather than no answer at all.  I like trying to help but this particular site seems to have some issues, sadly.

@NickGammon - If you want to reopen the question (I've just voted to reopen), I'll gladly put my comments in an answer (and take the -2 rep hit).. I could also add something about current consumption, unless you would like to post an additional answer about that (which might be better to be honest)

@Greenonline I've reopened it, and I'll upvote your answer to partly compensate for you-know-who. I agree you need the serial port for uploading sketches, but that doesn't really preclude you from using them for other purposes later. I also agree about the 5 votes, I thought we were doing something about that. You could mention the 74HC595 chip as an alternative way of doing it in your answer if you wanted.

the title is about Excel so if the answer is about the LEDs, the Q and its title should be edited. I couldn't decide which of existing Q&A about LEDs would be a duplicate, because of different ways how to do it. so the Q is too broad even if limited to the Arduino part.

@NickGammon - Ok, I think I've covered the basic principles, in my answer, without going down to design level (too broad). Thanks.

Hi this is my first question I have asked and the help that has been given is great.
this has given me loads to think about and loads to learn. thank you all for your help its really appreciated. always learning.

This really is a question of two parts:

"Can I communicate to the Arduino using Excel?", and;
"How can I light 20 LEDs using an Arduino Uno?"

Considering each aspect in turn...
Excel side
To add to chrisl's comment, which (partially) explained the Excel side:

... if you write code in Excel VBA you can absolutely use a serial com port. So yes, it can be done

Arduino side
Pin supply considerations
On the Arduino side you would need a sketch1 that then reads the serial port and receives the info sent from Excel, decodes that data and triggers the LEDs correspondingly.
Also, to light 20 LEDs you might need a multiplexer or decoder, as there probably aren't enough pins on an Arduino Uno for a one-pin-per-LED solution - there are twenty pins, but you will be using two of them (D0 and D1) for the serial communications via the serial port/monitor. Although, as Nick mentions in his comment, you could still use the Tx and Rx pins for the LEDs, but they would flicker during any serial communications.
With respect to using a multiplexer or decoder (there are a lot of different avenues that you could take2), as Nick also suggested, you might want to consider a shift register (such as a 74595).
Please refer to Serial to Parallel Shifting-Out with a 74HC595, from whence the schematic diagram below was sourced, for more information:

Current considerations
Using additional circuitry would also help alleviate another, as yet unconsidered, issue which is current draw. Unless you use low current LEDs, you might find the Arduino Uno struggling to supply sufficient current to power twenty LEDs.
Each pin on the Arduino Uno can supply 20 mA. However, the overall current draw should not exceed 200 mA..! Considering that one standard LED (whatever "standard" is or means) draws between 10 and 30 mA, so going for the low side, you could/might be able to light 20 LEDs. Nevertheless, you are nearing the limit and may be pushing it under certain scenarios. Using external "buffer" circuitry would prevent your Uno (and/or the regulator) from heating up and/or overheating.
Alternative Arduino solution
However, you could use an Arduino Mega, which has loads of pins - so you could have more than 20 LEDs (54 in fact) and still use a one-pin-per-LED solution.

Footnotes
1 If you can write that sketch and then have issues, then you can ask a more focused question regarding the Arduino code. However, as it stands, aside from just asking whether it can be done (to which the answer is "yes"), your question is otherwise too broad (if you also want to know how to do it).
2 Other methods of multiplexing include:

Charlieplexing, which allows you to control (n2 - n) LEDs with n pins, with little or no additional hardware/ICs. With 18 pins you could control 308 LEDs, although current supply issues would obviously arise, and need to be resolved.
Using a TLC 5940, 16-channel LED driver (which can be chained)

See also How can I effectively drive multiple LEDs with multiplexing?

LED matrix, I2C strips, Neopixels?

Comments have been moved to chat