text:
Extracting char array out of function
I have a array called Table1 witch contains '1','2','3','4'
I do not want to work with global variables
I want to change the content of Table1 with a function called 'Change' that gives a return char array back in to Table1
This is the program i wrote:
void setup()

{
  Serial.begin(9600);
}

void loop()
{
  char tabel1[4] = {'1','2','3','4'};
  int i;
  for (i = 0; i <= 3; i++)
  {
    Serial.println(tabel1[i]);
  }

  tabel1 = Change(tabel1);

  for (i = 0; i <= 3; i++)
  {
    Serial.println(tabel1[i]);
  }
}

char Change(char tabel2)

{
  tabel2[0] = 'n';
  tabel2[1] = 'b';
  return tabel2;

}

This is the error i'm getting:
In function 'void loop()':
testArray:17: error: incompatible types in assignment of 'char' to 'char [4]'
tabel1=Change(tabel1);
^
In function 'char Change(char*)':
30:12: warning: invalid conversion from 'char*' to 'char' [-fpermissive]
return tabel2;
^
exit status 1

[Error] Exit with code=1

Did you mean table or tabel??

I'm dutch and table in dutch is tabel so yeh XD

You should read something about C arrays and how they work.
Anyway, if you use:
  Change(tabel1);

// ...

void Change(char * tabel)
{
  tabel[0] = 'n';
  tabel[1] = 'b';
}

It'll change passed array because it's passed as pointer to the first element of tabel1.

In c an array's name is effectively a pointer to the start of the memory location where the array is stored. You have to be careful, if you pass an array to a function that function will have no knowledge of the array size. If there is a risk of the size being unknown you normally pass a second parameter, the size of the array. In this case we will assume the array passed to change is always at least 2 chars long and risk a crash if it isn't.
At the most simple level your change function becomes:
void Change(char tabel[])
{
  tabel[0] = 'n';
  tabel[1] = 'b';
}

and the line to call it is:
Change(tabel1);
Notice how there is no return type or return value. We were passed a pointer to where the array is in memory. When we make changes to the values we are changing the original array directly. The old values are lost.
The function:
void Change(char *tabel)
{
  *tabel = 'n';
  *(tabel+1) = 'b';
}

Is functionally identical to the one above only it is explicitly using a pointer rather than an array.
One thing you need to get used to in c is that an array is not a type of variable, it's a collection of variables. As such normal variable operations don't work on them.
e.g. array1 = array2 does not set the contents of array 1 to being the same as array2. It sets the memory address where array1 is stored to being the same as the memory address that is used for array2. The original memory used to store array1 is no longer accessible by the program and is now unusable. This is a bad thing.
Similarly if (array1 == array2) doesn't compare the contents of the two arrays, it compares their memory addresses.


text:
if-else statement not working
So I'm facing this problem a lot in my code where the program is not getting into the if else loop properly and just returning the same answer again and again.
void loop() {

double X_value = ((double)(analogRead(X_pin)-487))/540.00;
double Y_value = ((double)(529-analogRead(Y_pin)))/540.00;

double theta_rad = atan((double)Y_value/(double)X_value);
double theta_deg = ((double) theta_rad)*180.00/3.1416;

double temp = (double)abs(tan((double)theta_rad));
if (temp == 0.00) {
temp2 = 0.00;
} else {
  double temp2 = min(temp,1.00/temp);
}

Serial.print("Theta = ");
Serial.print(theta_deg);
Serial.print("\n");
Serial.print("temp 2 = ");
Serial.print(temp2);
Serial.print("\n");

delay(1000);

}

The answer keeps on coming 0 even when temp is non zero.

If anyone knows the reason please help...

Please edit your question to show actual code used.  What's there now has a compile error with temp2 not declared before use.  Note, the temp2 declaration shown in the else branch has scope only within the else branch and is not available outside it.

Note that You may want to use atan2() instead of atan().

And also it's not a good idea to compare floats for equality, as they are not "exact" numbers. For example 0.00 can be anything between -0.0049999.... and 0.0049999..... (roughly)

The initialisation code is missing. Where is temp2 declared? and X-pin and Y_pin

You use doubles for everything and then use a value of 3.1416 for PI? 1) in arduino doubles are only 32 bit floats not true 64 bit doubles so the constant casting to double is unnecessary. 2) a 32 bit float is accurate to more than 5 figures so that Pi value is the limiting factor in your accuracy.

I'm assuming that temp2 must be defined as a global or you'd be getting compiler errors.
You are re-defining temp2 within the else statement, that redefined value is then only local to that else and is lost as soon as you exit it.
void loop() {

double X_value = ((double)(analogRead(X_pin)-487))/540.00;
double Y_value = ((double)(529-analogRead(Y_pin)))/540.00;

double theta_rad = atan((double)Y_value/(double)X_value);
double theta_deg = ((double) theta_rad)*180.00/3.1416;

double temp = (double)abs(tan((double)theta_rad));

if (temp == 0.00) {
  temp2 = 0.00;
} else {

/* Bug here.                                                             */
/* this temp2 is local to these {} and is lost as soon as we reach the } */
/* at the end of the else.                                               */
/* Remove the word double and it should work                             */

  double temp2 = min(temp,1.00/temp);
}

Serial.print("Theta = ");
Serial.print(theta_deg);
Serial.print("\n");
Serial.print("temp 2 = ");
Serial.print(temp2);
Serial.print("\n");

delay(1000);

}

Personally I'd replace the entire if ... else with:
double temp = abs(tan(theta_rad)); // removed redundant casts to double

double temp2;
if (temp > 1.0) // 1/temp will be smaller if temp > 1
  temp2 = 1.0/temp;
else
  temp2 = temp;

It'll have exactly the same effect but avoids unnecessary floating point calculations

source: Stack Exchange

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

sort: votes


text:
Arduino not recognizing when a timer reaches 0
Alright, so I'm attempting to make a timer that will turn on a light after an hour. Currently I have it set to 5 seconds for testing. What is happening is whenever I start the program it won't recognize when the timer reaches 0.
Here is my code
/*
Hour Alarm
An hour long alarm that allows breaks
Created by: Jaxon Reid
Last Edited: 19/5/2017

Pins:
Pin 13 = Led
Pin 2 = Button
*/
int secLeft=5;
const int led=13;
const int button=2;
const int buttonIn=4;
int buttonValue=0;
// Declares the button to reset as 2 and the lightbulb on pin 13
//the secLeft means the seconds until the light turns on and button value is for wether or not the button is pushed

void setup() {
  Serial.begin(2400);
  Serial.print("On  ");
  pinMode(13,OUTPUT);
  pinMode(button,OUTPUT);
  pinMode(buttonIn,INPUT);
}
// makes the led pin an input and opens the channel for the debugger
void loop() {
  int buttonValue=digitalRead(button);
  Serial.println("Checking time");
  if (secLeft<=0) {
    Serial.println("No time remaining");
    digitalWrite(13,HIGH);
    Serial.println("Light On");
    // If the time remaining is 0 then turn on the light
  }
  if (secLeft>0) {
    Serial.println("Time Remaining");
    digitalWrite(led,LOW);
    secLeft=(secLeft--);
    Serial.println(secLeft);
  }
  if (buttonValue==1) {
    int secLeft=5;
    Serial.println("Reset Timer");
    Serial.println(secLeft);
  }
  delay(1000);
}

Whenever I start it up it just starts reading
On 5
Checking time
Time remaining
5
Checking time
Time remaining
4
Checking time
Time remaining
3
Checking time
Time remaining
2
Checking time
Time remaining
1
Checking time
Time remaining
0
Checking time
Time remaining
-1
Checking time
Time remaining
-2

etc...
So where did I go wrong is what I'm asking.
Thanks!

The problem is int secLeft=(secLeft2--); where you are creating a second variable called secLeft within the scope of the if block.  Ditch the int.  This is the second question I have seen with this issue in the last 30 minutes.  You probably also have the same issue with secLeft2

Now its not decreasing the secLeft at all

Noter that you still have an int secLeft in the reset section

As per comment and Majenko's answer you are current creating local variables called secLeft and secLeft2 inside the 'if block.  These take precedence over the ones you have defined globally.  Removing the in declarations from inside the if block will stop doing that and point you at the globally defined variables.
As to the rest of the code. If you have
secLeft=(secLeft2--);
secLeft2=(secLeft);

Then that translates to this sequence of instructions

Assign secLeft with the value of secLeft2
Decrement secLeft2
Assign secLeft2 with the value of secLeft

And in the end you do not change anything.
This is because you are using post-decrement on secLeft2  EG secLeft2--.  This is a feature of C style languages.
I am not sure what you are even trying to do at this point.

Got it thankyou I was thinking it would decrement beforehand

To get pre-decrement you have to do --secLeft.  C and C++ have both and they are both useful in their own way.

int secLeft=(secLeft2--);
int secLeft2=(secLeft);

You are making 2 new variables there instead of using the existing ones.

alright how do i fix that?

By not declaring new variables.

I have picked this up yesterday i learned C++ yesterday aswell what do i remove?

Remove the int from each line. Also, do you really want to reset secLeft2 to what it was before decrementing it? The second line looks a bit daft.

Now i just get 5,5,5,5,5 ...

Edit your question and add your updated code to the end so we can see what you have done.

I think you are getting muffled with your variables. There is no reason for secLeft2 to even exist.

I created secleft 2 cause before when i had secLeft=(secLeft--) i was afraid it was looping and reducing it to 0 immetiately btw codes updated

That format is incorrect but not wrong.  It has a redundant assignment since secLeft-- subtracts one and saves the result.

Besides problems mentioned in other answers, your use of button and buttonIn variables is messed up.
With button equal to 2, the pinMode(button,OUTPUT) statement initializes pin 2 to be an output.  Pin 2 is low after reset and pinMode() doesn't change it.
When you say int buttonValue=digitalRead(button); the low value at pin 2 will be read into buttonValue.  In the sketch, buttonValue will never be anything but low.
To fix this problem, get rid of buttonIn, and in setup() use pinMode(button,INPUT) to set button to be an input, not an output.

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


text:
Listen for specific frequency
I’m trying to build a custom baby monitor for my wife who is deaf. It needs to detect loud noises and listen for a specific series of tones from a feeding pump our daughter uses.  It will then send a radio signal to the other room to trigger a bed shaker.
I do have a loop which samples the MAX4466 microphone and uses a “peakToPeak” calculation to determine volume, which I can use to trigger for loud noises (pasted below).  However, I cannot figure out how to determine the frequency of a noise sample.  I’ve tried searching for other sketches and tutorials that would work, but haven’t found anything.  The feeding pump, when it has an error puts out a series of tones which alternates between 4.1 kHz and 2.1 kHz.   What I wanted to do is see if the first tone is sounding, and then if the second tone shows up within a couple seconds afterwards, then it would trigger sending the signal to the other device.
I’ve tried for two days now to find a way to determine the frequency, but haven’t figured it out.  Any help would be greatly appreciated.  The closest I was able to get was this: Instructables - Arduino Frequency Detection, but when I use this script, the Arduino can no longer do analogRead() to get the status of various setting knobs and such I have on the device.
The script I use to get the sound level / loudness is:
  #define micPin 0                      // Microphone
  const int sampleWindow = 96;          // Sample window width in mS (50 mS = 20Hz)
  unsigned int sample;
    while (millis() - startMillis < sampleWindow) {
      sample = analogRead(micPin);
      // Check peakToPeak mins and maxs
        if (sample < 1024) {
          // toss out spurious readings
           if (sample > signalMax) { signalMax = sample; }          // save just the max levels
           else if (sample < signalMin) { signalMin = sample; }     // save just the min levels
        }
    }
    peakToPeak = signalMax - signalMin;  // max - min = peak-peak amplitude

I don't have enough info to write a proper answer, but I suspect you're going to have to use something like a (fast) Fourier transform or a discrete cosine transform to get frequency information from real-world inputs. The article you link to uses (from a quick skim) variations on zero-crossing, which will go wrong as soon as you get background noise or multiple frequencies. A quick Google for "arduino fft" gave some hopeful-looking results. I hope that gives you something to get started. Good luck.

Might be able to use a Frequency-to-Voltage Converter http://www.analog.com/media/en/technical-documentation/data-sheets/ADVFC32.pdf

it would be a lot more practical to pipe the audio to a real computer and use fancy audio libs to achieve your goal. i guess a raspPI is "real" enough. look for "frequency bargraph" examples since they do everything you need and a tiny bit more (visualization)

I think the FFT solution is the best for your solution but... I usually find it more reliable to open the device I want to monitor and hook up a sensing point there (be it a transistor, an optocoupler, an op-amp, ...). If the alarm sound is the only one the feeder plays, you can just get the signal of the buzzer, filter it out a bit and you will have a digital signal for your arduino..

As stated in previous answers, frequency measurement is unlikely to be
reliable because the microphone is going to pick up ambient noise, which
is a combination of many individual frequencies. You want instead to see
how much sound amplitude you have at the specific frequency of the
feeding pump. Fourier analysis seems like the natural tool for the job.
However, a Fourier transform is heavy math, and overkill for your
application. You are only interested in the Fourier amplitude at one
specific frequency. Computing that single amplitude is way easier and
faster than doing a full-fledged Fourier transform.
My preferred method for doing that is called homodyne detection. It
is fast enough to be done in real time by an Arduino Uno sampling at
9.6 kHz. Basically you multiply the input signal by both a sine and
a cosine at the target frequency, then you low-pass filter both
products. The two resulting signals are the real and the imaginary part
of the complex amplitude you are looking for.
Here is a small program of mine that does almost exactly what you are
looking for: homodyne.ino. It is set for one specific frequency
(1 kHz, but it's trivial to change), and you will have to adapt it
to be able to change the target frequency between 4.1 and 2.1 kHz.

You can use a DFT(Discrete Fourier transform) that just checks the component frequency magnitude at 4.1kHz and 2.1kHz. Below is some code that works for my Arduino UNO. When I put a signal generator on A0 with a 2.3V(peak to peak) sine wave, the result goes above 0.5 at the respective frequencies.
float Single_Point_DFT(int16_t inputArray[], int startingIndex, int endingIndex, float sampleFreq, float freqToSampleFor){
  float N = endingIndex - startingIndex + 1; //N=number of samples
  float k = freqToSampleFor * N / sampleFreq;
  float radiansPerSample = 2.0 * 3.14159 * k / N;

  float RealSum = 0;
  float ImaginarySum = 0;
  for (int n = 0; n <= endingIndex - startingIndex; n++){
    float angle = n * radiansPerSample;
    float voltage = inputArray[startingIndex + n] * (5.0 / 1023.0);

    RealSum += voltage * cos(angle);
    ImaginarySum -= voltage * sin(angle);
  }

  return sqrt(RealSum*RealSum + ImaginarySum*ImaginarySum) / N;
}

const int analogInPin = A0;
uint32_t startTime_uS;
uint32_t endTime_uS;

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

void loop() {
  int16_t values[128];

  while(1)
  {
    startTime_uS = micros();
    for(uint8_t n = 0; n<128; n++)
    {
      values[n] = analogRead(analogInPin);
    }
    endTime_uS = micros();

    float sampleFreq = 128.0*1000000.0/(endTime_uS - startTime_uS);
    float result = Single_Point_DFT(values, 0, 127, sampleFreq, 2100);
    Serial.print(result);
    Serial.print(", ");
    result = Single_Point_DFT(values, 0, 127, sampleFreq, 4100);
    Serial.println(result);
  }
}

This calculation is pretty slow due to the float arithmetic and the sine/cosine calculations, But is is fast enough if the beeps last longer than a quarter of a second.

single-frequency DFT or related goertzel algorithm is indeed a good idea.  But doing it with floating point math on a system without hardware support of that is a very bad idea.  Also there's no need to take the square root, you can just compare the squared value.

With a microphone listening for one frequency in ambient audio you have to do far more than just count cycles or measure time between crossings.
You have to sample a burst of audio into a buffer at a minimum of double the rate of the highest frequency you are interested in. Then you need to analyse that audio sample to determine the amplitudes of the different frequencies within it. FFT (Fast Fourier Transform) is the most popular method of doing that, and there are integer maths based libraries and examples around on the internet suitable for running on an Arduino.

Yes, in general, however 1) Undersampling and looking for the aliased frequencies is not out of the question and might be used to advantage on an underpowered system 2) computing a full FFT is not needed and probably not efficient when the desire it to find two alternativing frequency components.

A few ways, fft, 1057, or sin multification. Fft is quite calculation and space intensive, even in interfere form. For the detection of a known frequency, 1057 can be very efficient.
Multification is iterative so space and mips efficient. But you will need to filter and it detects with a delay.
A more efficient way is hardware filtering followed by rectification .

Could you give more details on “1057”?


text:
Sidestep one second log rate with NeoGPS when another sensor on the board need to log faster
The sample rate of an accelerometer, like an MPU6050, is much faster than the GPS log rate, different technology, different issues.
A common GPS Reciver has, approximatly, one second log rate.
In my specific case the accelerometer has a 100hz log rate.
With a previous code the gps log rate was slowing down the accelerometer log rate so i thought to introduce two counters:

one for the gps
one for the accelerometer

What i tried to do was:
  if ((lastLogGPS + LOG_RATE_GPS) <= micros()) {
  //Log accelerometer and gps data
  } else ((  if ((lastLog + LOG_RATE) <= micros()) {
  //Log only Accelerometer data
  }

1. Is that a speed and memory efficient solution? Or better way exist*?
2. During a 60 seconds test the board return me only the accelerometer value, never the satellites informations, i think there are some dumb errors in my code

Thanks for your help :)
This is the void loop section
void loop()
  {
    Wire.beginTransmission(MPU);
    Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
    Wire.endTransmission(false);
    Wire.requestFrom(MPU,14,true);   // request a total of 14 registers
    AcX=Wire.read()<<8;
    AcX|= Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
    AcY=Wire.read()<<8;
    AcY|=Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
    AcZ=Wire.read()<<8;
    AcZ|=Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
    GyX=Wire.read()<<8;
    GyX|=Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
    GyY=Wire.read()<<8 ;
    GyY|=Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
    GyZ=Wire.read()<<8;
    GyZ|=Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
    if ((lastLogGPS + LOG_RATE_GPS) <= micros()) {
    while (gps.available( gpsPort )) {
    fix = gps.read();  // get the entire fix structure, once per second

    if (logGPSData()) { // Log the GPS data
    SerialMonitor.println( F("GPS logged.") ); // Print a debug message
    } else {// If we failed to log GPS
    // Print an error, don't update lastLog
    SerialMonitor.println( F("Failed to log new GPS data.") );
      }
    }
   lastLogGPS=micros();
  }
  else{
    if ((lastLog + LOG_RATE) <= micros()) {

      printImuData(dataFile,lastLog, AcX, AcY, AcZ, GyX, GyY, GyZ);
      dataFile.flush();
      }
    lastLog=micros();
    }
  }

This the function that print only the accelerometer informations:
static void printImuData(Print &printer, unsigned long lastLog,
        int16_t AcX, int16_t AcY, int16_t AcZ,
        int16_t GyX, int16_t GyY, int16_t GyZ)
{//Printing the mpu6050 information

  printer.print("0");   printer.print(",");   //0 longitude
  printer.print("0");   printer.print(",");   //0 latitude
  printer.print("0");   printer.print(",");   //0 altitude
  printer.print("0");   printer.print(",");   //0 speed
  printer.print("0");   printer.print(",");   //0 course
  printer.print("0");   printer.print(",");   //0 date
  printer.print("0");   printer.print(",");   //0 time
  printer.print("0");   printer.print(",");   //0 satellites
  printer.print(lastLog); printer.print(",");
  printer.print(AcX);     printer.print(",");
  printer.print(AcY);     printer.print(",");
  printer.print(AcZ);     printer.print(",");
  printer.print(GyX);     printer.print(",");
  printer.print(GyY);     printer.print(",");
  printer.println(GyZ);

}

And this is the part for the GPS informations:
byte logGPSData()
{
  if (dataFile.isOpen())
  { // Print longitude, latitude, altitude (in feet), speed (in mph), course
    // in (degrees), date, time, and number of satellites.

    if (fix.valid.location)
      dataFile.print(fix.longitude(), 6);
    dataFile.print(',');
    if (fix.valid.location)
      dataFile.print(fix.latitude(), 6);
    dataFile.print(',');
    if (fix.valid.altitude)
      dataFile.print(fix.altitude() * 3.2808, 1);
    dataFile.print(',');
    if (fix.valid.speed)
      dataFile.print(fix.speed_mph(), 1);
    dataFile.print(',');
    if (fix.valid.heading)
      dataFile.print(fix.heading(), 1);
    dataFile.print(',');

    if (fix.valid.date) {
      dataFile.print( fix.dateTime.full_year() );
      if (fix.dateTime.month < 10)
        dataFile.print( '0' );
      dataFile.print( fix.dateTime.month );
      if (fix.dateTime.date < 10)
        dataFile.print( '0' );
      dataFile.print( fix.dateTime.date );
    }
    dataFile.print(',');

    if (fix.valid.time) {
      if (fix.dateTime.hours < 10)
        dataFile.print( '0' );
      dataFile.print( fix.dateTime.hours );
      if (fix.dateTime.minutes < 10)
        dataFile.print( '0' );
      dataFile.print( fix.dateTime.minutes );
      if (fix.dateTime.seconds < 10)
        dataFile.print( '0' );
      dataFile.print( fix.dateTime.seconds );
    }
    dataFile.print(',');

    if (fix.valid.satellites)
      dataFile.print(fix.satellites);
  dataFile.print(',');
  dataFile.print(lastLogGPS);
    dataFile.print(',');
    dataFile.print(AcX);
    dataFile.print(',');
    dataFile.print(AcY);
    dataFile.print(',');
    dataFile.print(AcZ);
    dataFile.print(',');
    dataFile.print(GyX);
    dataFile.print(',');
    dataFile.print(GyY);
    dataFile.print(',');
    dataFile.print(GyZ);

    dataFile.println();
    dataFile.flush(); // make sure the file contains at least this much

    return 1; // Return success
  }

  return 0; // If we failed to open the file, return fail
}

Here a pic of some data returned by Arduino

*I need to load easily the *.csv whith the recorded data on matlab so i have some constraints.

I'd be tempted to go about this a different way. Check if there is data waiting on the GPS serial port, if so log GPS data. If not assume this is an IMU only time. That way you will log GPS data whenever it is generated even if the GPS rate is set to something other than 1 Hz. Also your GPS data will be at exactly 1 Hz (or whatever rate you set). If you use the arduino clock to time reading GPS data then things will get out of sync over time. You'd need a very long log file for it to matter much but it's good practice to allow for different clocks to be slightly off from each other.

@Andrew I solved moving out of the statement   if ((lastLogGPS + LOG_RATE_GPS) <= micros()) {   the statement  while (gps.available( gpsPort )) {     fix = gps.read();, but is very very slow now and is logging at one second rate very useless. By now i can log gps information, but at one second log rate, so i resolved nothing. I attached a string example [link[(http://imgur.com/a/0CWFc)

Ok, I won't recreate your whole code, but here is a logic snippet that you can use.
Let's suppose that you have 2 sensors, sensor1 and sensor2.
sensor1 is read every 10 milliseconds and sensor2 is read every 16 milliseconds.
Here is what you would do:
Make 2 global variables for your timers :
unsigned long timer1 = 0;
unsigned long timer2 = 0;

Then make 2 constants for the frequency, this example will set the frequency in milliseconds.
const int frequency1 = 10;
cosnt int frequency2 = 16;

Then in your void loop, you would do something like this:
void loop () {
    if (timer1 + frequency1 >= millis()
        read(sensor1);
        timer1 = millis();
    }

    if (timer2 + frequency2 >= millis()
        read(sensor2);
        timer2 = millis();
    }
}

This method makes sure that your code isn't going to get stuck anywhere. I would also suggest to remove any while loops because of that danger that it might freeze& your code.

Yep i made 2 global variabiles and defined the frequency, but i did not attached that part of code.  The While is inside the GPS loop, and Arduino doesn't write any data from the GPS(because It seems is Never satisfied the if condition for the GPS, or another sort of problem). More over  i am not sure the GPS will works without the "While" statement,  until now or with tinygps or neogps that Command is widey used in the tutorials :)

The suggested code will fail after some time, please read the answer to this question and update your code example accordingly.

@PatrickTrentin : This is a logic snippet, not a full code, we don't write full code for people here on SE.

@DatHa are you really arguing that it is fine for an  answer on S.E., viewed by who knows how many people, to contain a not-so-obvious implementation bug, especially for the hobbyist audience that is typical for Arduino?

@PatrickTrentin : my answer is mean't to give a direction, not the full map. Eventually, when they find that problem, they will search that question up and land on the question that you found. I am not arguing that my code is perfect, I'm just saying that this is not mean't to cover all the problems in the world. I can name many more if you really wanted to. But as I said, this is just pointing someone on the right path because here, on SE, we don't write full code for people, no matter what. So either stop complaining or write your own answer.

@DatHa I actually never asked you to write full code of any type, I simply suggested a quality improvement that is holding back my upvote.

@DatHa i implemented yet your suggestions(before reading your answer but are not useful in my case, i see on git hub that i have to use a format like while (gps.available [...])). By now I partially solved the problem, as you can see reading the comment above but, i log at one second rate (i think the limit is gps.available)


text:
Wi-Fi module 5 GHz
What is a Wi-Fi module for an Arduino that works on 5 GHz? The ESP8266 - doesn't support 5 GHz according to:

Re: 802.11AC 5GHz
Why can't ESP8266 operate in 5 GHz since 802.11N is supported
my own experiments.

You may need to drop "Arduino" from your search term and simply look for something supporting a UART or SPI interface and having an on-board protocol engine (since running a TCP stack on an Arduino is often problematic).  Unfortunately on-board TCP stacks, while initially seeming convenient, can turn out in the long run to have severe, unfixable problems frustrating serious use.

I asked Microchip a while back if they planned to release a 5GHz WiFi module at any point in the near future. The answer was basically "No, there would be no benefit to it." For embedded systems there is no point in 5GHz since 2.4GHz is more than adequate and there are better long range solutions than WiFi (LoRa for instance).

I need to connect an Arduino to a 5Ghz Wifi hotspot. I will accept the first applicable workaround as an answer.

You may find an external module with SPI or UART interface. Arduino support for it may be lacking though. We can't do your shopping for you though.


text:
How do I interpret the esp8266 "boot mode" message?
Everytime the chips resets, we get the reason and the next boot mode.
ets Jan  8 2013,rst cause:XXX, boot mode:(YYY,ZZZ)
For XXX we can check the meaning here.
For YYY and ZZZ I am not sure but I know it has something to do with this. I think YYY stands for abc where a = MTDO, b = GPIO0 and c = GPIO.
For my ESP12E I am getting boot modes like boot mode:(1,7), thus after the reset, the code doesn't start again. It just "hangs there" forever.
I feel that it is starting the UART routine, because 1 = 001, meaning GPIO2 is at HIGH and the others are at LOW.
But maybe what I want, for it to start the setup() and loop() routines all over again is to activate the "SPI" by setting the MTDO pin to LOW and the other two to HIGH.
Can someone explain me better what are these 3 boot modes and how can I interpret the boot mode?

take the first number, and %4 to extract the boot mode. 99% of the time you want SPI flash, so the error code basically warns you that one of GPIO 0,2, or 15 is screwed up

boot mode:1 - means that you are in flashing/programming mode (GPIO0 is low) - so, your sketch isn't even running - note: I've got 2 ESP-12E's and have vowed never to buy them again - all my ESP-07's and ESP-12F's are rock solid - the 12E's are basically crap that despite being "wired" exactly the same as 07's and 12F's (same circuit with just the different modules) boot erratically into random modes, and fail half way through flashing more often than not

Isn't ESP-12F the same as ESP-12E with a different board? I think I've had that GPIO0 issue in all of them. They should have used other pin than that for boot mode. In every ESP it means that only when you know you'll not upload code anymore, should you connect GPIO0 to HIGH in order to properly configure the boot mode, that's silly. Anyway the only reasons I like ESP-12E is for the USB port, the amount of exposed pins and price.

there's no USB on the 12E, or any ESP module for that manner...


text:
Nano-like Board - Programmer Not Responding
I am trying to upload a basic sketch to my unofficial Nano-like board and keep getting this error. I understand that it is a generic connection error between the Arduino and my PC, but can't figure out why it is having this problem.

Semi-compatible nano-like board
Drivers
Arduino IDE 1.8.3 freshly installed
Windows 10 64-bit
Also tried on Mac OSX with the same result

I've looked up the drivers from the manufacturer's website and installed them, and the Arduino Nano shows up just fine under my Device Manager. The green power light comes on, it is recognized by my PC, and blue flashing 'L' light blinks, making me think that the manufacturer had uploaded the Blink sketch to test it. However, when I try to upload a sketch from the IDE I get this error:
avrdude: stk500_recv(): programmer is not responding

Under 'Tools" I have the board set to 'Arduino Nano', the processor set to 'ATmega168' and the port the same COM port as what it's listed as in Device Manager. Assuming that all of those are correct, I have tried a few things with no luck:

Reinstalling the IDE, drivers and restarting my computer.
Letting Windows find its own driver.
Pressing the 'reset' button just before hitting 'upload' in the IDE
Using different micro USB cables and USB ports on my computer.

Any other ideas or is the unit possibly just faulty?
Please note that I have already at similar questions and tried a bunch of their suggestions with no luck.

Isn't the device ATMega328?

@user43648 The chip on the board says ATmega168PA, but I have tried both with no luck.

Maybe you have to burn the Arduino Bootloader to it? You would another Arduino (Uno, Nano, whatevere) or a ICSP (in curcuit serial programmer) to do this.

This is a generic message, yes, so there are several possibilities.  1) that port was somehow busy with another program  2) bad cable  3) bad board, or maybe the PC is confused and a reboot will straighten it out.  Presuming you have rebooted then maybe try switching boards and/or cables..

The Arduino.cc developers changed the bootloader on official Arduino Nanos to communicate at a different speed. Try setting Tools → Processor → ATmega328P (Old Bootloader)

That is a Chinese NANO clone, using the notorious CH340G chip.
macOS does NOT have a driver, and it is difficult, if not impossible to get a driver which 1. macOS will let you install, and 2. Actually works.
I do not know the state with current Windows.
In my experience, in addition to poor support the chips are unreliable and fail to respond.
You could try using a Uno as ICSP, bypassing the boot loader, or (untried) use an external USB serial interface. Both of these approaches are documented on the Arduino site.

The official website offers a mac version: http://www.wch.cn/download/CH341SER_MAC_ZIP.html Is that not good enough ? In Windows and linux the CH340G is very reliable.

There was a problem with the official CH340 driver not being compatible with macOS Sierra but I see there was a new official release since that time so hopefully it's fixed. You can also find a fixed unofficial version with a few minutes of searching: CH340 has always worked great for me on Windows. The only problems people have is that the driver isn't included with the Arduino IDE but it only takes a minute to download and install the driver.

For issues like this, you have to narrow down the problems first. For example
is the computer plus programmer combo able to program any avr? If so, the issue us with your target, including wiring.
If not, can the programmer able to program any chip? If so, the issue is with your pc plus programming software.
...
Going backwards and with solid logic, which means making zero assumption, you will narrow the issues down further.

It's a wiring problem (soldering), check by multimeter (continuity mode).
between RST and GND. Then between ICSP pins. you have to get (1) that mean no shorts between the PINS.
Good luck!

No, it's not.  Your post shows a complete disregard for the actual contents of the question.  ICSP is not involved here. Please read more carefully next time!

@Ziad please provide more content to your answers to make them more useful for others with the same problems.


text:
What is the meaning of the preceding character on several library defines?
I have been reviewing the code for several libraries,mostly by SparkFun, and looking at the defines for for instance the chip select pins for their hardware.
In the defines, rather than being a simple number or string, they have the following syntax:
#define P_MOSI  B,3

with others being preceded by a D instead.
I am surmising this may be a data type definition, but I don't recognise the syntax and am wondering

What does the syntax mean?
What is the effect of nominating the data type of a define?
Is this Arduino specific syntax or general to C/C++?
If I want to modify a value, is it as simple as changing the value after the comma?

That completely depends on where it's actually being used.

I looked into one of these libraries, namely the SparkFun CAN-Bus
Arduino
Library.
The macro appears to be used inside other macros that require two
arguments, for example RESET(P_MOSI);. Given the following
definitions from the library:
#define RESET(x) _XRS(x)
#define _XRS(x,y) PORT(x) &= ~(1<<y)
#define PORT(x) _port2(x)
#define _port2(x) PORT ## x
#define P_MOSI B,3

the call RESET(P_MOSI); expands to
PORTB &= ~(1<<3);

PORTB is the name of an IO port of the MCU which controls the outputs
of the pins. It is actually a macro from
avr-libc that expands to something
like:
(*(volatile uint8_t *)(0x05 + 0x20))

where 0x05 is the IO port number of the register (the number depends
on the particular AVR chip) and 0x20 is an offset needed to get the
memory-mapped address from the IO port number. When the compiler does
constant folding, RESET(P_MOSI); resolves to
*(volatile uint8_t *)0x25 = 8;

which is then compiled into
cbi 0x05, 3

a single assembly instruction (Clear Bit in Io port) that executes in
two CPU cycles and sets to zero the bit 3 of IO port 0x05.
The same end result could be achieved in a much simpler way:
#define P_MOSI 11  // assuming digital 11 = PB3, as in the Uno
#define RESET(x) digitalWrite(x, LOW)

However, the function digitalWrite() is very slow, mostly because it
has to map an Arduino pin number to a port address and a bit number, and
it does it at run time. The SparkFun approach, though somewhat
convoluted, is way more efficient, because the mappings are performed
at compile time.

#define P_MOSI  B,3

This is a C style macro definition. During the pre-processor phase of compilation where ever the text P_MOSI is encountered it will be replaced with the text B,3.
This is a purely textual replacement with no understanding of the semantic meaning of what is being replaced.  So the validity of the macro will depend on where it is being used.
I am not familiar with how this macro is being used in the library code you are looking at, but from what I have seen from a quick google this macro is used to define things on a per-chip architecture basis.  EG for an ATmega16 it is
#define P_MOSI  B,5

But for a AT90USB82 it is
#define P_MOSI  B,2

So if you are trying to adapt a library to your processor you will need to change the macro to suit your architecture.
In general such defines are used to adapt the same code across multiple architectures.  For instance here is a snippet of something I found when googling
#if (BUILD_FOR_MCP2515 == 1)
    #if defined(__AVR_ATmega16__) || defined(__AVR_ATmega32__) || defined(__AVR_ATmega644__)
        #define P_MOSI  B,5
        #define P_MISO  B,6
        #define P_SCK   B,7
        #define SUPPORT_FOR_MCP2515__
    #elif defined(__AVR_AT90USB82__) || defined(__AVR_AT90USB162__)
        #define P_MOSI  B,2
        #define P_MISO  B,3
        #define P_SCK   B,1
        #define SUPPORT_FOR_MCP2515__

That is what I thought as well, in which case it must be arguments to a function, elements in a list/array, have another define for the B and D symbols. If that's the case then that's kind of complicated. It seems to be nonstandard if you've never seen it before.

@JCollins: Most things after #define should be considered non-standard.

@JCollins I have a bucket load of experience with C/C++ but virtually zero with Arduino.  In fact I only wrote my first Arduino program yesterday.

The is exactly what I am looking to do, connect a piece of SparkFun hardware to a MEGA 2560. I have made what I think are the necessary changes, but the unit still does not communicate, leading to the question.

While we can't see how the macro is being used, it may be worth noting that, on Uno's built-in SPI interface, the MOSI signal is on port-B, bit 3.
Update:

the architecture is broken down into ports and pins.

The AVR processors use memory-mapped, byte-wide I/O ports, where each bit mapped to a physical pin (actually to a multi-function pin-driver/receiver). The Arduino programming environment defines symbols such as PORTB to be the addresses of those ports. It further defines single-pin I/O functions (digitalRead(), digitalWrite() ) that "know" the mapping of pin numbers to ports and bits as implemented in each processor. Most people rely on the single-pin functions but the ability read and write the ports directly is there if you need it. And note that the Arduino pin numbers do not match the physical pin numbers of the pins at the exterior of the chip, but it does match the numbers silk-screened on the PCB. While this relieves you from having to deal with that mapping, it makes those low level details somewhat less visible.

Here's some interesting information, that the architecture is broken down into ports and pins. Perhaps now I need to find the translation between pin/port numbering and the board's own printed numbering.

As in found here: https://www.arduino.cc/en/Hacking/PinMapping2560. This seems to be a step forward..!


text:
Serial.read() always returns 255
So I'm trying to learn basic Android app dev. My master plan was to make an app using MIT App Inventor that would turn on an LED over Bluetooth using an Arduino. Once I verified that everything worked, I would write the entire app from scratch using Android Studio. This way, when I inevitably run into bugs with my written-from-scratch app, I could say with 100% certainty that the issue is in my Android code and not hardware/Arduino related.
So I'm having trouble right now. I have two separate LED circuits, a blue LED from port 13 and a green LED from pin 8. I verified that both circuits are working properly by using the Blink code, so I know the issue is definitely not with the LED circuits.
I'm using an HC 06 Bluetooth module. The pins are connected as follows:
HC 06 -> Arduino
RX -> TX
TX -> RX
5V -> 5V
GND -> GND
Here is the Arduino code:

#include <SoftwareSerial.h>

SoftwareSerial bluetooth(0,1);
int ledblue = 13;
int ledgreen = 8;
int tx = 1;
int rx = 0;
int type;

void setup() {
  Serial.begin(9600);
  //bluetooth.begin(9600);
  pinMode(ledblue, OUTPUT);
  pinMode(ledgreen, OUTPUT);
  pinMode(tx, OUTPUT);
  pinMode(rx, INPUT);
  allpinslow();
}

void loop() {
  int i = 0;
  int m = 0;
  delay(500);
  if (Serial.available() > 0) {
    while(Serial.available() > 0){
      type = Serial.read();
      Serial.println(type);
    }
    Check_Protocol(type);
  }
}

void allpinslow()
{
  digitalWrite(ledgreen, LOW);
  digitalWrite(ledblue, LOW);
}

void Check_Protocol(int inStr) {
  int i = 0;
  int m = 0;
  if (inStr == '0') { //Led Off equals("2off")
    allpinslow();
  }
  if (inStr == '1') { //Led on
    digitalWrite(ledblue, HIGH);
  }
  if (inStr == '2'){
    digitalWrite(ledgreen,HIGH);
  }
}

Here is the MIT App Inventor block code

If I press the Green or Off button, the Serial Monitor spits out 255. If I press Red, nothing shows up on the serial monitor. I'm a bit dumbfounded on what is broken so I would greatly appreciate any help I can get.
Edit: @Delta_G here is the modified code
#include <SoftwareSerial.h>
int ledblue = 13;
int ledgreen = 8;
SoftwareSerial mySerial(2,4); //RX, TX
int type;

void setup() {
  Serial.begin(9600);
  mySerial.begin(9600);
  pinMode(ledblue, OUTPUT);
  pinMode(ledgreen, OUTPUT);
  allpinslow();
}

void loop() {
  int i = 0;
  int m = 0;
  delay(500);
  if (mySerial.available()) {
    while(mySerial.available()){
      type = mySerial.read();
      Serial.println(type);
    }
    Check_Protocol(type);
    //Serial.println(inSerial);
  }
}

void allpinslow()
{
  digitalWrite(ledblue, HIGH);
  digitalWrite(ledblue, LOW);
}

void Check_Protocol(int inStr) {
  int i = 0;
  int m = 0;
  if (inStr == '0') { //Led Off equals("2off")
    digitalWrite(ledblue, LOW);
    digitalWrite(ledgreen, LOW);
  }
  if (inStr == '1') { //Led on
    digitalWrite(ledblue, HIGH);
  }
  if (inStr == '2'){
    digitalWrite(ledgreen,HIGH);
  }
}

You have a big problem here: you are using both software and hardware serials at once. I suggest you to use only the hardware serial. To do so, remove the lines #include <SoftwareSerial.h> and SoftwareSerial bluetooth(0,1);. Then tell where is the serial terminal attached (to the arduino board?) and, finally, if it still doesn't work try swapping the RX and TX wires

The HC 06 RX pin is attached to pin 1, the HC 06 TX pin is attached to pin 0. I got rid of the two lines of code, but the same exact result still occur. Swapping the pins won't work-the phone will refuse to connect to the module

Apologies for the double comment - ". Then tell where is the serial terminal attached (to the arduino board?) " I set pin 0 (the Arduino's RX pin) to input and pin 1 (the Arduino's TX) pin to output - shouldn't this tell the Arduino where the serial terminal is attached?

Your code is referencing the "Serial" object which refers to the hardware UART, not the "bluetooth" object which is a softare serial instance on the now hopefully de-conflicted pins.

Hi, I attempted to use SoftwareSerial instead. I added the updated code to my original post. All three buttons on my app still return "255" in the serial monitor. If you could check the updated code out, I'd greatly appreciate it. Thanks!

Update: It was a faulty Bluetooth module that was causing the issues. I bought a new one and everything works perfectly!

If you are using Serial then you can't use pins 0 and 1 for something else as those are the hardware serialpins. Pick different pins for the Bluetooth.

If I use softwareserial and while attaching the HC 06 TX to pin 4 and HC 06 RX to pin 2, I get the same results (255)

255 is diagnostic.  That's what you'd get if you called read() when there is no data available.

But for the life of me I can't figure out why it's not getting any data. If you look at the app's block code, it is clearly sending 48, 49, and 50 yet the Arduino isn't getting anything

Show the new code with the new pins.  Who is doing the sending?  The bluetooth?  Are you reading the software serial instance?  Or are you just reading from Serial like in the code you posted?

I added the new code to my original post

And to answer your question, the app is supposed to send either 48, 49 or 50 to the Bluetooth module. The Bluetooth module then sends it to the Arduino, and depending on what value it got, it'll turn on one of the LEDs or turn them both off.

@Delta_G actually the value for no data available is -1; and the data types involved would appear to represent that correctly, rather than misinterpret it as 255, but perhaps you have a specific theory as to how that misinterpretation could arise?  Also note that the read only appears to be performed if a check for available data returns true.

Oh, I'm sorry.  I'm used to seeing people read into a 8bit variables.  I didn't realize this one actually read into an int.

From reading the comments, I assume you are using an Arduino Uno,
and you have a PC (or Mac, or any type of computer) connected to its USB
port, and an Android device at the other end of the Bluetooth link.
I can't see what is wrong with your sketch. I will then only suggest two
methods for checking the low-level communication is working properly.
Once you know the communication is good, debugging should be easier.
Test bypassing the microcontroller
First, load an empty sketch in the Arduino, then connect the
Bluetooth module as follows:
HC 06   Arduino
───────────────
 GND ─── GND
  5V ─── 5V
  RX ─── RX
  TX ─── TX

It is important to load the empty sketch first: you do not want the
Arduino to access its hardware serial port. Now you can open your serial
monitor on the PC, set to 9600/8N1.
With this setup, the HC 06 will be using the USB/serial bridge of the
Arduino (the ATmega16U2), whereas the main microcontroller (the
ATmega328P) is just a bystander. Whatever the HC 06 outputs through its
TX should appear on your serial monitor. The data path is as follows:
┌─────────┐  Bluetooth  ┌───────┐  Serial  ┌──────┐     ┌──────┐  USB  ┌────┐
│ Android │ ──────────→ │ HC 06 │ ───────┐ │ 328P │ ┌─→ │ 16U2 │ ────→ │ PC │
└─────────┘             └───────┘        │ └──────┘ │   └──────┘       └────┘
                                         └──────────┘

Note the 328P disconnected from the serial link.
Test with an echo sketch
Load the following sketch:
void setup()
{
    Serial.begin(9600);
}

void loop()
{
    if (Serial.available())
        Serial.write(Serial.read());
}

then connect the Bluetooth module as follows:
HC 06   Arduino
───────────────
 GND ─── GND
  5V ─── 5V
  RX ─── TX
  TX ─── RX

With this setup, whatever the HC 06 outputs on its TX should appear on
your serial monitor and should be sent back through Bluetooth. The
data path is:
┌─────────┐  Bluetooth  ┌───────┐  Serial  ┌──────┐     ┌──────┐  USB  ┌────┐
│ Android │ ──────────→ │ HC 06 │ ───────→ │ 328P │ ┌─→ │ 16U2 │ ────→ │ PC │
│         │ ←────────── │       │ ←──────┐ └──────┘ │   └──────┘       └────┘
└─────────┘             └───────┘        └─────┴────┘

Note that the output of the 328P is received by both the 16U2 and the
HC 06. Since the Android device seems to ignore whatever it receives
through Bluetooth, the setup should work fine for debugging you app too.

For the first method, I loaded an empty sketch, reconnected the HC 06, and opened the Serial Monitor in the IDE. Nothing happened. I connected to the HC 06 via Bluetooth on a second computer, opened TeraTerm VT, set it to 9600/8N1, tried pressing the buttons on the app. Nothing happened. None of the buttons I pressed elicited a response.
For the second method, I uploaded the echo sketch and opened the Serial Monitor again. This time, all I got was one backward question mark each time I pressed a button
http://imgur.com/a/I1qaP
Is it possible the module is faulty?

Then I would conclude that you have a communication problem upstream of the Arduino.

So it potentially could be a busted Bluetooth module?
The problem with the app is that this is a dummy app written in MIT App Inventor. There is no way for me to jump into the source code and verify that everything is actually correct. I essentially have to assume that the App Inventor compiled the app properly.

I cannot say, I do not know how the Bluetooth module is supposed to work, or how you can configure it. The experiment only proves it is not sending what you expect, so it's not your Arduino sketch that is faulty. If you have a scope, you could try to look at the module's TX when sending data from your app.

I used Step 2 from here to try and test my BT module:
https://create.arduino.cc/projecthub/mjrobot/connecting-stuff-via-bluetooth-android-arduino-d0b8f1
There was no response to any AT commands. Is this a possible indication of a DOA module?

I replaced Serial.write with Serial.println in your echo sketch, which returned 255. So... I guess we came back to the same place?

@theflyingoreo: Yes, but the sketch being now reduced to the bare minimum, you know the problem is not there. I would try looking at the module's TX with a scope, if you have one. Are you sure this module is talking at 9600/8N1? I have no experience with Bluetooth, so I am afraid I cannot provide more help.

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


text:
Some questions about a RGB LED Strip project that Im planning to do
Good day all
So Im in the planning and research phase of a new project that I want to start for my car. I want to control a bunch of RGB LED strips independently from each other via a micro controller, preferably Arduino  of courese, with a breakout board or something. I am going to run this system off the car battery so the current shouldn't be an issue, I hope, but prolonged usage will most likely drain the battery quite quickly. The strips I want to control are of the following lengths:

6 x 30cm Pieces
3 x 2m Pieces

So I want to be able to control all of them individually as well as the colour and brightness individually. So here are my questions:
Is there a board that the arduino can talk to that has 27 PWM outputs?
Can one maybe use normal outputs and just HIGH Low them quickly in sequence and use an arduino MEGA?
What would the current draw be if all the colours are on full on all strips? Would  it rather be better to blink them in sequence,rather than full on, and lose some brightness to reduce current draw?
Could multiplexing here be an alternative to controlling them individually? Maybe get it so I switch all the Positive outs of the LEDs, and the connect the 3 colours together. So in that case I would have 3 + 9 outputs?
Would addressable LEDs actually work better?
If you could refer to me to similar projects so I can sniff around there that would be greatly appreciated. So far Im just trying to wrap my head around all the aspects of the project. And yes I know that I wil not be able to use this while Im on public roads, its just for show.... So not sure what the legal aspects there are... :P

There isn't any Arduino with 27 PWM Outputs ! Upto how much I know.  If you really want to use so much long RGB Led Strip that also individually all the LEDs than it's not possible I would prefer you to use NeoPixel Strips instead ! Now I can't really say much will be the current draw upto when you provide me a datasheet. Next I didn't understand that 3+9 output thing.

I think you didn't even research a bit Am I correct ?

Haha I did a little... I was looking for like a chainable breakout or some controlling device for the RGB. Yeah after thinking about it for a bit, the individually addressable LEDs might be the better, more expensive option. In that case I could just use a few pins for the data write to the different strips, and then just connect them all to power, if i understand everything correctly?

have you heard of Adafruit's NeoPixels? example

You could use chainable RGB drivers like these:

They are based on the P9813 chip and can be used with the FastLed library.
You can find them on Aliexpress or eBay, if you search for "STM32 rgb".


text:
Measuring distance based on time
I have written a arduino sketch which is used to measure the distance travelled. Since distance = speed * time , I have initiated speed = 6. I have initiated time = millis() variable and it calculates the time in millis().
So, distance is calculated as (speed*time) /1000 and we get distance for every second.
Now, as soon as the distance==20, I want to print distance and then delay for 5 seconds. So, as soon as distance==20 implies time = 4000 . If I delay for 5 seconds, time becomes 9000. But I want time to start from 4000 itself. So I have initiated another variable called curTime = time - prevTime.At the start, prevTime = 0. Code:
int prevTime = 0;
void loop(){
  unsigned long time = millis();
  unsigned long curTime = time - prevTime;
  int speed = 6;
  unsigned long distance = (speed * curTime)/1000;
  Serial.println(distance); // displays values of distance
  if(distance == 20){
    Serial.println(distance);
    delay(5000);
    prevTime = time;
  }
}

So prevTime = 4000 if distance == 20.
After this, time will be equal to 9000 and curTime will be 9000-4000 which equal 5000. So the distance will be 30 skipping all the values between 20 and 30. I don't want the distance to skip the values between 20 and 30. I have tried a lot but couldn't achieve it. Please help me fix this.
Thanks.
Link for code:
https://circuits.io/circuits/5260912-the-unnamed-circuit/edit

@JohnnyMopp, Thanks for the reply. Please see the link on how code works.When distance == 20==> prevTime=time ==> prevTime=4000(After delay). Now when curTime is calculated, it's coming as 5000 (since time=9000 and prevTime=4000). But when I keep prevTime = millis(), curTime is started from 0 again. For my output , as soon as distance==20, after the delay, again the distance should get calculated from 21, but in the above code, the distance is skipped to 30.

Thanks for the reply. I tried it earlier, but it didn't work.

This program is not measuring anything. As it stands, it is completely useless, and unlikely to be what you want. Could you please explain clearly what you actually want to do?

When distance == 20 you pause for 5 secs. So all calculations after that will be off by 5 secs. So, prevTime should equal 5000.
unsigned long time = millis();
unsigned long curTime = time - prevTime;    // 0 or 5000
int speed = 6;
unsigned long distance = (speed * curTime) / 1000; // calculating distance in meters for every milli second
Serial.println(distance);
// Only pause once
if (distance == 20 && prevTime == 0) {
  delay(5000);
  prevTime = 5000;  // Adjust for the delay
}


text:
Is Arduino Ethernet shield compatible with arduino due?
Arduino Due's operating voltage is 3.3 volt and Ethernet shield operates on 5 volt supply. So my question is that this Ethernet shield will work on an Arduino Due and also if it will not harm the Arduino Due board due exceeding the operating voltage?

The Arduino Ethernet shield (or at least V2 of it) is based on a W5500 chip which itself features "3.3V operation with 5V I/O signal tolerance".  In other words, the core of it already is a 3.3v device, just one that can tolerate connection to a 5v Arduino.
Of course the shield is more than just the chip.  A very quick look isn't showing any glaringly obvious uses of 5v levels on the board in a place where a 3.3v Arduino derivative wouldn't expect them.
However, you should review the the full schematics and make your own determination that these are applicable to the specific board you plan to use and do not place 5v level on any signal the Due could not accommodate.
It's unfortunate that the shield documentation doesn't seem to say anything about compatibility, but worth noting the the Ethernet Library has some specifics for the SAM family of chips one of which is used on the Due.

The Ethernet Shield V1 was based on the W5100 chip.  This may not have 5v tolerant inputs, as it appears to use level translation on the input side.  But it is also powered from 3.3v, so likely the outputs would be fine for a Due.  An interesting question is if the V1 shield would be damaged if connected to a 5v Arduino with a sketch that erroneously drove MISO high as an output.

Of course it will harm your due. Now for that problem you could use a 3.3v to 5v and vice versa level converter.

This is simply false.  The W5500 features "3.3V operation with 5V I/O signal tolerance"


text:
Is there any way to use the serial port as an interruption source?
I have an sketch made for reading a temp/hum sensor once every ten seconds aprox. However, I want to introduce an interruption source to send from my keyboard a magic word to make the sensor be read exactly at that instant.
By checking out the reference on attachInterrupt(), I found only the ways to declare interruption pins, but nothing related to serial. What you can say about it?
Thanks in advance.

Serial.available() or the serialEvents can be used essentially like an interrupt.

@dandavis, not really.  Those are polling methods, not interrupts.  Those two methods do not "interrupt" other things that your code may be doing.  Your code must call available frequently or, if you are using serialEvent, you must make sure that loop doesn't block.  However, in the OP's application, polling is sufficient (see gre_gor's answer).

@slash-dev: regardless of the underpinning, to the dev, they "can be used essentially like"... Specifically, there's no need here for a low-level interrupt when the "main work" is only is done every 10 seconds...

Use millis() for the timing of the temperature reading, then you can read from the serial in between time and won't need to use any interrupts.
unsigned long last_measure = 0;

const byte buffer_size = 16;
char buffer[buffer_size] = "";
byte buffer_i = 0;

// setup() and other stuff

void loop() {
    if (millis() - last_measure > 10000) { // read the temperature like in the "blink without delay" example
        last_measure = millis();
        int value = readSensor();
        Serial.println(value);
    }
    while (Serial.available()) {
        char c = Serial.read();
        if (c == '\n') { // end of line, which means we got the whole string
            if (strcmp(buffer, "magic") == 0) { // compare if it matches the magic word
                int value = readSensor(); // read and print the temperature
                Serial.println(value);
            }
            buffer_i = 0; // reset the index
            buffer[buffer_i] = 0;
        }
        else if (buffer_i < buffer_size-1) { // if the buffer is not full
            buffer[buffer_i++] = c; // add char to buffer
            buffer[buffer_i] = 0; // and null terminate the string
        }
    }
}

Thank you all, guys. I considered your ideas, and then I code this solution. It works fine, right now I'm reading my sensor once every 30 minutes (1,800,000 miliseconds) and whenever I send the magic word. I hope it is useful to you:
void loop(){
if ((millis() - timer < 1800000) && (Serial.available() > 0)){
    magicInput = Serial.readString();
    magicInput.trim(); //Cleans input from \n at the end, otherwise never equals magicInput
    if (magicInput.equals(magicWord)){     //Elegant form for "=="
      Serial.println();
      Serial.println("  === Your request ==="); //Shows requested measurement
      Serial.println(millis() - timer); //Time since last measurement
      measure(); //
    }
  }

  if (millis() - timer >= 1800000){
    Serial.println();
    Serial.println("===== Normal mode =====");  //Indicates that measurement was not requested by user
    Serial.println(millis() - timer); //Checks that 30 "exact" minutes have run
    mide();
    timer = millis();
  }
}

Serial.readString() has a timeout of 1 sec by default, so your response has an unnecessary delay. Use Serial.readStringUntil('\n') instead.

Here is a logic snippet you can use:
unsigned long timer = 0;

void loop(){
  readSensors();
  while(millis() - timer < 10000){
    if(stringFromSerial == magicWord){
      readSensors();
    }
  }
}

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


text:
Global variables with C++ in multiple files
I'm not a C++ programmer (but I have used regular C code for implementing low-level machine language equivalent SW for some time), and after trying to modify an existing cC+ program to do what I need (and failing), I've decided to rewrite parts of the code in plain C code.
But to be able to use the data, I need to create some variables that have to be accessible to parts of the existing C++ code.
When I declare a global variable (extern int variable name;) outside the main program, the compile fails because the references to the global variable aren't within the scope of the cpp parts of the program.
I don't program with multiple files myself, so I was wondering if I need to globally declare the same variables as part of each cpp program that needs to have access to the variables? Is there a another/better way?

How do I use extern to share variables between source files?

Why not just write C code but still name the file .cpp and let the C++ compiler compile it.

So you know, using global variables is not best way to compose object oriented code.  And I know where you are coming from (embedded processors with little room for extravagant C++ constructs).  But contemporary embedded processors are way more powerful than the venerable 8051 of yesterday.  And C++ is a great way to compartmentalize and isolate features to the extent they really only need to be tested once.  Then reused over and over again.  Give it some thought before you force old methods where newer approaches are starting to make sense and save money.

I just deleted my 3rd attempt to answer your question.  There are just too many assumptions that need to be made about your existing C++ code as well as your attempts to bring it all together using ordinary C.  I keep coming back to it would be better if you just learned C++.  I'll just say this, if the existing C++ classes still work for you, you should be able to use them using only formally passed values.  Why do you need to use global variable on top of that?

First, I haven't written the c code yet, just declared the new global variables, but it won't compile.

I understand the reusability of object orientated code, but I've never written any.....I really don't want to learn right now, just make some mods if possible, but because that was not successful, I thought I'd write one of the c++ parts in c code, but the global issue is stopping me. I'd really love to learn c++, but I need to get this code  modified for a project, and can't delay it for likely some months of learning......BTW, I'm 70+ years old, and have been a computer professional since 1968, mostly doing HW design......something about old dogs and new tricks, I think.

When using multiple source files you need to use header files to share things between them.
myproject.h:
#ifndef __myproject_h__
#define __myproject_h__
extern int aGlobalVariable;
#endif

myNewCode.c
#include "myproject.h"
int aGlobalVariable;

modifiedOldCode.cpp
#include "myproject.h"

This way the header file defines the variable as an extern in all of your c / cpp files so that it is visible to all of them but the variable is only actually declared and memory allocated for it in one place, in the .c file.
Similarly any functions that you want to be visible in both files should be declared in the headerfile (e.g. void myfunction(int x);) but the actual definitions should be somewhere in the .c or .cpp files.
The #ifndef and #define lines in the header as there so that if the header somehow gets included twice you don't get lots of redefinition errors.
There is nothing strange about c++ and globals, a global defined this way is global to everything, it doesn't matter what object you're in or how things are scoped. This can however have some strange effects since there is only ever one copy of a global while you can possibly have multiple instances of the c++ class that uses it. This can cause some consistency related issues if you aren't careful. Whether you need to worry about this or not depends very much on the nature of the code.

Thanks.....that's the information I needed.....hopefully I'll be able to implement it.....


text:
Can't get constant reading with load cells
I'm really a newcomer to arduino and I'm trying to build a scale with four SEN-10245 load cells and a HX711. My issue is that I can't get constant readings in the serial monitor and I'm not sure if my coding is right or if I did the right setup.
I made the following setup, based on some examples I found online:

The code I'm using is as follows:
    #include <hx711.h>
    Hx711 scale(A1, A0);
    void setup() {
    Serial.begin(9600);
    }
     void loop() {
     Serial.println(scale.averageValue());
     delay(200);
    }

link for the library github: https://github.com/aguegu/ardulibs/tree/master/hx711
Please help me, i'm a total beginner.

What is your power supply?

What are the readings you get? How much do they vary?

by now my only power supply is my computer.

@Miguel can you clarify what you mean by "constant readings"? Is it moving from 100 to 1200 or form 395 to 396?

Ihave the same problem can you help me

Assuming everything is hooked up correctly, your issue is likely related to electromagnetic noise (aka electromagnetic interference, EMI). Load cells output very small voltages, which is why you need the HX711 amplifier. Your long wires are essentially acting as antennas, picking up the electromagnetic noise in the room. One easy way to reduce the noise is to twist the wires together. You can also shield the wires by wrapping them with aluminum foil and attaching the foil to ground.
Making the wires much shorter would likely also help. That would be a good test to see if it helps.
The power supply could also be creating noise. I have found that the 5v line coming from a computer is often quite noisy. This is harder to fix, but an easy way to test if this is the issue is to power the Arduino with a 9V battery. Just make sure you plug it into the Vin pin, not the 5V pin, because the 9V needs to be regulated down to 5V.


text:
Getting more current through an LED array
I have an Arduino Uno controlling an array of 24 LEDs (datasheet).  I understand these LEDs are ultraviolet and have a forward current of 0.5A.  My power source (12V 2A) is wired to a switch which is then wired to the LED array and Arduino.  I should probably use a 12V 4A power source but was worried if too much current would go to the Arduino.  As per my attached diagram, the Arduino and LED array are in parallel.  I would like to get more current through my LEDs to increase their brightness.  What would be the best way to do this?
Updated: I tried adding a 100 Ohm resistor (where R11 is located) but the Arduino wasn't drawing enough power to turn on my LCD.  And then I tried a 1 Ohm resistor instead but the resistor burned out.  Unfortunately, I threw out the resistor and don't have a picture of it.  I believe the correct value should be ~47 Ohm so I have added that resistance as R11.  However, I haven't tested it yet as I want to make sure it's correct.  (12V - 6V) = 130mA * R >>> R = 46.15 Ohm.  I used a voltage drop of 6V so that at least 5V is still going into the Arduino (12V - 6V = 6V which is greater than 5V).  I measured the current through a multimeter to be 130mA.

This diagram is really messy. Also, I'm going to vote to migrate this question to the Electrical Engineering StackExchange because that is probably a better place to ask this.

Please edit your question and/or the  diagram to include values for R1–R9.  (R1-R8 have a lot to do with how much current flows.) Also edit your question to indicate whether you know the spec sheet is for a UV LED that does not produce visible light and it is specified for 1/2 amp forward current so that 8 strands of LEDs would take 4 amps, which a 12 V, 2 A supply can't handle.  Also say where the 1Ω resistor that burned out was located and add a picture of the burned out resistor

@Padraig, regardless if my answer works for you - please do as James Waldby requests and reword your question so that more people can make use of this exchange of information.

The current a bipolar transistor configured as a common emitter amplifier will allow from its collector to its emitter is equal to its beta time the base to emitter current.
A beta of 100 is common for many transistors. Assuming this information is close enough to your transistor, we can choose a base series resistance suitable for the collector to emitter current desired.
For example if you were using a 5 volt microprocessor and the voltage drop across the base to emitter was the usual 0.7 volts for silicon semiconductors and you had a base series resistor of 10Kohms:
V = I * R
V = 5 - 0.7 = 4.3 volts
R = 10000 ohms
I = 4.3/10000 = 0.43mA
I(ce) = Beta * 0.43mA
I(ce) = 100 * 0.43mA = 43mA

You could pass up to 43mA from the collector to the emitter.  If that is not enough,you can lowered the base resistor to 1Kohms:
R = 1000 ohms
I = 4.3/1000 = 4.3mA
I(ce) = Beta * 4.3mA
I(ce) = 100 * 4.3mA = 430mA

And increase the current to 430mA.  You still need to verify that the processor can supply the current to control the transistor (4.3mA as calculated above) as well as pick a transistor of sufficient capacity to handle the load.
If a beta of about 100 is not enough, consider using a Darlington transistor arrangement. This type of "2 transistor" device has a gain of the product of each individual transistor's beta.  So, it is common for such a device to have a beta of 10000!  Using this device, you can use a much larger base resistor and still be able to switch more current.

I tried adding a 100 Ohm resistor (where R11 is located) but the Arduino wasn't drawing enough power to turn on my LCD.

You should not have a resistor in the Arduino's supply line at all.

And then I tried a 1 Ohm resistor instead but the resistor burned out.

If you really wanted to have one to share the heat load of the on-board regulator, it would need to be a power resistor of appropriate wattage rating.

I believe the correct value should be ~47 Ohm so I have added that resistance as R11...I used a voltage drop of 6V so that at least 5V is still going into the Arduino (12V - 6V = 6V which is greater than 5V). I measured the current through a multimeter to be 130mA.

This is incorrect.
The Arduino's regulator needs something like 7 volts input to operate correctly.
The power drawn by the Arduino will not be fixed, it will depend on what it is doing, what I/Os are exerted against what loads, and other things like the LCD you apparently have.
Likely, if you want to use a power resistor you should design it to drop no more than half of the difference between the supply voltage and the regulator dropout voltage, under conditions of maximum load.  A fixed power resistor cannot be used to replace the variable power resistor that is a linear regulator; at most it can be used to offset some of the fixed part of the resistance and resulting thermal load.  But you still have to leave all of the variable part plus a healthy margin for the regulator to handle, or it won't be able to regulate.
It would be simpler to just put a heatsink on the regulator.


text:
Sending JSON message to web api via post. Why does HTTP 1.0 versus 1.1 make a difference?
I am sending a message to a web api call every xx seconds. I could not get it to work at all until I changed the header from HTTP 1.1 which is what I was using to HTTP 1.0. Then, it started working. Why would this affect things where I could not post and now I can?
This is what it was when it wasn't working:
client.println("POST /BoxLevel/api/BoxMeasurement HTTP/1.1");

And the change that fixed it:
client.println("POST /BoxLevel/api/BoxMeasurement HTTP/1.0");

Thanks!

HTTP/1.1 requires you to provide the host name of the server. And it will keep the connection open for some time unless you explicitly opt out of this. Thus, the equivalent of the basic HTTP/1.0 request in HTTP/1.1 language is
POST /the_uri HTTP/1.1
Host: foo.example.com
Connection: close

Thank you for the answer. One follow up question, with the host requirement in 1.1, does the host have to be valid? Meaning, will the client try to resolve the connection or check the host or can you populate it with anything?

@MichaelBedford: It's up to the server to interpret the Host header. It is very common for a single server to serve more than one Web site (it's called shared hosting). The Host header is then used by the server to know which Web site the client wants. If you provide an empty or a dummy name, you usually get a useless dummy page. A server serving a single site may just ignore that header, but it could also give an error if it's incorrect.


text:
Rounding up and Down
My arduino is meisuring the tempature and gives values like: 28.58 Degrees Celcius. I would like to round this up to one decimal. I could make the variable one shorter by cutting the "8" off which would desplay 28.5.
Yet this feels a bit like cheating as it mathimatical not correct. Does anyone know how to round up/down. Which would show my tempature as 28.6.
Extra advice needed. I am sending the tempature by Serial to my RPi which has a python code running. Would you suggest doing the rounding in the Arduino code or in The Python code.
Thanks in Advance!

Wouldn't it be better to round to nearest rather than systematically rounding up.

Yea I would love to able to round it the mathematical way. 28.65 <, will become 28.6 and 28.65 ≥, will become 28.7

Then let Serial.print() do the rounding, as per @Jot's answer.

Personally, I would not round until the data is on the Pi. Why lose precision when you don't need to? What if, at some later point, you decide you need to do more calculations on the data on the Pi? Python has a round() function built in.

As far as I know, the Serial.print (or println) does rounding up and down. All you have to do is take a float variable and do Serial.print( value, 1);
Without extra parameter, the default is choosen, which is 2 decimal digits: Serial.print( value, 2);
Why do you want to shorten the bytes over the Serial ? You can just as well send two decimal digits and process the value in Python.

Thats what the last part of my question is about ;) wondering where to process, in python on my Rpi or before sending.

Any rounding should be done as close to the final output as possible. If your serial port is fast enough then send 2 or 3 digits and round when the Pi is outputting the data. You don't want to base calculations on rounded values if you can help it, that introduces the possibility of errors.  That said it's a complete waste of time sending random numbers, if the temperature sensor has an error of +/- 1 degree then the first decimal place may be useful, anything after that is meaningless.

Okay agreed! It more precise to process at the final stage, yet the accuracy of the sensor is not there, so I will save bandwidth by using Serial.print(value, 1);

You can round in C by multiplying for the significance, adding +0.5, round down (equals as casting to an integer) and divide.
float f_rounded = ((int) (f * 10.0 + 0.5) / 10.0);

28.6 will be:
float f_rounded = ((int) (28.6 * 10.0 + 0.5) / 10.0)
                = ((int) 286.5) / 10.0 = 286 / 10.0 = 28.6

In Python it is equal (except the cast operator is int(...)
Update: for negative numbers +0.5 should be -0.5
Credits for Edgar Bonet: using round works for both positive and negative numbers:
float f_rounded = round(f * 10) / 10.0;

This would round -28.58 to -28.5.

@JohnnyMopp Updated my answers, thanks for the comment

Why not just float f_rounded = round(f * 10) / 10.0;? This handles both the positive and negative cases.


text:
How can I use the NRF24L01 modules without a library?
The datasheet is too intimidating for me, and I dont want to use the libraries available. Hence, I am looking for some clarity on this matter.

You can use them as book marks.

You can use the NRF24L01 by writing the functionality that is currently within a library yourself (and strip of parts you do not use).
However, for this, you need to understand the library, and therefore high likely the datasheet too.
You also can start without looking at a library, but your only documentation source is the datasheet itself.
A NRF24L01 has a lot of possibilities (that is why the datasheet is so extensive), so writing the functionality yourself might be causing more time.

And given all the functionality to be implemented to do even basic stuff, they would probably still end up writing something that looks very much like a library.

Indeed I did. But it's opened up the module for me. I was just stuck on the SPI commands though. Specifically the SPI read operation. I just didn't look at the diagram.


text:
send sketch to arduino via wifi
I'm pretty new to arduino and need some help.
My task is to connect my UNO R3 to wifi AND then send data (sketch for blinking led) to it.
I successfully connected my arduino with my wifi, but how do I send the sketch?
I didn't find a tutorial for this. Do you know a good one or can you help me, please?

I would prefer you to use a simple Adafruit EZ Link that provides you serial communication with a reset line with the help of Bluetooth. Well the solution that Majenko gave is also applicable but that will need a bit of work.

Once you involve wifi, an ATmega-based Arduino is rarely the right choice.  You'd be better off figuring out how to get an ESP8266 to reprogram itself, or using a Linux-based router chip which can load a new "OTA" image to its external SPI flash store.  Both solutions will be cheaper than Arduino + Ethernet Shield.

There is a difference between communicating via WIFI while a sketch is running or to send the sketch itself ... for the latter, I don't think there is an easy solution; you probably have to write your own AVR programmer, receiving the sketch via WIFI and store it on the Flash memory.

Given the bootloader, there's not as much difference as you think, if you have a wifi adapter that functions as a mostly transparent bridge, but ideally can also be commanded to toggle a modem status line to reset the ATmega.

You can't with a normal Arduino and WiFi shield.
However it is possible (if you are cunning) to do it with the ESP8266.
The basic idea is that you program an ESP8266 module to act like a transparent TCP/IP to UART bridge. Connect it to the TX and RX pins of the Arduino, listen on a port number of your choice, then when you connect to it (with telnet, netcat, socat, etc) all data is forwarded directly back and forth to the UART interface. If you monitor the connection state as well and use that to drive an equivalent of the DTR pin you can reset the Arduino automatically when you connect.
There is an example in the ESP8266 core that does it all apart from the connection monitoring, which is easy enough to add.
Then it's just a case of getting your computer to connect a virtual serial port with the remote socket on the ESP8266 and you have OTA programming for your choice of target board.
On Linux you can use socat for that:
root@foo:~# while `true`; do echo "ready"; socat pty,link=/dev/ttyACM99,raw,wait-slave,user=youruser,group=dialout tcp:192.168.0.16:24; done

(yes, you have to run it as root).
Quite how you'd go about that on other operating systems I don't know. I think socat is available on OS X. Windows is anyone's guess though.

Can we use a Adafruit Bluetooth EZ Link ?

No idea. If it can be a serial port, has the facility to reset the target MCU, and can be used without needing an active sketch on the Arduino (it is configured separately to the Arduino) then possibly.


text:
Problem on multiple interrupts operation on Arduino Uno
I experimenting with the interrupt ISR using Arduino Uno. In my circuit, I am taking two switches which are connected with Uno's interrupt pins, pins 2 and 3, and also taking multiple LEDs which are connected with other pins.
My logic is when I press switch1 (which is connected to pin 3) LEDs should be turned on by the interrupt service routine and when I press switch2 (which is connected to pin 2) LEDs should be turned off by the interrupt service routine.
My problem is that when I pressed switch1 LEDs are turned on but when I pressed switch2 LEDs are not turned off.
Here's my code:
int switch1 = 3;
int switch2 = 2;
int led1 = 13;
int led2 = 12;
int led3 = 11;
int led4 = 10;
int led5 = 9;
int led6 = 8;
int led7 = 7;
volatile bool flag1 = false;
volatile bool flag2 = false;
//volatile byte state = LOW;

void setup()
{
  pinMode(switch1, INPUT_PULLUP);
  pinMode(switch2, INPUT_PULLUP);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  pinMode(led5, OUTPUT);
  pinMode(led6, OUTPUT);
  pinMode(led7, OUTPUT);
  attachInterrupt(digitalPinToInterrupt(switch1), &setFlag1, CHANGE);
  attachInterrupt(digitalPinToInterrupt(switch2), &setFlag2, CHANGE);
}

void loop()
{
  if (flag1)
  {
    off();
  }
  if (flag2)
  {
    blink1();
  }

}

void blink1()
{
  attachInterrupt(digitalPinToInterrupt(switch2), setFlag2, CHANGE);
  digitalWrite(led1, HIGH);
  blink2();
}

void blink2()
{
  digitalWrite(led2, HIGH);
  blink3();
}

void blink3()
{
  digitalWrite(led3, HIGH);
  blink4();
}

void blink4()
{
  digitalWrite(led4, HIGH);
  blink5();
}

void blink5()
{
  while (1)
  {
    digitalWrite(led5, HIGH);
    delay(10);
    digitalWrite(led5, LOW);
    delay(10);
  }
}

void off()
{
  digitalWrite(led1, LOW);
  digitalWrite(led2, LOW);
  digitalWrite(led3, LOW);
  digitalWrite(led4, LOW);
  digitalWrite(led5, LOW);
  attachInterrupt(digitalPinToInterrupt(switch1), setFlag1, CHANGE);
}

void setFlag1()
{
  detachInterrupt(digitalPinToInterrupt(switch1));
  flag1 = true;
}

void setFlag2()
{
  detachInterrupt(digitalPinToInterrupt(switch2));
  flag2 = true;
}

I don't think I've ever seen a call chain quite like that before.  Also: 1) Do you know what while(1) does? 2) Why are you detaching and attaching interrupts all the time?

Any reason you make this o convoluted?

I don't see how you will ever leave the blink5 function. What is the purpose of an infinite loop in it?

You are being way way too convoluted with this. You're overthinking it.
The code should be as simple as (LED stuff omitted):
volatile bool running = false;
const uint8_t switch1 =3;
const uint8_t switch2 =2;

void setup() {
    pinMode(switch1, INPUT_PULLUP);
    pinMode(switch2, INPUT_PULLUP);
    attachInterrupt(digitalPinToInterrupt(switch1), turnOn, FALLING);
    attachInterrupt(digitalPinToInterrupt(switch2), turnOff, FALLING);
}

void loop() {
    if (running) {
        // Do something
    } else {
        // Do something else
    }
}

void turnOn() {
    running = true;
}

void turnOff() {
    running = false;
}

Note that what goes in loop() should be non-blocking, or at least have a reasonably short duration, so that it is able to pick up the changed running variable.
However, for something like this, interrupts are pretty pointless.

Thanks for reply. Actually this is not my solution but  you're right according to my question. It's my fault, I asked this question in wrong way. I am sorry for it . Well Now I am letting you know what I am actually want. There are several functions which will perform respective tasks. Executions of those function may or may not in a sequence but here I was showing in a sequence. There are two interrupts and each interrupt has an associate function means whenever interrupt will occur firstly that associate function should execute after execution this particular function process may go (contd)

(contd) any other function depend on condition. Among those function there is a function which will execute for real time that's why I have taken while(1)loop. And second interrupt associate with only one function and its task is different not associate with other functions but here I was showing it wrong. So my intention is whenever an Interrupt occur process execution should go their respective functions and functions are may or may not associate with each other.

Well, that is an entirely different kettle of fish. A completely different question that requires a completely different answer (and possibly a completely different understanding of what interrupts actually do on your part).

Now I am letting you know what I am actually want. - comments are not for completely rewording the question. You asked the question, you amend it to state what you actually want to do.


text:
Running a function in the background continuously
I have a keypad which is connected to arduino (with one analog pin).In the arduino code, I have created a circular queue which stores the inputs by pressing on keypad. Now when a key is pressed on keypad, it is stored as the first element in the queue. If an another key is pressed, it is stored as second element in the queue until is queue is full.(The keypad pins are connected using a voltage divider for each pin, so each and every key pressed on keypad will be recognized by arduino based on voltage for the key. The keys and voltages are stored in an array, as follows):
int keyboardPin = 0;    // analog pin to which keypad is connected
int keyboardValue = 0;  // Initial reading of analog pin 0 (A0) (it is zero as no key is pressed initially)
char keypad[16] = {'1','2','3','4','5','6','7','8','9'};
int treshold[16] = {590,568,548,426,415,404,334,326,320}; // Volatge values corresponding to each pin
int front=0,rear=0,size=6; // implementing circular queue using array
char cQueue[6];
int speed = 6,timer=0;
void setup(){
  cQueue[0] = '1'; // the first element of queue is '1' by default at the start
}
void loop(){
  keyboardValue = analogRead(keyboardPin); // Reading the value from A0 when key is pressed
  while(keyboardValue > 5) {  // Runs when a key is pressed
    for(int i=0;i<8;i++){
      if((treshold[i] - keyboardValue) == 0){
        Serial.println(keypad[i]); // Printing the key pressed
        enQueue(keypad[i]); // Storing the key pressed in the queue
        break;
      }
    break;
    } // end of for
  keyboardValue = 0;
  liftStops(cQueue[front+1]);// function to be run in background (front + 1) because  the key pressed by the user should be the argument of function
  break;
  } // end of while
}        // end of loop
int isFull(){  // to check if queue is full
  if( (f1 == r1 + 1) || (f1 == 0 && r1 == stops1-1)) {
  return 1;
}
  return 0;
}
void enQueue(char element){  // adding key pressed to queue
  if(isFull()){
    Serial.println("Lift full");
  }else{
    r1 = (r1 + 1) % stops1;
    qlift1[r1] = element;
  }
}
int deQueue(){  // removing the front element of queue
  char element;
  element = qlift1[f1];
  f1 = (f1 + 1) % stops1;
  return(element);
}

At the start of program, 1st element of queue is loaded with '1' (in setup function). When key is pressed, it is added as 2nd element of the queue.
There is a function which should run in the background as soon as a key is pressed. The function is:
void liftStops(char keyPress){  // defined after the loop() function
  while(timer<100){
    distance = (speed*timer);
    motorClockwise();
    Serial.println(distance);
    if(keyPress == '1' && distance == 0){
      motorStop();
      deQueue();
      return;
    }else if(keyPress == '2' && distance == 30){
      motorStop();
      deQueue();
      return;
    }else if(keyPress == '3' && distance == 60){
      motorStop();
      deQueue();
      return;
    }else if(keyPress == '4' && distance == 90){
      motorStop();
      deQueue();
      return;
    }
    timer = timer+0.167;
    delay(200);
  }
}

The element hold indicated by front variable in the queue is passed as a parameter to the liftStops() function. There is a motor in the circuit and the motorClockwise() rotates motor clockwise,motorStop() will stop the motor.
When the program is run for first time , if I press '2', it is stored as second element in the queue. The function liftStops() starts with '2' as its argument. Now the liftStops() function runs till distance == 30 and motor stops. Now deQueue() function is called and the element indicated by front gets eliminated('1' gets eliminated in the above case). After this,if I press '3', liftStops() runs till distance == 60 and the element indicated by front gets eliminated('2' in this case).
If I press a key when the liftStops() execution didn't finish, nothing is added to queue. I want the liftStops() function to run in background so that each and every key I press at any point of time gets stored in queue and the liftStops() function runs for every element in queue one after another.
Thanks.

If you use millis() instead of delay() (see the Blink Without Delay Arduino tutorial), then you won't need to run anything in the background.

Thanks for the reply. I have tried a lot using millis(), but I couldn't achieve the desired output.

I wrote in a comment to your question:

If you use millis() instead of delay() [...], then you won't need
  to run anything in the background.

and you answered:

I have tried a lot using millis(), but I couldn't achieve the
  desired output.

From this, I assume the real problem is that you haven't tried hard
enough. The general approach is quite simple:

Is there any work that has to be performed right now?

if yes, then just do it
if no, then don't do it

It works as long as you do not have any blocking code in your program.
Especially no calls to delay().
In your particular case, it would seem that liftStops() has work only
when:

timer is less than 100
and it hasn't done useful work during the past 200 ms (that's
the delay(200) in your code, and it's not useful work).

You may try the following:
void liftStops(char keyPress) {

    // Manage the execution timing.
    static uint32_t last_time;
    uint32_t now = millis();
    if (timer >= 100 || now - last_time < 200)
        return;  // nothing to do this time
    last_time = now;

    // Do the actual work.
    distance = (speed*timer);
    motorClockwise();
    Serial.println(distance);
    if(keyPress == '1' && distance == 0){
      motorStop();
      deQueue();
      return;
    }else if(keyPress == '2' && distance == 30){
      motorStop();
      deQueue();
      return;
    }else if(keyPress == '3' && distance == 60){
      motorStop();
      deQueue();
      return;
    }else if(keyPress == '4' && distance == 90){
      motorStop();
      deQueue();
      return;
    }
    timer = timer+0.167;
}

Just make sure it is called often. I.e. you call it in loop() and you
make sure there is no blocking code elsewhere in your program.

Typically this is done via an interrupt.
The use of an analog keyboard makes that more difficult or less convintional as the detection of a press in the analog sense is more difficult. One way to go is likely to scan the keyboard on a constant rate. But then detecting releases needs to be done creatively.

Thanks for the reply. I think it's easy the other way. The arduino runs the liftStops() function in the background and always checks if any key is pressed,stores it in queue and run the liftStops() for every function in queue.

You probably want to think through it more. The term "background" can be confusing. It generally means a high priority short task that can interrupt other low priority tasks.

Your code has a serial print in it and then delay. That's the sort of things that you should not put in the interrupt.

Obviously the whole thing is moot if you have a different distribution of "background".

Use loop function already provided for repetitive tasks
 void loop() {
 //this itself should be the function which you want keep running
 //check for keystrokes here and handle characters as they are
 //received. For handling characters, you can write a function outside
 //of the main loop which should return control to loop when task is
 //finished
 delay(200);
 }

I have solved my problem using attachInterrupt() function.The loop() runs liftStops() continuously and if there is a keyPress, it is recorded by the interrupt.
void setup(){
  attachInterrupt(digitalPinToInterrupt(3), floor1, CHANGE);
}
loop(){
  liftStops();
}
void liftStops(){
  if(qlift1[f1+1] != NULL){
    while(timer<100){
      distance = (speed*timer);
      motorClockwise();
      Serial.println(distance);
      if(qlift1[f1+1] == '1' && distance == 0){
        motorStop();
        deQueue();
        delay(5000);
        return;
      }else if(qlift1[f1+1] == '2' && distance == 30){
        motorStop();
        deQueue();
        delay(5000);
        return;
      }else if(qlift1[f1+1] == '3' && distance == 60){
        motorStop();
        deQueue();
        delay(5000);
        return;
      }else if(qlift1[f1+1] == '4' && distance == 90){
        motorStop();
        deQueue();
        delay(5000);
        return;
      }else if(qlift1[f1+1] == '5' && distance == 120){
        motorStop();
        deQueue();
        delay(5000);
        return;
      }else if(qlift1[f1+1] == '6' && distance == 150){
        motorStop();
        deQueue();
        delay(5000);
        return;
      }
      timer = timer+0.167;
      delay(200);
    }
  }
}
void floor1(){
  keyboardValue = analogRead(keyboardPin);
  while(keyboardValue > 5) {  // Runs when a key is pressed
    for(int i=0;i<8;i++){
      if((treshold[i] - keyboardValue) == 0){
        Serial.println(keypad[i]); // Printing the key pressed
        enQueue(keypad[i]); // Storing the key pressed in the queue
        break;
      }
    break;
    } // end of for
  keyboardValue = 0;
  break;
  } // end of while
}

If any key is pressed during delay(5000) even that gets recorded.