text:
Is this assignment valid or needs casting?
I have this assignment and while i don't get any error not even warning from the compiler.
uint16_t Buffer[40000];

for (int n=0; n<40000 ; n++){
Buffer[n] = (0.99 * cos(((2.0*PI)/40000)*n);
}

The Buffer is an unsigned short but as you can see inside there are float values inside.
The program does not work as expected.
Also i have another case where i am not sure if i need casting as this time, the final value is a float value.
int intVal;
float floatVal;

floatVal = intVal - intVal*Buffer[intVal];

Is this valid? Does it need casting? Or there is not reason to declare floatVal as float?

what exactly do you expect from the program to do?

it is a real time audio manipulation application

this is irrelevant.
What do you expect after executing your first snippet, to be the contents of Buffer?

The first one has wrong parenthesis, and casting is correct, however everything between 0 and 0.9999999999 results into a 0 in uint16_t variable.

Thanks! So i will experiment by just leaving the cos part!

What board are you trying to run that on?

There aren't many Arduinos that have 80 KB of RAM - please specify which one you are trying this on.

The Arduino line is not noted for its ability to do real-time audio manipulation. That's not its target market.

I am using Arduino DUE

c will perform implied casts for standard data types, normally without issuing any warnings.
This can catch you out at times.
So if you try to store a float into an int then it will be rounded down to the next integer. Since floats sometimes have rounding errors this can result in the value being 1 less than expected. e.g. 5 / 2.5 should give 2.0 but due to rounding may result in 1.99999999999. When saved as an int that would then give a value of 1.
If you want to round to the nearest integer then first add 0.5.
While the casts are implied and so not technically needed it can sometimes be a good idea to still include them explicitly just to make it clearer in the code that values are going to get rounded down.
The other thing to keep in mind is how variable types are promoted by the implied casts.
e.g. consider the following two lines:
float x = 3 + 2/4.0;
float x = 3.0 + 2/4;
In the first the calculation it is: int + int / double = int + double = double
In the second it is: double + int / int = double + int = double
So both result in a double that is then converted to a float (arduino is a little non-standard here, doubles are just floats anyway).
However the resulting values will be different. The first one will give
the expected 3.5 while the second one will give 3.0 because 2/4 is an integer calculation and will have a value of 0. In order to get the correct value either the 2 or the 4 must be cast to a float or double before the division operation takes place.
For your specific questions:
Buffer[n] = (0.99 * cos(((2.0*PI)/40000)*n); is perfectly valid, all calculations will be performed as doubles and the end result cast to an int however you may get rounding issues as mentioned above. Changing the line to Buffer[n] = (0.99 * cos(((2.0*PI)/40000)*n) + 0.5); will round to the nearest integer which is probably what you want.
For the second question, floatVal = intVal - intVal*Buffer[intVal]; there is no need for a cast, the value will be calculated as an int and then there is an implied cast to a float. However I'm not sure what the point of using a float is here since the result is always going to be an integer, using a float will only slow things down.

First part:
uint16_t Buffer[40000];

for (int n=0; n<40000 ; n++){
  Buffer[n] = (0.99 * cos(((2.0*PI)/40000)*n);
}

Buffer[n] will be filled with an uint16_t and implicit casting to an uint16_t will be used. I suggest you do such implicit castings explicitly (so add (uint16_t) ... if you want).
However, if you do not want this, either define the Buffer as float, or at least add + 0.5 to give better roundings (if that is improving, depends on your situation, but mathematically it is better).
thus:
static const uint8_t BUFFER_SIZE = 40000;
uint16_t Buffer[BUFFER_SIZE];

for (int n=0; n<BUFFER_SIZE; n++)
{
  Buffer[n] = (int) (0.99 * cos(((2.0*PI)/BUFFER_SIZE)*n));
}

The next one:
int intVal;
float floatVal;

floatVal = intVal - intVal*Buffer[intVal];

This is also 'compiler-correct', and an int value can be more easier converted to a float. You will not lose digits. However, to make it clear an explicit cast with (int) ... is better.
Thus:
int intVal;
float floatVal = (float) (intVal - intVal*Buffer[intVal]);


text:
Arduino Due, program not there after power off
When i program my arduino Due after a RESET, my program is still there.
However, when i power off my Due and then turn it back on, no program is there!
There is no persistence in the program and i have to program it all again!
I am programming it throught the Programming port.
EDIT: If it doesn't boot properly with my code and then i press the RESET button, then my code is loaded and it works like i programmed it. But how can i make it so that it works straight away, after it's fed with power?

source: Stack Exchange

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

sort: votes


text:
Tone() function pauses between notes
I tried to experiment with the tone() function that comes with the arduino library.
I played around with the standard code example located here:
https://www.arduino.cc/en/Tutorial/BuiltInExamples/toneMelody
This is the code:
#include "pitches.h"

int melody[] =
{
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};

int noteDurations[] =
{
  4, 8, 8, 4, 4, 4, 4, 4
};

void setup()
{
   for (int thisNote = 0; thisNote < 8; thisNote++)
   {
      int noteDuration = 1000 / noteDurations[thisNote];
      tone(8, melody[thisNote], noteDuration);

      // to distinguish the notes, set a minimum time between them.
      // the note's duration + 30% seems to work well:
      int pauseBetweenNotes = noteDuration * 1.30;
      delay(pauseBetweenNotes);

      // stop the tone playing:
      noTone(8);

   }
}

void loop()
{
  // no need to repeat the melody.
}

However, the problem is that there is always a pause between notes.
In musical terms, this is called staccato.
I want to be able to play short melodies where there are no delays between the notes, and one note progresses to the next naturally. By the way, this is called legato in music theory.
Now, in this example, the delay between the notes sounds good because this "music piece" is supposed to be played this way. But in every other song that i experimented with, there were always some pauses between notes.
This is what this song sounds like: https://soundcloud.com/nikowow-1/normal
Naturally, my mind went to the delay(pauseBetweenNotes) function. So i thought this is what causes the delay between the notes. So i set it up to 0.5. This is what it sounds like: https://soundcloud.com/nikowow-1/05a
As you can hear, it just speeds up the whole song. The delay between the notes remain, but the whole song is sped up (in a higher tempo, so to speak).
In order to better hear the delay between the notes, please take a listen at the song when i selected a value of 3 - causing a smaller tempo, so that the delay between the notes can be more easily audible: https://soundcloud.com/nikowow-1/3a-1
I want to create some melodies where there are no delays between the notes and i am stuck.
EDIT: If you remove the delay line alltogether, the song is played so quickly that only a click sound is heard.

https://www.arduino.cc/en/Tutorial/BuiltInExamples/BlinkWithoutDelay

@VE7JRO Thank you! But sorry but i dont understand. How can this be implemented in the tone() function?

I'm probably messing something. So, I'll just ask: What happens if you remove (or comment out) delay(pauseBetweenNotes); altogether?

@timemage Sorry i ommited this in the question and will edit it. But if you remove the delay, the song is played so quickly that only a feint click is heard.

I see. They made it non-blocking. That's not really what I expected from ArduinoLand.

Replace the delay with a millis timer.

@VE7JRO, why do you point them to millis()? that is not a solution to what the question asks. btw: https://arduino.stackexchange.com/questions/17355/playing-melody-with-tone-without-using-delay/89697#89697

@Juraj This was it! Thank you so much! If you want, you can make a proper answer, so i can upvote and mark it as the selected answer. Once again, thanks a ton!

@Juraj because ditching the use of delay is the most important lesson an Arduino user can learn.

@VE7JRO, OP is not there yet

@Juraj - The blocking delay will be the next question :)

I am not sure i understand what you suggest. I should replace delay with a millis timer to do the delay work? I thought millis only counts time. Does it also perform countdown until a specific time?

@VE7JRO, that question would be a duplicate of https://arduino.stackexchange.com/questions/17355/playing-melody-with-tone-without-using-delay/89697

there is
      // to distinguish the notes, set a minimum time between them.
      // the note's duration + 30% seems to work well:
      int pauseBetweenNotes = noteDuration * 1.30;
      delay(pauseBetweenNotes);

so the *1.30 creates the pause.
if you change it to
   int pauseBetweenNotes = noteDuration;

there will be no pause between notes.
The tone length is specified with the last parameter of the tone() function (noteDuration here).

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


text:
How to increase current in Arduino uno?
How to increase current in O/P port in Arduino uno ?
to make it 200mA How I can do this?
It can in proggraming add more current
Which sample way to increase current ?
To control 2 Dc motor which normally work with 3 AA battery
Thanks

You add a transistor. Just like when you're controlling a relay, which needs more current that the Arduino can provide.

You can use a TT2148 power transistor-this can connect to arduino without a resistor and deal with high current.

Personally I'd prefer a MOSFET...

What model of MOSFET do you prefer to use?

That depends on many factors - current levels, switching speed and voltages, footprint, etc. I have many that I often choose between. One of my current common ones is the TSM2314CX

The TSM2314CX then. That depends on many factors-state the obvious!

Which type of transistors I can use?? I can use TIP120 transistor?

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


text:
How I can use multi sensor in one code in Arduino?
How I can use multi smoke sensor in one code? I mean how can I use more than one sensor, where both sensors has the same purpose, like use smoke sensor in multi room. Similar to this code where one is used only. How I can more than one, in Arduino Uno R3,,
<per>
    int redLed = 12;
int greenLed = 11;
int buzzer = 10;
int smokeA0 = A5;
// Your threshold value
int sensorThres = 400;

void setup() {
  pinMode(redLed, OUTPUT);
 pinMode(greenLed, OUTPUT);
pinMode(buzzer, OUTPUT);
pinMode(smokeA0, INPUT);
Serial.begin(9600);
}

void loop() {
  int analogSensor = analogRead(smokeA0);

  Serial.print("Pin A0: ");
  Serial.println(analogSensor);
  // Checks if it has reached the threshold value
  if (analogSensor > sensorThres)
  {
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
    tone(buzzer, 1000, 200);
  }
  else
  {
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);
    noTone(buzzer);
  }
  delay(100);
}

How I can add more than one sensor to get same purpose. check detect 1 and detect2 and detect 3 if one of this detection LED Red ON, Thanks`

just duplicate the parts of the code that handle the sensor.
int redLed = 12;
int greenLed = 11;
int buzzer = 10;
int smokeSensor1 = A5;
int smokeSensor2 = A4;
int smokeSensor3 = A3;
// Your threshold value
int sensorThres = 400;

void setup() {
  pinMode(redLed, OUTPUT);
  pinMode(greenLed, OUTPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(smokeSensor1, INPUT);
  pinMode(smokeSensor2, INPUT);
  pinMode(smokeSensor3, INPUT);
  Serial.begin(9600);
}

void loop() {
  int analogSensor1 = analogRead(smokeSensor1);
  int analogSensor2 = analogRead(smokeSensor2);
  int analogSensor3 = analogRead(smokeSensor3);

  Serial.print("Pin A0: ");
  Serial.println(analogSensor1);
  // Checks if it has reached the threshold value
  if( (analogSensor1 > sensorThres) || (analogSensor2 > sensorThres) || (analogSensor3 > sensorThres) )
  {
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
    tone(buzzer, 1000, 200);
  }
  else
  {
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);
    noTone(buzzer);
  }
  delay(100);
}

You haven't mentioned what sensor you are using, so I can't offer any help on how to interface with it. Though you can add 'multi-sensor code' by adding code that will get the state of the sensor at times when you can afford to wait a few ms before checking the state of the other sensors. With the code you provided, you could after the if/else block but before the delay.
Also, it is typically not a good idea to put sensors far away from each other but still connect them to the same controller. You should give each room its own Arduino.

I use Mq2 smoke sensor. I mean use mq2 sensor in many room at least 3 sensor in one Arduino uno.


text:
How I Can Send the status of switch in SMS by Arduino?
How I want help ,, I want send status of Switch If switch > 20 send SMS status of switch OFF and when switch <20 than mean switch ON , Don't want send the value of reading.
I use Arduino uno
If I want use multiple switch and send all status of switchs in one message.
I mean if switch1 > 20 ON and switch2 <20
I want send status of switch In one SMS
Switch1 ON
Switch2 OFF
Switch3 OFF
How I can do this??
void loop()
Switch = analogRead(S_Switch);
if (Switch > 20 )
{
Serial.println(Switch);// If Switch > 20 show in SMS switch statuse  OFF,, If switch < 20 show in SMS switch statuse ON
Serial.print("\n******************\n");
Sim900Serial.print("AT+CMGF=1\r"); //Sending the SMS in text mode
delay(1000);
Sim900Serial.println("AT + CMGS = \"+***************\"");//The predefined phone number
delay(1000);
Sim900Serial.println("MY Swicth statuse is :");
Sim900Serial.println(Switch); // I don't want the value of Switch I want ( ON , OFF )
 Sim900Serial.print("              ");
Sim900Serial.println((char)26);//the ASCII code of the ctrl z is 26
delay(5000);
Sim900Serial.println();
}

Do you want to send the value in both cases, ON and OFF?  Do you just want it to keep sending constantly, over and over, or some other behaviour (e.g. when it changes)?  Does your existing code work (but not do what you want)?

Here, Updated Code...
const int switchOneInput = A0; // Switch 1
const int switchTwoInput = A1; // Switch 2

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

void loop()
{
  int switchOneStatus = analogRead(A0);
  int switchTwoStatus = analogRead(A1);

  // When Switch 1 is OFF and Switch 2 is OFF
  if(switchOneStatus < 20 && switchTwoStatus < 20)
  {
    smsOne();
  }

  // When Switch 1 is ON and Switch 2 is OFF
  else if(switchOneStatus > 20 && switchTwoStatus < 20)
  {
    smsTwo();
  }

  // When Switch 1 is OFF and Switch 2 is ON
  else if(switchOneStatus < 20 && switchTwoStatus > 20)
  {
    smsThree();
  }

  // When Switch 1 is ON and Switch 2 is ON
  else if(switchOneStatus > 20 && switchTwoStatus > 20)
  {
    smsFour();
  }

}

void smsOne()
{
  Serial.begin(9600);  //Baud rate of the GSM/GPRS Module
  Serial.print("\r");
  delay(1000);
  Serial.print("AT+CMGF=1\r");
  delay(1000);
  Serial.print("AT+CMGS=\"+**********\"\r");    //Number to which you want to send the sms
  delay(1000);
  Serial.print("Switch 1 is OFF and Switch 2 is OFF\r");   //The text of the message to be sent
  delay(1000);
  Serial.write(0x1A);
  delay(1000);
}

void smsTwo()
{
  Serial.begin(9600);  //Baud rate of the GSM/GPRS Module
  Serial.print("\r");
  delay(1000);
  Serial.print("AT+CMGF=1\r");
  delay(1000);
  Serial.print("AT+CMGS=\"+**********\"\r");    //Number to which you want to send the sms
  delay(1000);
  Serial.print("Switch 1 is ON and Switch 2 is OFF\r");   //The text of the message to be sent
  delay(1000);
  Serial.write(0x1A);
  delay(1000);
}

void smsThree()
{
  Serial.begin(9600);  //Baud rate of the GSM/GPRS Module
  Serial.print("\r");
  delay(1000);
  Serial.print("AT+CMGF=1\r");
  delay(1000);
  Serial.print("AT+CMGS=\"+**********\"\r");    //Number to which you want to send the sms
  delay(1000);
  Serial.print("Switch 1 is OFF and Switch 2 is ON\r");   //The text of the message to be sent
  delay(1000);
  Serial.write(0x1A);
  delay(1000);
}

void smsFour()
{
  Serial.begin(9600);  //Baud rate of the GSM/GPRS Module
  Serial.print("\r");
  delay(1000);
  Serial.print("AT+CMGF=1\r");
  delay(1000);
  Serial.print("AT+CMGS=\"+**********\"\r");    //Number to which you want to send the sms
  delay(1000);
  Serial.print("Switch 1 is ON and Switch 2 is ON\r");   //The text of the message to be sent
  delay(1000);
  Serial.write(0x1A);
  delay(1000);
}

Thanks dear but still you don't understand me this I can use just for one switch ON or OFF , if more than one switch ,, And I want both status in one SMS

I mean both status Switch1 ON or OFF and Switch2 ON or OFF In same SMS. Example Switch1 ON , Switch2 ON

Ok. Got it. You mean like if Switch 1 is ON or OFF then SMS you notify you about Switch 1 is ON or OFF. And now if you add another Switch let say Switch 2. So, now suppose Switch 1 is ON and Switch 2 is OFF then SMS be like Switch 1 is ON and Switch 2 is OFF. Am I right ?

Thanks Hasan,, Yes and send in one SMS so any change in switch will change in SMS

Ok. Got it. Let me modified my code.

I just modified my code. I hope it will help  you.

Let us continue this discussion in chat.


text:
Home devices control system using gsm and arduino mega2560
Hi dears I'm trying to do project to control app base gsm control by arduino mega 2560 gsm module SIM900A
To send SMS to open Led than reply SMS to give as the status I mean send SMS then I received SMS from GSM module  by this code same time work but same time not work also same time send SMS1111 received SMS2222 status.
I hope it is clear.
#include <SoftwareSerial.h>
#include <string.h>
#include "SIM900.h"
#include <TinyGPS.h>
#include "sms.h"
SoftwareSerial GSMSerial(12, 13);
byte buffer[128];
int count = 0;
const int Led4 = 43;
const int Led1 = 44;
const int Led2 = 45;
const int Led3 = 50;
void SIM900power()
{
}
void setup() {
    pinMode(Led1, OUTPUT);
  pinMode(Led2, OUTPUT);
  pinMode(Led3, OUTPUT);
  pinMode(Led4, OUTPUT);
  GSMSerial.begin(19200); // the SIM900 baud rate
  Serial.begin(9600); // the Serial port of Arduino baud rate.
  Sim900_Inti();
}
void loop() {
  GSMSerial.listen();
  if (GSMSerial.available()) // If date is comming from from GSM shield)
  {
    while (GSMSerial.available()) // reading data into char array
    {
      buffer[count++] = GSMSerial.read(); // writing data into array
      if (count == 128)break;
    }
    Serial.write(buffer, count); // if no data transmission ends, write         buffer to hardware serial port
Cmd_Read_Act(); //Read the 'COMMAND' sent to SIM900 through SMS
clearBufferArray(); // call clearBufferArray function to clear the storaged data from the array
count = 0; // set counter of while loop to zero
  }
  if (Serial.available()) // if data is available on hardwareserial port ==>     data is comming from PC or notebook
    GSMSerial.println(Serial.read()); // write it to the GPRS shield
}
void clearBufferArray() // function to clear buffer array
{
  delay(1000);
  for (int i = 0; i < count; i++)
  {
    buffer[i] = NULL; // clear all index of array with command NULL
    delay(100);
  }
  for (int n = 0; n < count; n++)
  {
    buffer[n] = NULL; // clear all index of array with command NULL
    delay(100);
  }
  for (int m = 0; m < count; m++)
  {
    buffer[m] = NULL; // clear all index of array with command NULL
    delay(100);
  }
  for (int p = 0; p < count; p++)
  {
    buffer[p] = NULL; // clear all index of array with command NULL
    delay(100);
  }
}
void Sim900_Inti(void)
    {
     GSMSerial.println("AT+CMGF=1"); // Set GSM shield to sms mode
  Serial.println("AT+CMGF=1");
  delay(500);
  GSMSerial.println("AT+CNMI=2,2");
  Serial.println("AT CMGF=1");
  delay(500);
}
void Cmd_Read_Act(void) //Function reads the SMS sent to SIM900 shield.
{
  char buffer_i[128];
  for (int i = 0; i < count; i++)
  {
    buffer_i[i] = char(buffer[i]);
  }
  if (strstr(buffer_i, "1111")) //Comparing password entered with password     stored in program
  {
          digitalWrite(Led1, HIGH);
   SMS_1111();
  }
  char buffer_n[128];
  for (int n = 0; n < count; n++)
  {
    buffer_n[n] = char(buffer[n]);
  }

  if (strstr(buffer_n, "2222")) //Comparing password entered with password     stored in program
  {
          digitalWrite(Led2, HIGH);
   SMS_2222();
  }
      char buffer_m[128];
  for (int m = 0; m < count; m++)
  {
    buffer[m] = char(buffer[m]);
  }
  if (strstr(buffer_m, "3333")) //Comparing password entered with password     stored in program
  {
   digitalWrite(Led3, HIGH);
   SMS_3333();
  }
  char buffer_p[128];
  for (int p = 0; p < count; p++)
  {
    buffer[p] = char(buffer[p]);
  }
  if (strstr(buffer_p, "4444")) //Comparing password entered with password stored in program
      {
    digitalWrite(Led4, HIGH);

   SMS_4444();
  }
}
  void SMS_1111() // complet liter Replay SMS TO Know Led1 Is ON
 {
 }
 void SMS_2222()// complet liter
{
}
void SMS_3333()// complet liter
{
}
void SMS_4444()// complet liter
{
}>

Why are you using software serial on an Arduino Mega?

Sorry I used Arduino Uno before now my problem when I send 1111 or 2222 I received  SMS from gsm module but when I send 3333 or 4444 not received any thing

For the 3333 and 4444 you are doing
buffer[m] = char(buffer[m]);

and
buffer[p] = char(buffer[p]);

which does nothing.
You probably meant
buffer_m[m] = char(buffer[m]);

and
buffer_p[p] = char(buffer[p]);

@Moosa Don't forget to accept the answer if it solved your problem.


text:
Reading Two Quadrature Encoder using a single Arduino Due
I am working on an autonomous robot in my summer vacations. I am currently working on running the motors of my robot in a closed loop. In order to do so, I have to interface two Quadrature encoders of the motors with the Arduino Due that I have. My motor encoder have 3200 Edges per Revolution. I have read the Atmel SAM3x8E datasheet and have successfully tested one encoder in Arduino IDE. It appears that TIOA0 and TIOBO are used to read PHA and PHB of of one Encoder which correspond to Pin 2 and 13 of Arduino Due. I am not using Index pin (TIOB1).

It seems that I can only interface 1 quadrature .Is their any way I can use Quadrature decoder to read 2 encoders instead of one. As I have stated earlier I am not using the index pin. So, maybe there might be a way to decode to encoders using the three available pins as shown in the above diagram. I don't want to use Interrupts to do this job.
Here's is the link of SAM3x Manual:
http://www.atmel.com/Images/Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf
Link of Motor that i am using:
www.pololu.com/product/2824

According to Quadrature Decoder QDEC for SAM3/4 Devices_ApplicationNote_AT11483 and referenced excel sheet with Device to No of QDEC channels it seems to have two of them. However in DUE almost none of interesting devices are wired to headers completely (Extmem, SD interface,...)
However TIOA6 and TIOB6 should be on pins 5 and 4
Pin configuration should be something like this:
  PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC25B_TIOA6, PIO_DEFAULT);
  PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC26B_TIOB6, PIO_DEFAULT);

And TC0 is pretty much same as TC2, so just copy&paste and change TC0 to TC2
Full config:
  REG_PMC_PCER0 = PMC_PCER0_PID27 | PMC_PCER0_PID28 | PMC_PCER0_PID29;
  REG_PMC_PCER1 = PMC_PCER1_PID33 | PMC_PCER1_PID34 | PMC_PCER1_PID35;

  PIO_Configure(PIOB, PIO_PERIPH_B, PIO_PB25B_TIOA0, PIO_DEFAULT); // arduino pin 2
  PIO_Configure(PIOB, PIO_PERIPH_B, PIO_PB27B_TIOB0, PIO_DEFAULT); // arduino pin 13

  REG_TC0_CMR2  = TC_CMR_TCCLKS_TIMER_CLOCK4 | TC_CMR_WAVE | TC_CMR_ACPC_TOGGLE | TC_CMR_WAVSEL_UP_RC;
  REG_TC0_RC2   = F_CPU / 128 / 1;
  REG_TC0_CMR0  = TC_CMR_ABETRG | TC_CMR_LDRA_EDGE | TC_CMR_LDRB_EDGE | TC_CMR_ETRGEDG_EDGE | TC_CMR_CPCTRG;
  REG_TC0_BMR   = TC_BMR_QDEN | TC_BMR_SPEEDEN /*| TC_BMR_EDGPHA*/;
  REG_TC0_CCR0  = TC_CCR_CLKEN | TC_CCR_SWTRG;
  REG_TC0_CCR1  = TC_CCR_CLKEN | TC_CCR_SWTRG;
  REG_TC0_CCR2  = TC_CCR_CLKEN | TC_CCR_SWTRG;

  PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC25B_TIOA6, PIO_DEFAULT); // arduino pin 5
  PIO_Configure(PIOC, PIO_PERIPH_B, PIO_PC26B_TIOB6, PIO_DEFAULT); // arduino pin 4

  REG_TC2_CMR2  = TC_CMR_TCCLKS_TIMER_CLOCK4 | TC_CMR_WAVE | TC_CMR_ACPC_TOGGLE | TC_CMR_WAVSEL_UP_RC;
  REG_TC2_RC2   = F_CPU / 128 / 10;
  REG_TC2_CMR0  = TC_CMR_ABETRG | TC_CMR_LDRA_EDGE | TC_CMR_LDRB_EDGE | TC_CMR_ETRGEDG_EDGE | TC_CMR_CPCTRG;
  REG_TC2_BMR   = TC_BMR_QDEN | TC_BMR_POSEN /*| TC_BMR_EDGPHA*/;
  REG_TC2_CCR0  = TC_CCR_CLKEN | TC_CCR_SWTRG;
  REG_TC2_CCR1  = TC_CCR_CLKEN | TC_CCR_SWTRG;
  REG_TC2_CCR2  = TC_CCR_CLKEN | TC_CCR_SWTRG;

I am using Arduino IDE for programming. According to Quadrature Decoder QDEC for SAM3/4 Devices_ApplicationNote_AT11483 Pg 16 I have to first configure the IOpins. How can i configure TIOA6 and TIOB6 as QDEC input pins?

@KIVV Please see the above comment

@MasoodSalik How exactly it's done right now for TC0? Some library or directly in arduino? Do you have code for it? And also which Arduino IDE - there is arduino.cc and arduino.org

I have posted the code in another post   http://arduino.stackexchange.com/questions/28268/how-to-configure-2nd-quadrature-decoder-io-pins-in-arduino-ide

I am currently using Arduino IDE 1.6.10.(zip file download fromhttps://www.arduino.cc/en/Main/Software) After Installing the board "Arduino SAM board (32 bit ARM Cortex M3). All libraries of DUE are already added in it.

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


text:
How do I Continuity Test/Troubleshoot a Linksprite RS232 V2 Shield?
I have a Linksprite RS232 v2 adapter (which uses a MAX232 chip), as per this image. I have soldered on the headers and tested the pins to make sure there are no solder bridges. I have set the jumpers so that D2 is set to TX and D3 to RX. However, I can't establish comms through the device using the Software Serial library, regardless of how I set the jumpers. (Real Term doesn't show me anything when a USB-to-Serial adapter is connected. However, if I change the baud rate to 9600, I get about 5 bytes of 0x00, then nothing.)
If I disconnect the shield from the Arduino board then supply 5V to pin 2 or 3 (from an Arduino) and connect pin 5 of the DB/E9 to the Arduino's GND, I get output from both pins 2 and 3 (RX/TX) on the DB/E9 (regardless of which pin on the board is powered). The voltage between pins 2 and 3 on the connector differs by ~0.1V. Is this normal or is my circuit faulty? How do I test the continuity of the board/connector and diagnose and fix the fault?
In case it's of any relevance, I'm using an Uno with an SMD chip.

Do you have an oscilloscope, or logic analyzer, or more than one Arduino?  If you only have a DVM, with jumpers off run a sketch that toggles different digital pins at about .5 Hz, and verify that that shows up ok on pins of J2 on the shield.

I don't have an oscilloscope or logic analyser (or know how to use one). I do have a DT830B multimeter and multiple boards (Uno R3, Leonardo R3, Mega 2560 R3).

It turns out that the ATMega328P-PU chip on the Uno I was using is damaged. I will try again with a different board and see if the problem persists.

@JamesWaldby-jwpat7 Thank you for the suggestion. I managed to get access to an oscilloscope and test the shield with a different board. It helped me diagnose that the RS232 shield is non-functional.


text:
Why is one LED more luminous (brighter) than the other?
Given that there is a circuit with two pins (12 and 10) from an Uno providing power to LEDs on two separate branches, why is the yellow LED dimmer than the green LED? (Please see below image.) To my understanding, the branches attach to GND in parallel, so the LEDs should be equally bright.
If it helps, the two branches are programmed so one LED is off when the other is on and vice versa, with a 1s interval between changing pin state. This isn't a PWM thing as using pin 8 instead of 10 makes no difference.

Different colour LEDs have different forward voltages and require different value resistors to get the same current through them.

What do you mean by "forward voltages"? Does voltage not travel in only one direction?

You will need to read some tutorial about LED functioning in order to properly handle your circuit. I highly suggest https://learn.adafruit.com/all-about-leds/overview in it all terms like forward voltage and forward current are explained, among others.

Just like men, all LEDs have been made different.
Practically, that means two different LEDs (one green and one yellow for instance) will have different brightnesses (more precisely, luminous intensities) when they are traversed by the same current (forward current).
LED luminous intensity is a function of the current that traverses it (among other factors).
If you want the same brightness for those 2 LEDs, then you'll have to:

Get both LEDs datasheets (should be a couple of A4 pages for each)
Find the luminous intensity/forward current function curve in each
Determine which brightness you want for both
Deduce the current for each
Calculate the resistor value to get that current for each

Then you will have to use two different resistors values in your wiring, based on calculations of step 5.
Simpler, you could just replace one of your 2 resistors with one small pot that you can use to tune brightness of the second LED until it fits brightness of the first one.
Be careful with pot manipulation though, as a 0 resistance would probably grill your LED (and potentially the Arduino pin it is wired to).

Thanks for the warning about burning LEDs with pots; I already did that to one of them testing out how much luminous intensity I could get out of a red LED. :(

Don't worry that can happen to anyone, even not beginners (I grilled a few LEDs myself, including 7-segment displays, and also a few transistors :-))

Eish. At least LEDs are cheap...

Add to that the human eye responds in different ways to different colours of light - green being the most sensitive... so you have visual intensity as well...

@Majenko correct, but that is not shown in the datasheets. This is why in the end, the pot solution is probably the most relevant.

Or use PWM to set the brightnesses to be visually equal...

Personally I'd use PWM only if I need to vary the brightness during my program; if I can fix it, I'd go with the pot solution and just the digital pin out.

Just like men, all LEDs have been made different.  - and women. ;)


text:
How to calculate the needed voltage and current to supply for Arduino
I have Arduino MEGA and I'm connecting to it 5 servomotors.
{ 3 TowerPro M995
Basic Information

Modulation:  Digital
Torque:  4.8V: 130.5 oz-in (9.40 kg-cm)
6.0V: 152.8 oz-in (11.00 kg-cm)

Speed:  4.8V: 0.20 sec/60°
6.0V: 0.16 sec/60°

Weight:  1.94 oz (55.0 g)
Dimensions:
Length:
1.60 in (40.7 mm)

Width:
0.78 in (19.7 mm)

Height:
1.69 in (42.9 mm)
Motor Type:  3-pole
Gear Type:  Metal

2 Towerpro M996R

Basic Information

Modulation:  Digital
Torque:  4.8V: 130.5 oz-in (9.40 kg-cm)
6.0V: 152.8 oz-in (11.00 kg-cm)

Speed:  4.8V: 0.19 sec/60°
6.0V: 0.15 sec/60°

Weight:  1.94 oz (55.0 g)
Dimensions:
Length:
1.60 in (40.7 mm)

Width:
0.78 in (19.7 mm)

Height:
1.69 in (42.9 mm)
Motor Type:  3-pole

}

So how can I calculate the voltage and current needed to supply this Arduino?

Use a LiPo battery then you never need to worry about current again :)

Drive all your components simultaneously from an external supply at appropriate voltage. Measure current draw in series (set your multimeter's red cable on the 10A port and set it to 10A, and connect red to VOUT, black to ground). Don't hold the wires in your hands, use clip-ons. Let it run for a while, and pay attention to current fluctuations. Read the current requirements on the display. A power supply with a bit more amperage than necessary is a Good Thing(tm).
Edit: remember to get both normal load and stall measurements. It is wise to add some way of turning stalling motors off, since stalling is motor death. And sometimes power supply death - those segway-for-kids things come to mind (and make me snicker ... WHEN I WAS A CHILD WE HAD OUR FEET FOR TRANSPORTATION, AND SHOES, IF WE WERE LUCKY!).

Voltage is simple - a device has a requirement and that is what you have to provide. In the case of the servos that is a range of voltages that it can use. So 5V is a good voltage.  The Arduino can take 5V if you feed it in to the 5V pin or the USB port, or 7-12V if you feed it in to the barrel jack.
The current you cannot calculate. You haven't provided enough information. The calculation, when you have the information, is quite simple: for all the devices on the same power supply add the currents requirements together. The supply has to be able to provide at least that amount of current.

I couldn't find information about the current anywhere :/  this is the info provided by the main website..   the servos are connected in arduino ... so they are taking the volt from 5V in arduino ..

Then you will have to measure the current with your trusty DMM.

Measurements in ordinary cases will not be a reliable indication of what can be encountered.  The servos should not be powered through the Arduino.  Expect that they can draw up to several amps when loaded, especially in combination.


text:
IR remote unstable button numbers
Question
Is there a reason for unstable button numbers of an IR remote?
Desciption
I wrote a remote class where I identify the pressed number of the remote to set states. But however I get never the same number of the pressed key.
For example I press the number '1' and on the serial interface shows this:
3588650484
2740290906
3148594742
689746115
2396927248
2934053595
4294967295
3876827360

And it should look like this:
16724175 // Button 1
4294967295
16724175 // Button 1
16724175 // Button 1
16724175 // Button 1
16724175 // Button 1

Hardware
I am using an arduino UNO board and the standart remote of the starter kit. There is no name just 'SPECIAL FOR MP3'.
Some more infos
Ok, in my first project I used the code from Noreddine Kessa(Example Project) which works fine. Next I copied some code in my new class 'IRControl.cpp' ( you can see below). Then I created an object IRControl in the main.cpp and run the menu() in the loop.
h-File:
/*
 * IRControl.h
 *
 *  Created on: 04.04.2016
 *      Author: David
 */

#ifndef IRCONTROL_H_
#define IRCONTROL_H_

//Remote Defines
#define buttonON 16753245
#define buttonMode 16736925
#define buttonSoundOff 16769565
#define buttonPlayStop 16743045
#define buttonTrackBack 16712445
#define buttonTrackForward 16761405
#define buttonEQ 16769055
#define buttonMinus 16754775
#define buttonPlus 16748655
#define button0 16738455
#define buttonRepeat 16750695
#define buttonJSD 16756815
#define button1 16724175
#define button2 16718055
#define button3 16743045
#define button4 16716015
#define button5 16726215
#define button6 16734885
#define button7 16728765
#define button8 16730805

#include "IRremote.h"
#include "wiring_private.h"

enum zustaende{Motor1, Motor2, Motor3, Sleep};
extern int zustand;

class IRControl {
private:
    IRrecv *irrecv;
    decode_results remoteValue;
public:
    IRControl(int RECV_PIN);
    virtual ~IRControl();
    void menu();
};

#endif /* IRCONTROL_H_ */

cpp-File:
* IRControl.cpp
 *
 *  Created on: 04.04.2016
 *      Author: David
 */

#include "IRControl.h"

IRControl::IRControl(int RECV_PIN) {
    // TODO Auto-generated constructor stub
    irrecv = new IRrecv(RECV_PIN);
    pinMode(RECV_PIN , INPUT);
    irrecv->enableIRIn();
}

IRControl::~IRControl() {
    // TODO Auto-generated destructor stub
    delete irrecv;
}

void IRControl::menu() {
    if (irrecv->decode(&remoteValue)) {
        //lReceived = remoteValue.value ;
        Serial.println(remoteValue.value);
        /*
        switch(remoteValue.value)
                {
                case button1:
                    zustand = Motor1;
                    //digitalWrite (LED1, HIGH); // for control
                    break;

                case button2:
                    zustand = Motor2;
                    //digitalWrite (LED2, HIGH);
                    break;
                case button3:
                    zustand = Motor3;
                    //digitalWrite (LED3, HIGH);
                    break;

                case button0:
                    zustand = Sleep;
                    break;

                default: break;
                }
                */
        irrecv->resume(); // Receive the next value
      }
}

Where the problem could be
I think there could be a problem with the IRrecv *irrecv;. But i'm not sure.
Thanks for your help

I'd say you're just "receiving" random numbers. That most likely means your hardware setup is not what it should be. Unfortunately your answer only mentions software so nothing to comment about until you explain your hardware setup. And instead of immediately complicating things with complex code, I usually just start with the library's example code and check that my hardware setup is OK. Only then I continue with the software.

there are a number of ir protocols, you need to understand which one you are using, and use the right software/hardware and/or settings.  you cant just randomly throw ir at some random tool and expect it to work.

it not giving consistent results indicates that you have not matched up the receiver (protocol, frequency, etc) to the transmitter (the remote).

Thanks for your answers. However I used the same hardware setup for both projects. The problem appeared as I exported the code to my new class.

So I guess the general setting should be fine and there is an issue in the code.

Please post the code where you call the library. In particular where do you make an instance of IRControl?
I am guessing you are doing it at global scope which means you are probably running into the C++ static initialization order fiasco.
What it is: http://www.parashift.com/c++-faq/static-init-order.html
How to prevent it: http://www.parashift.com/c++-faq/static-init-order-on-first-use.html
To prevent this, you should not be doing this in the class constructor:
irrecv = new IRrecv(RECV_PIN);
pinMode(RECV_PIN , INPUT);
irrecv->enableIRIn();

Instead, make a begin function (like most Arduino classes do) and call that from setup.

btw. is http://www.parashift.com/c++-faq/static-init-order.html down?

Ok it works. I i create the objects in the main.cpp and changed my code in the IRControl. I think your answer was a good help. Should i update my question and add my solution?

btw. is parashift.com/c++-faq/static-init-order.html down? looks like it. It's the top Google hit for C++ static initialization order fiasco though.

Should i update my question and add my solution? - not really, because the question part is for the question. If you want to amplify on my answer with example code, etc. then make your own answer and explain what you had to change and why. It doesn't make a lot of sense if a question answers itself.

What you can do, if my answer was largely correct, but you want to add more detail, is to edit my answer and add in the detail. The edit will be added to an edit queue, but it will no doubt be accepted. That way the answer is fleshed out. If you think that your code is substantially different to what I posted, then post it as a separate answer.

Don't just post all your code though. Post the relevant parts, that solved the problem. This will help others in the future.


text:
Large arrays crash the arduino
I have three large PROGMEM arrays, in order to store musical notes for a song. One array is the notes, one is the note durations, and one is the pause after the note.
The first array is an int one and the other two are floats. The program works, but after a specific number of elements, the arduino crashes. Meaning, I upload the program without problems, but the device does nothing.
When I have 227 elements (in all three arrays) obviously, the program works. If I increase the number  of elements to 228, nothing happens when I upload...
When the IDE says avrdude: 10606 bytes of flash verified then everything works. When the size gets increased to 10616, everything crashes. Is this normal behaviour?
EDIT: The code is trivial, the only important part of the code is this:
int number_of_stored_values_in_MelodyArray = sizeof(Crash_Melody) / sizeof(int);
int Melody_Array[number_of_stored_values_in_MelodyArray];
memcpy_P(Melody_Array, Crash_Melody, sizeof Melody_Array);

I am using memcpy_P() in order to copy the arrays from PROGMEM to RAM.
I do this for the int and the two float arrays. With 221 elements in each array, I guess I am out of RAM.
The reason I have an array for the pause as well, is because I am using an online midi to tone() converter and that is the format that it uses. So I have to stick to that format.
I think if I did the assignment incrementally - like for example copy only 20 elements from the array, play the song, then repeat until the end, I would have no problem.
Is there a way for memcpy_P() to specify not the whole array to copy, but index them? Does it take a starting index value?
EDIT 2:
This is a snippet of code after trying Edgar Bonnet's approach.
int number_of_stored_values_in_MelodyArray = sizeof(My_Melody) / sizeof(int);
for (int i = 0; i < number_of_stored_values_in_MelodyArray; i++)
{
  int note = pgm_read_word(&My_Melody[i]);
  float duration = pgm_read_word(&My_noteDurations[i]);
  float pause_duration = pgm_read_word(&My_Delay[i]);
  playMelodyExtended2(note, duration, pause_duration, number_of_stored_values_in_MelodyArray, 10, 400);
}

int playMelodyExtended2(int melody, float noteDuration, float pauseDuration, int number_of_notes, int music_pin, int delay_var)
{
  for (int thisNote = 0; thisNote < number_of_notes; thisNote++)
  {
    tone( music_pin, melody, noteDuration );
    delay( pauseDuration );
    noTone(music_pin);
  }

  delay(delay_var);
}

EDIT 3:
This is the newest iteration of the code:
 int number_of_stored_values_in_MelodyArray = sizeof(My_Melody) / sizeof(int);
 for (int i = 0; i < number_of_stored_values_in_MelodyArray; i++)
 {
    int note = pgm_read_byte_near(&My_Melody[i]);
    note << 8;
    note += pgm_read_byte_near(&My_Melody[i+1]);
    float duration = pgm_read_float_near(&My_noteDurations[i]);
    uint16_t pause_duration = pgm_read_byte_near(&My_Delay[i]);
    pause_duration << 8;
    pause_duration += pgm_read_byte_near(&My_Delay[i+1]);
    playMelodyExtended2(note, duration, pause_duration, number_of_stored_values_in_MelodyArray, 10, 400);
  }

int playMelodyExtended2(int melody, float noteDuration, uint16_t pauseDuration, int number_of_notes, int music_pin, int delay_var)
{
  for (int thisNote = 0; thisNote < number_of_notes; thisNote++)
  {
    tone( music_pin, melody, noteDuration );
    delay( pauseDuration );
    // stop the tone playing:
    noTone(music_pin);
  }

  delay(delay_var);
}

why are duration and pauses represented by floats? ... they are not floats in music notation

What Arduino are you using? Could you share your code (without the array contents)?

also share the messages in the arduino IDE ... copy the text and paste into your question ... do  NOT use a screenshot ... do not put in a comment

the three arrays can be of type byte ... you only need two arrays ... a pause is just an unvoiced note ... use value 0 for pauses

As long as the last message of the compile and link tells you that you don't fill the flash over 100%, everything is fine. Anyway, please [edit] your question and provide a minimal, reproducible, and complete example. It can consists of just a big enough array and empty setup() and loop(). Add the output log.

Which Arduino? This is kind-of important. Assuming you have 32k of programmable memory (for example, on the Uno) then 2280 bytes of array should not crash it. I would be wondering about your code, frankly. The code you didn't post.

When the IDE says avrdude: 10606 bytes of flash verified then everything works. When the size gets increased to 10616, everything crashes. Is this normal behaviour? No, of course not.

I updated the question.

Is there a way for memcpy_P() to specify not the whole array to copy, but index them?  yes, well you could do: memcpy_P(&Melody_Array[10], Crash_Melody, 10); to get 10 bytes, but what Edgar Bonet said is a much better solution. Just access each note one at a time. There is no point in making the code complex by getting chunks of notes.

With your "Edit 2": Looks like the wrong number of bytes are being read for your floats or some number format conversion issue produces basically random numbers for your durations. Try pgm_read_float for reading the floats.

@orithena Thanks! Tried it as well, but now I hear a periodic beeping. All the beeps and pauses between are the same... I also tried pgm_read_byte_near() for the int variable, but with the same results...

@user1584421 This sounds as if there are some conversion issues. By using the pgm_read_* methods, you are basically saying "Read n bytes from Progmem and just put the bits into the variable". That means you need to know which bitsize the values are in your Progmem array, how many bits are read by the pgm_read_* methods, how many bits are in the target variable and whether it is a signed int, unsigned int or IEEE768-formatted float. Try to output the numbers (Serial.println as first line in playMelodyExtended2, outputting all arguments) and compare them to your input arrays.

@user1584421 It may also be a good idea to use the type int16_t, uint16_t, int32_t or uint32_t instead of a plain int. int actually is an alias, denoting the "standard int" for the CPU/platform you're compiling for; using one of the types above, you'll always know the bitsize of your variable. But this is a problem far off your original question, so a new question might be a good idea here (please also post the code that creates the PROGMEM array, as there might be some clues in there).

In the edited version of your question, you wrote:

I am using memcpy_P() in order to copy the arrays from PROGMEM to
RAM.

The whole purpose of PROGMEM is to avoid having to store the data in
RAM. If you copy the arrays to RAM, you are defeating PROGMEM. Your
Arduino has much more Flash than RAM, and it will crash if you eat up
all the RAM. This is why the PROGMEM optimization is valuable whenever
you have large arrays of constant data.
The proper way to use those arrays is to copy to RAM one element at a
time: get the data for the next note you have to play, then play it,
then move to the next one. E.g.:
for (int i = 0; i < melody_length; i++) {
    int note = pgm_read_word(&Crash_Melody[i]);
    // etc...
}

Copying small chunks to RAM, as you suggest in your question, would make
the code more complex and add absolutely no value.

Edit: In the second edit of your question, you have this:
float duration = pgm_read_word(&My_noteDurations[i]);

What this does is:

read the first two bytes of My_noteDurations[i] (which is a
four-byte quantity, thus you are truncating it)
interpret that as an integer (which it is not)
convert that to float

The result will have little to do with the original number. The correct
way to read a float from PROGMEM is to use pgm_read_float().
That being said, I see now that you use this number as a parameter for
delay(). Given that this function takes an integer, there is no point
in storing the delay as a float. This will only add a (somewhat costly)
float-to-integer conversion to your program, with no added benefit.
Also, since the delays are likely to be less than 65 seconds, a
16-bit unsigned integer should be enough.
Further down, you have this:
for (int thisNote = 0; thisNote < number_of_notes; thisNote++)
{
  tone(music_pin, melody, noteDuration);
  delay(pauseDuration);
  noTone(music_pin);
}

I fail to see the purpose of this loop. You are repeating each note
a number of times that is equal to the total number of notes in the
song. Why?

Answer to edit 3: there are a few issues I can see in this version
of the code.

Consistency of the data types: in the previous version, it looked
like the pause durations were floats. Now they are integers. You have
to make sure you use the pgm_read_*() function suitable for the
actual data type of the array.

Reading by bytes: there is no point in reading a 16-bit integer one
byte at a time: use pgm_read_word() to read it all at once. Reading
byte by byte only makes the code more complex and increases the
chances of bugs. In fact, your way of reconstructing the numbers is
buggy.

The loop in playMelodyExtended2() makes no sense to me. Please, try
removing it.

Here is what I suggest at this point:
for (int i = 0; i < number_of_stored_values_in_MelodyArray; i++)
{
    int note = pgm_read_word(&My_Melody[i]);
    float duration = pgm_read_float(&My_noteDurations[i]);
    uint16_t pause_duration = pgm_read_word(&My_Delay[i]);
    tone(10, note, duration);
    delay(pause_duration);
}

This snippet makes some assumptions about the rest of your code, and
specifically about the way your arrays are defined. If these assumptions
are incorrect, this will not work. Thus, I second @orithena's comment
and urge you to post a full, testable version of you sketch (three notes
would be enough).

Thanks! I tried your approach but it didn't work. I have posted the code in my question. All I hear is a constant buzz.

Thanks Edgar!  I tried pgm_read_float() as well, but all I heard was a periodic beeping. All the beeps and pauses between are the same... I also tried pgm_read_byte_near() for the int variable, but with the same results. I will try to trim the float array, since delay() receives only ints... As for why the code is like that.... Yes, I am iterating for every number of notes in the melody. I have found an online midi to tone() converter that outputs three arrays. The pitch, the note duration and the delay. So I created this function in order to handle it. This works but I am out of RAM

@user1584421: This iteration makes no sense. Try playing each note only once.

But how it should be done? This works. Like I said, the website the performs the conversion gives three arrays for each given note. Pitch, duration and delay....

However, since that function works, and its compatible with the format, why change it? There is an error probably, in how I parse that data from PROGMEM. I updated the question with what I last tried.

@user1584421 Yes, it works, but probably not in the way you want it to. If your array has 1283 notes, you call playMelodyExtended2 with number_of_notes = 1283. Then this for loop plays the first note 1283 times. It then returns, the next note/duration/delay is read, then playMelodyExtended2 is called again for that second note. And it plays that second note 1283 times. Repeat until all 1283 notes are played 1283 times each. Your Edit 3 also does not fix that.

I also tried the first approach, with memcpy_P, but I made the delay[] array as uint16_t. And this works, but then it suddenly stops.... So it is better, because with the original approach, it didn't play at all. But now, it still does not play the whole melody.

@orithena I get it now. I should remove the for loop inside the playMelodyExtended2() function. EDIT: I just did, and it does not work as intended.

@user1584421 Yes. You then may also remove the argument number_of_notes Or, alternatively, always call playMelodyExtended2 with number_of_notes = 1, if you need that argument in the future for other purposes.

@user1584421 Then it is time to finally post full code, especially the actual declaration of the PROGMEN arrays (the first three values of each array would suffice). Also, add that debugging output of the actual values in playMelodyExtended2 I mentioned yesterday, compare them to your input arrays, and after that, we may be able to help you further.

@EdgarBonet Thank you so much! This was it!

@orithena The last edit in this answer worked! My code was included in my question, it was what I posted. The PROGMEM definitions were trivial. `const int My_Melody[] PROGMEM =
{
55,
//...
};
const float My_noteDurations[] PROGMEM =
{
200.7139,
//....
};
const uint16_t My_Delay[] PROGMEM =
{
214,
//...
};`


text:
Detecting when a timer interrupt does not run
I am dealing with code thatt i received that relies heavily on timer interrupts.
i am using arduino Mega (Funduino)
More specifically, when a signal arrives in a pin, an interrupt is run that starts a timer. A different interrupt is run from inside the 1st interrupt, when the timer overflows.
The interrupts measure time between the incoming signal pulses, to figure out the resistance of a sensor, that is being produced from a supporting analog circuit.
The problem is when the sensor doesn't work. For example, the resistance is open circuited. Then the analog circuit does not produce and signal, and no interrupt is triggered.
My code is stuck on the loop() function. It cannot progress because it requires a flag to be set up ,from when the interrupt finishes execution (the interrupt sets that flag at the end).
What i would like to do, is to detect when the resistance is open circuited and move on.
This means i have to figure out how to detect when the interrupt is not run.
Perhaps i would set a timer to that flag that the interrupt sets? And if some time passes without the flag being set, this means that the interrupt did not run.
But using another timer (my interrupt already uses two timers) maybe would complicate things further. Any ideas?
Maybe i could also check if the pin that receives the signal does not receive anything for some time... Maybe this would be a better option. If it is, what's the best way to do so, considering the fact i already use two different timers?
This is the code:
/***** CONSTANTS *****/
const int BAUD_RATE = 9600;

const int INTERRUPT_PIN = 3;

const int S0_PIN = 4;
const int S1_PIN = 5;
const int S2_PIN = 6;
const int OE_BAR_PIN = 22;

const int NUM_OF_SENSORS = 8;

/***** ANALOG CIRCUIT CONSTANTS *****/
const double CAPACITOR_VALUE = 400; //pF
const double GAIN_VALUE = 3.5222672065;
const double R_BIAS_VALUE = 98.7; //kΩ

/***** GLOBAL VARIABLES *****/
int number_of_samples = 10;

int pulse_counter = 0;
byte measurement_counter = 0;

unsigned long overflows = 0;
unsigned long ticks = 0;
double period = 0;

boolean interrupts_enabled = false;
boolean measurement_finished = false;

int sensor_coord;

boolean full_mode = false;

void setup() {
  attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), count_time_of_k_pulses, RISING);

  pinMode(OE_BAR_PIN, OUTPUT);
  pinMode(S0_PIN, OUTPUT);
  pinMode(S1_PIN, OUTPUT);
  pinMode(S2_PIN, OUTPUT);

  TIMER1_init();

  Serial.begin(BAUD_RATE);
  while (! Serial);
}

void loop() {
  if (Serial.available()) {
    /***** DEFINE MEASUREMENT MODE *****/
    String input = Serial.readString();
    if (input[0] == 'r' && interrupts_enabled == false) {
      if (input[1] == 'f') {
        full_mode = true;
        sensor_coord = 0;
      } else
        sensor_coord = input[2] - '0';

      select_sensor();

      /***** SET VARIABLES FOR DUMMY MEASUREMENT *****/
      number_of_samples = 10;

      pulse_counter = 0;
      measurement_counter = 0;

      TIMER1_clear();

      interrupts_enabled = true;
    }
  }

//THIS IS WHERe I BELIEVE THE CHECK SHOULD OCCUR, OF WHETHER THE INTERRUPT DID NOT RUN. OR WHETHER THE PIN 3 IS RECEIVING A ZERO SIGNAL FOR SOME TIME

  if (measurement_finished) {
    measurement_counter++;

    ticks = (overflows * 65536) + TCNT1;
    period = (ticks * 0.0625) / (number_of_samples - 1);

    if (measurement_counter == 1) {
      /***** SET VARIABLES FOR MEASUREMENT *****/
      number_of_samples = 500;

      pulse_counter = 0;

      TIMER1_clear();

      interrupts_enabled = true;
    }
    else {
      TIMER1_print_results();

      if (full_mode) {
        sensor_coord++;

        select_sensor();

        /***** SET VARIABLES FOR DUMMY MEASUREMENT *****/
        number_of_samples = 10;

        pulse_counter = 0;
        measurement_counter = 0;

        TIMER1_clear();

        interrupts_enabled = true;

        if (sensor_coord == NUM_OF_SENSORS) {
          full_mode = false;
          interrupts_enabled = false;
        }
      }
    }
    measurement_finished = false;
  }
}

/***** INTERRUPT ROUTINES *****/

void count_time_of_k_pulses() {
  if (interrupts_enabled) {
    pulse_counter++;

    if (pulse_counter == 1)
      TIMER1_start();

    if (pulse_counter == number_of_samples) {
      TIMER1_stop();

      measurement_finished = true;
      interrupts_enabled = false;
    }
  }
}

ISR (TIMER1_OVF_vect) {
  overflows++;
}

/***** FUNCTION FOR SENSOR SELECTION *****/

void select_sensor() {
  digitalWrite(OE_BAR_PIN, LOW);
  digitalWrite(S2_PIN, ((sensor_coord & 4) == 4) ? HIGH : LOW );
  digitalWrite(S1_PIN, ((sensor_coord & 2) == 2) ? HIGH : LOW );
  digitalWrite(S0_PIN, ((sensor_coord & 1) == 1) ? HIGH : LOW );
}

/***** TIMER1 FUNCTIONS *****/

void TIMER1_init() {
  TCCR1A  = 0;
  TCCR1B  = 0;
  TIMSK1  = 0;
  TCCR1B |= (0 << CS12) | (0 << CS11) | (1 << CS10);
}

void TIMER1_start() {
  TIMSK1 |= (1 << TOIE1);
}

void TIMER1_stop() {
  TIMSK1 = 0;
}

void TIMER1_clear() {
  TCNT1     = 0;
  overflows = 0;
}

void TIMER1_print_results() {
  Serial.println("----------------------------------------");
  Serial.print("SENSOR COORDINATE         = ");
  Serial.println(sensor_coord);

  Serial.print("NUMBER OF PULSES MEASURED = ");
  Serial.println(pulse_counter);

  Serial.print("TIMER1 VALUE              = ");
  Serial.println(TCNT1);

  Serial.print("TIMER1 OVERFLOWS          = ");
  Serial.println(overflows);

  Serial.print("TICKS                     = ");
  Serial.println(ticks);

  Serial.print("MEASURED PERIOD           = ");
  Serial.print(period);
  Serial.println(" US");

  Serial.print("MEASURED RESISTANCE       = ");

  double resistanse = ((period * GAIN_VALUE * 1000) / (4 * CAPACITOR_VALUE)) - R_BIAS_VALUE; //kΩ
  Serial.print(resistanse);

  Serial.println(" kΩ");

  Serial.println("----------------------------------------");
}

EDIT: This is the updated code, with help from chrisl.
Only the lines or blocks of code with '!!!!!!!!!!!' are new, so there is not much new code.
/***** CONSTANTS *****/
const int BAUD_RATE = 9600;

const int INTERRUPT_PIN = 3;

const int S0_PIN = 4;
const int S1_PIN = 5;
const int S2_PIN = 6;
const int OE_BAR_PIN = 22;

const int NUM_OF_SENSORS = 8;

/***** ANALOG CIRCUIT CONSTANTS *****/
const double CAPACITOR_VALUE = 400; //pF
const double GAIN_VALUE = 3.5222672065;
const double R_BIAS_VALUE = 98.7; //kΩ

/***** GLOBAL VARIABLES *****/
int number_of_samples = 10;

byte measurement_counter = 0;

unsigned long overflows = 0;
unsigned long ticks = 0;
double period = 0;

//variables for determining if a resistance cannot be measured !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
unsigned long timestamp = 0;
unsigned long measurement_timeout = 5000;  //5 secods is the timeout time
boolean sensor_corruption[7]; //each element of the array is the sensor info. If false, resistance is working. If it's true, resistance is open.
boolean ISR_unavailable = false; //this flag is raised, when the ISR dose not run, because no signal comes from the circuit, because resistance is open circuit
boolean setup_finished = false;

//variables that get changed inside the ISR - thus are declared volatile!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
volatile int pulse_counter = 0;
volatile boolean interrupts_enabled = false;
volatile boolean measurement_finished = false;

int sensor_coord;

boolean full_mode = false;

void setup() {
  attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), count_time_of_k_pulses, RISING);

  pinMode(OE_BAR_PIN, OUTPUT);
  pinMode(S0_PIN, OUTPUT);
  pinMode(S1_PIN, OUTPUT);
  pinMode(S2_PIN, OUTPUT);

  TIMER1_init();

  Serial.begin(BAUD_RATE);
  while (! Serial);

  //Initializing all array elements to false!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  for (int i=0; i<=7; i++)
  {
    sensor_corruption[i] = false; // false means it's working ok. true means it's corrupted
  }

  setup_finished = true; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

}

void loop()
{
  if (Serial.available())
  {
    /***** DEFINE MEASUREMENT MODE *****/
    String input = Serial.readString();
    if (input[0] == 'r' && interrupts_enabled == false)
    {
      if (input[1] == 'f')
      {
        full_mode = true;
        sensor_coord = 0;
      } else
        sensor_coord = input[2] - '0';

      select_sensor();

      /***** SET VARIABLES FOR DUMMY MEASUREMENT *****/
      number_of_samples = 10;

      pulse_counter = 0;
      measurement_counter = 0;

      TIMER1_clear();

      interrupts_enabled = true;
    }
  }

// TIMEOUT CODE HERE. TO DETERMINE IF A RESISTANCE IS OPEN CIRCUITED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  if(setup_finished && millis() - timestamp > measurement_timeout)
  {
    sensor_corruption[sensor_coord] = true; //label the resistance (indicated by sensor_coord) as true in the boolean array. this means it's open circuited (no signal from circuit)
    measurement_finished = true;
    interrupts_enabled = false;
    ISR_unavailable = true;
  }

  if (measurement_finished)
  {
    //This does not get executed when the resistance is open circuited
    if (!ISR_unavailable) //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! this if statement is the only thing i added here
    {
      measurement_counter++;

      ticks = (overflows * 65536) + TCNT1;
      period = (ticks * 0.0625) / (number_of_samples - 1);

      if (measurement_counter == 1)
      {
         /***** SET VARIABLES FOR MEASUREMENT *****/
        number_of_samples = 500;

        pulse_counter = 0;

        TIMER1_clear();

        interrupts_enabled = true;
       }
    }
    else
    {
      TIMER1_print_results();

      if (full_mode)
      {
        sensor_coord++;

        select_sensor();

        /***** SET VARIABLES FOR DUMMY MEASUREMENT *****/
        number_of_samples = 10;

        pulse_counter = 0;
        measurement_counter = 0;

        TIMER1_clear();

        interrupts_enabled = true;

        if (sensor_coord == NUM_OF_SENSORS)
        {
          full_mode = false;
          interrupts_enabled = false;
        }
      }
    }
    measurement_finished = false;
    ISR_unavailable = false; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    timestamp = millis();  //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  }
}

/***** INTERRUPT ROUTINES *****/

void count_time_of_k_pulses() {
  if (interrupts_enabled) {
    pulse_counter++;

    if (pulse_counter == 1)
      TIMER1_start();

    if (pulse_counter == number_of_samples) {
      TIMER1_stop();

      measurement_finished = true;
      interrupts_enabled = false;
    }
  }
}

ISR (TIMER1_OVF_vect) {
  overflows++;
}

/***** FUNCTION FOR SENSOR SELECTION *****/

void select_sensor() {
  digitalWrite(OE_BAR_PIN, LOW);
  digitalWrite(S2_PIN, ((sensor_coord & 4) == 4) ? HIGH : LOW );
  digitalWrite(S1_PIN, ((sensor_coord & 2) == 2) ? HIGH : LOW );
  digitalWrite(S0_PIN, ((sensor_coord & 1) == 1) ? HIGH : LOW );
}

/***** TIMER1 FUNCTIONS *****/

void TIMER1_init() {
  TCCR1A  = 0;
  TCCR1B  = 0;
  TIMSK1  = 0;
  TCCR1B |= (0 << CS12) | (0 << CS11) | (1 << CS10);
}

void TIMER1_start() {
  TIMSK1 |= (1 << TOIE1);
}

void TIMER1_stop() {
  TIMSK1 = 0;
}

void TIMER1_clear() {
  TCNT1     = 0;
  overflows = 0;
}

void TIMER1_print_results() {
  Serial.println("----------------------------------------");
  Serial.print("SENSOR COORDINATE         = ");
  Serial.println(sensor_coord);

  //Added the if-else statement, to cover the possibility of open circuited resistance !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  if (sensor_corruption[sensor_coord])
  {
  Serial.println("This resistance is open circuited!!!");
  }
  else
  {
  Serial.print("NUMBER OF PULSES MEASURED = ");
  Serial.println(pulse_counter);

  Serial.print("TIMER1 VALUE              = ");
  Serial.println(TCNT1);

  Serial.print("TIMER1 OVERFLOWS          = ");
  Serial.println(overflows);

  Serial.print("TICKS                     = ");
  Serial.println(ticks);

  Serial.print("MEASURED PERIOD           = ");
  Serial.print(period);
  Serial.println(" US");

  Serial.print("MEASURED RESISTANCE       = ");

  double resistanse = ((period * GAIN_VALUE * 1000) / (4 * CAPACITOR_VALUE)) - R_BIAS_VALUE; //kΩ
  Serial.print(resistanse);

  Serial.println(" kΩ");
  }

  Serial.println("----------------------------------------");
}

And this is the output i get:
----------------------------------------
SENSOR COORDINATE         = 0
This resistance is open circuited!!!
----------------------------------------
----------------------------------------
SENSOR COORDINATE         = 1
This resistance is open circuited!!!
----------------------------------------
----------------------------------------
SENSOR COORDINATE         = 2
This resistance is open circuited!!!
----------------------------------------
----------------------------------------
SENSOR COORDINATE         = 3
This resistance is open circuited!!!
----------------------------------------
----------------------------------------
SENSOR COORDINATE         = 4
This resistance is open circuited!!!
----------------------------------------
----------------------------------------
SENSOR COORDINATE         = 5
This resistance is open circuited!!!
----------------------------------------
----------------------------------------
SENSOR COORDINATE         = 6
This resistance is open circuited!!!
----------------------------------------
----------------------------------------
SENSOR COORDINATE         = 7
This resistance is open circuited!!!
----------------------------------------
----------------------------------------
SENSOR COORDINATE         = 8
This resistance is open circuited!!!
----------------------------------------
----------------------------------------
SENSOR COORDINATE         = 8
This resistance is open circuited!!!
----------------------------------------
----------------------------------------
SENSOR COORDINATE         = 8
This resistance is open circuited!!!
----------------------------------------
----------------------------------------
SENSOR COORDINATE         = 8
This resistance is open circuited!!!
----------------------------------------
----------------------------------------
SENSOR COORDINATE         = 8
This resistance is open circuited!!!
----------------------------------------

As you can see, all the resistances are falsely labeled as open circuited.
Not only that but for some reason, it measures resistance 8 which does not exist, multiple times. Actually then it loops forever on resistance 8 (Normal operation stops at resistance 7 )

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

I tried to understand your program and found quite a few issues, which I
am listing below. This is more a general review than a specific answer.
I hope it nevertheless helps you fix the code.
The major issue is the logic of loop() being quite convoluted and hard
to follow. My guess is that the issue you face is a direct consequence
of this single problem. I won't propose a fix because I can't really
understand what this logic is supposed to accomplish. I think this
problem is rooted in that logic having too much “state”, i.e. too many
global variables that influence its behavior.
You may be able to make the logic of the function a lot clearer if you
consolidate various state-defining variables into a single enum
variable named state, and write the logic as in a regular finite
state machine. This should make it a lot easier to understand,
which in turn should make the bugs evaporate like magic.
Now, some specific details in the code.
I can't understand the purpose of measurement_counter. It is used only
in the test if (measurement_counter == 1). A boolean named
first_measurement may be more appropriate here. Better yet if you can
merge it into the unique state variable.
The variable setup_finished has no purpose at all. It is used only in
loop() to test whether setup() is done. However, loop() only
starts running after setup() is complete, so the test is pointless.
The handling of OE_BAR_PIN looks wrong: the pin goes LOW in
setup() and never goes HIGH again. It would seem saner to initialize
it HIGH, keep it HIGH when toggling the sensor-select pins, and only
turn it LOW once a sensor has been properly selected. Thus:
void setup() {
  ...
  digitalWrite(OE_BAR_PIN, HIGH);
  pinMode(OE_BAR_PIN, OUTPUT);
  ...
}

void select_sensor() {
  digitalWrite(OE_BAR_PIN, HIGH);
  digitalWrite(S2_PIN, ((sensor_coord & 4) == 4) ? HIGH : LOW );
  digitalWrite(S1_PIN, ((sensor_coord & 2) == 2) ? HIGH : LOW );
  digitalWrite(S0_PIN, ((sensor_coord & 1) == 1) ? HIGH : LOW );
  digitalWrite(OE_BAR_PIN, LOW);
}

Note that setup() turns the pin HIGH before setting it as
OUTPUT: this prevents an unwanted short LOW pulse.
The handling of Timer 1 is also flaky: it runs continuously.
TIMER1_start() and TIMER1_stop() start and stop the overflow
counting, not the timer itself. This means the measured tick count can
be off by as much as ±65,535 ticks. It would be more sensible to really
start and stop the timer as needed:
void TIMER1_init() {
  TCCR1A  = 0;
  TCCR1B  = 0;
  TIMSK1 |= (1 << TOIE1);
}

void TIMER1_start() {
  TCCR1B |= (0 << CS12) | (0 << CS11) | (1 << CS10);
}

void TIMER1_stop() {
  TCCR1B  = 0;
}

You probably want to call TIMER1_stop() when you detect a timeout.

About the measurement_counter.. The first time you perform a measurement, the data is false.
Thats why we do the first measurement with 10 samples, just to get rid of it.
The second time we do a measurement, we do it properly with 500 samples.
Measurement-counter is the toggle between these two.
b) I removed the setup_finished and all related stuff. c) About the OE_BAR_PIN and handling of Timer1, i didn;t quite get your points, but i tested your code and the results are similar so i guess you are probably right. d)My code is still stuck in the bracjket where i detect a timeout and i

Don't k know why. It just cannot exit that region, whether it receives pulses or not. You also said "You probably want to call TIMER1_stop() when you detect a timeout." How will that play out in my code for timeout detection?

Thanks a lot for the input. Utilizing your advice, i managed to make the sketch work with one set of measurements, as opposed to using two sets fo measurements because the first one always yielded wrong results. It probably had something to do with the timers, which your implementation solved completely. I don't understand what you did with the timers, but it worked.

In your code you are using the measurement_finished variable as a flag, that a new measurement was finished inside the ISRs, so that it can be handled inside the loop() function. This is very useful. As I understood, an open circuit means, that no measurement can happen, since no pulses are created. So you need to check, how much time passed since the last measurement.
Also the Arduino core sets up Timer0 for general timekeeping purposes. For example the delay() function uses it, and also functions like micros() and millis(), which will return the number of micro/milli-seconds elapsed since startup. So, if you are using these functions, you are actually using a hardware timer, but you don't have to set it up yourself. It is already done by the Arduino core.
So I suggest a principle similar to the BlinkWithoutDelay example from the Arduino IDE. First you define a global timestamp variable and a timeout value (here 1s aka 1000ms):
unsigned long timestamp=0;
unsigned long measurement_timeout=1000;

Then inside your loop() function (in fact you can do this exactly, where you placed the corresponding comment for the check), you check for the difference between the current time and the timestamp:
if(millis() - timestamp > measurement_timeout){

This will trigger, when the timestamp was last updated 1s ago. Inside this measurement, you do, what ever you need to do, if a measurement timeout happens (like printing an appropriate message to Serial). And now, we want to start a new timeout by updating the timestamp variable to the current time, as given by millis(). We could do this inside the corresponding ISR, but that would give us a problem. The ISR could fire right in between of the calculation of our if statement. This cannot happen for single byte variables (as for an 8 bit controller the current 8 bit action will be completed in one step), but unsigned long has 4 bytes. We would need to disable interrupts, when accessing it, to keep it from getting corrupted.
So we can simply set the timestamp inside the
if (measurement_finished) {

statement in the loop function. There we simply do
timestamp = millis();

to update the timestamp. As long, as the if statement is evaluated often enough (at least 1 time during the timeout range), it will work.
So, what happens in the changed code? When you start the code, it might think, that a zero measurement was done (if your setup() function needs longer than the timeout), but as soon, as the first measurement arrives, the if (measurement_finished) statement will execute and update the timestamp. Now the millis() if statement is disabled for the timeout duration, each new finished measurement will reset this timeout. It is like a dead man's switch. The timeout will trigger, when there is no one (or no code) to reset the timeout again.

BTW: As you are using interrupt routines, you should declare all variables, that get changed in an ISR as volatile like this:
volatile int pulse_counter = 0;

If you are not doing this, the compiler might optimize the variable to use a cached value, instead of the real value. Also think about, what I wrote above about variables changed by ISRs in the middle of a calculation. You have to be careful to not run in difficult to debug situations, if you don't protect your variables in the main code against change from an ISR.

Thank you very much for your help. I tried your approach, but unfortuantely, for some reason, it gets all my resistances as open circuited. Not only that, but one  resistance is measured multiple times. I will edit and post my new code. All the lines that have this character is the ones i added. So not much code is new.

These characters (!!!!!!!!!!!)

After further testing, your solution does not work, as it always stays in that block. Instaed of only staying when the interrupt doesnt run.

Why are you doing interrupts_enabled = false; at a timeout? As I understand your code, that would prevent any new pulses to be measured. Also you set measurement_finished to true, despite you not having a finished measurement. This resets the timestamp in the next if statement, but you don't turn on the interrupts through the variable there. Without the ISR actually measuring pulses, you again run into a timeout. So the interrupt is only reactivated if you send the corresponding serial data. And I don't know, why you habe the ISR_unavailable variable. Don't see, where you would need it

Also I'm agreeing with Edgar, that rewriting your code with an FSM with 1 state variable will lead to a simpler, cleaner and a lot easier to debug code.

I corrected the interrupts_enabled = false; at the timeout. I set the measurement_finished to true, in order to enter the next block of code (which is necessary). It then resets the timestamps like you said, but the interrupts are on niw, since i corrected the interrupts_enabled. The ISR_unavailable makes sure that the bracket of code does not run, but instaed moves forward. Still with all these cahnges, the code is stuck on the if(millis() - timestamp > measurement_timeout){ bracket, labelling all resistances as open-circuit. In other words, it is impossible to escape this bracket.

If everytghing works correctly, why does it even enter that block of code?


text:
Are there any advantages to Wifi shields as opposed to a Yun?
I have an Arduino Uno and I have a remote sensing project for which I need Wifi connectivity. After doing research, I've found that I have 2 options:

Buy a WiFi shield for my existing Uno
Buy an Arduino Yun with built-in WiFi

Looking at costs, I found that a WiFi shield costs more than double what it costs to buy a Yun, so it would seem to me that the best option is the Yun as I'd save some cash and get a more capable board. However, I can't help but think I'm missing something.
What are the advantages of an Uno plus Wifi shield as opposed to a Yun?

Have you considered using an ESP8266-based dev board? NodeMCU, for example. This is a single SoC solution that can be had for less than 5USD with integrated WiFi. Remote sensing and logging via HTTP to a web service is ridiculously easy.

I didn't even realize it was an option to be honest @uint128_t, I didn't think anything that inexpensive would actually be a wifi device!

There's a number of things to consider that could sway your choice one way or another:
Power consumption
The Uno is a small low-power chip to which you add WiFi. The Yun is an Arduino Leonardo with a WiFi router (like you have on your desk) strapped to the back of it.  The Yun will therefore consume considerably more power than the Uno.
Boot time
The Uno takes about 1 second to boot up - faster (instant) if you remove the bootloader and program it direct with a programmer.  The Yun takes minutes to boot.
Stability
The Uno is a solid state single item. The Yun has an entire operating system with filesystems and things.  It's far more likely that the Yun will corrupt itself through power loss than an Uno will get struck by a stray neutrino.
Cost
Yes, the Yun is cheaper. But is cheap always good?
Remote-ability
The Yun can be completely reprogrammed remotely. A new sketch can be uploaded to the Leonardo portion of it without you even having to be in the same country. The same can't be said for the Uno.
Power
The Linux portion of the Yun is considerably more powerful than any normal Arduino.

This is very good information @Majenko, probably the best synopsis of the two boards I've seen.

I have more to add now I have been thinking about it.

First of all yun is not the same as uno + wifi shield. yun is more like a linux pcc with wifi and a lenoardo.
If you are asking for your options there are more options. For what you want I would go for a ESP8266. Again there are 2 options here:

uno + ESP8266 (as a wifi shield)
ESP8266 (as a dev board)

I think it is pretty obvious that the ESP8266 (as a dev board) is the most cost effective.
You can program the ESP8266 just like a uno in the arduino IDE.
So I would advice to take that board.

There aren't just two options.
There are also Dragino and Iduino Yun shields, which are (usually) slightly cheaper than an Arduino Yun. These can be plugged into Leonardo/Uno base boards.
Whereas an Uno or Leonardo requires about 6-7v from the power supply, a Yun shield requires 9-12v (due to the Atheros chip drawing a bit extra).
There is also the Tian, which is the Yun's successor (but at higher cost).
If you're willing to look further afield than Arduino only, you might want to consider a BeagleBone Black (which works out slightly cheaper in terms of cost/feature).


text:
Why digital pin not reading ON from push button switches connected to 5V and pull-down 10K resistor?
Here's my circuit:

And the code:
//pins
const int control1 = 2;
const int control2 = 3;
const int enable = 9;
const int pinDirection = 4;
const int pinOnOff = 5;
const int pot = A0;
//states
int stateOnOff = 0;
int stateOnOffPrev = 0;
int stateDirection = 0;
int stateDirectionPrev = 0;

int motorEnabled = 0;
int motorSpeed = 0;
int motorDirection = 1;

void setup(){
  pinMode(pinDirection, INPUT);
  pinMode(pinOnOff, INPUT);
  pinMode(control1, OUTPUT);
  pinMode(control2, OUTPUT);
  pinMode(enable, OUTPUT);

  digitalWrite(enable, LOW);
  Serial.begin(9600);
}

void loop(){
  stateOnOff = digitalRead(pinOnOff);
  delay(10);
  stateDirection = digitalRead(pinDirection);
  motorSpeed = analogRead(pot)/4;

  if(stateOnOff != stateOnOffPrev){
    if(stateOnOff == HIGH){
      motorEnabled = !motorEnabled;
    }
  }

  if(stateDirection != stateDirectionPrev){
    if(stateDirection == HIGH){
      motorDirection = !motorDirection;
    }
  }
Serial.println(stateDirection);
  if(motorDirection == 1){
    digitalWrite(control1, HIGH);
    digitalWrite(control2, LOW);
  }else{
    digitalWrite(control1, LOW);
    digitalWrite(control2, HIGH);
  }

  if(motorEnabled == 1){
    analogWrite(enable, motorSpeed);
  }else{
    analogWrite(enable, 0);
  }

  stateDirectionPrev = stateDirection;
  stateOnOffPrev = stateOnOff;

}

As you can see, the switch on pin 5 controls whether the motor is on and the potentiometer controls motor speed. Both work.
However, when the switch on pin 4 is closed the stateDirection variable still reads 0, or open circuit. It should when pressed change the direction of the motor via the H-bridge. I've tried everything I could, new switches, higher resistance. The only time it read HIGH is when I literally plugged switch out to GND.
Serial shows stateDirection as an unending chain of zeroes.
And finally the schematics from the original project.

Thank you.
**PS: Forgive for lack of comments! But I think a good Arduino programmer should not need comments. **

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

What if you use an empty breadboard and put in a button and resistor only? And make your code print the button state over and over?

when the switch on pin 4 is closed the stateDirection variable still reads 0, or open circuit.

you could have pull-up enabled on that pin: with a nominal value of 50k, 10k pull-down is just on the cusp of making it a logic low.
solution?
1) disable pull-up;
2) use a stronger pull-down;
3) get rid of the pull-down and rely on the pull-up alone.
...

If it shows low when bypassing switch and jumping to ground.. Then either bad switch or maybe simply wrong orientation of switch.
Edit: if GND is making pin 5 HIGH in logic, then your button needs to jump to GND and have the resistor on 5v. Currently it is opposite according to your schematic.

authors: Антонов Кирилл


text:
Is applying 5 volts to LED dangerous?
The Arduino Uno manual (from the kit) instructs to connect a resistor to GND when lighting an LED on the breadboard with the 5V (socket?). The red, green, and yellow LEDs don't light up so brightly... actually they are barely bright enough to detect. Is it safe to apply all 5 volts by connecting the cathode to the ground with a wire? I tried it for a second and it worked... Just don't try it on the blue, I assume that beyond 5V it will explode, it burnt so bright..
Optional: Why does only the blue LED light visibly?

So you want to know if you should use a resitor along with the LED?

The brigtness of an LED depends on the voltage acorss it and the resistor value that used in series when it connect to a power supply. You will find varying the voltage and resistor values will cause the LED to have different brightness.

I don't understand why people downvote (and I don't want you to upvote). I'm just asking a beginner question that I cannot find answer to on Google. Should I put "WARNING: BEGINNER QUESTION" at the beginning of my question?

@Roman I see that someone has flagged this question as "off-topic" I think it's actually a very relevant question (though may fit better on electronics.se, but they'll probably dislike your question anyway). I must say that your question is also not very clear, you seem to ask a lot of different questions at once.

I'll vote to leave your question open, since it already has a lot of good answers. You may want to try to cleanup the question (make it clearer) for future reference.

Different color LEDs are not the same.  The are made with different impurities.  And some colors (blue) were really hard to figure out.  So much so that the blue LED inventor was awarded the Nobel Prize!
Consequently, it should not be assume all LEDs operate at the same voltage and current.  As such, when driving an LED with a constant voltage source, derive the proper series resistance for each case.
Example 1:
Given a red LED which may have 1.8 volt drop and may need 20mAmps to operate driven by a 5 volt source, we find the proper series resistor to be...

V = I * R
5 - 1.8 = 20mA * R
R = (5 - 1.8) / 0.020
R = 160 ohms

Example 2:
Given a blue LED which may have a 3.3 volt drop and may need 20mAmps to operate driven by a 5 volt source, we find the proper series resistor to be...

V = I * R
5 - 3.3 = 20mA * R
R = (5 - 3.3) / 0.020
R = 85 ohms

Your specific LEDs may have different specifications.  The above are only examples.
Go here for more about calculating the proper LED series resistance.
In general, LEDs that are over driven will grow dimmer and not recover.

No, you cannot safely power an LED with 5V without a resistor. The resistor is absolutely 100% required.
The resistor isn't put there purely on a whim, it's required to set the current based on the supply voltage minus the LED forward voltage and the resistance of the resistor.

What would happen if the LED recieved 5V for longer than a second?

It will probably survive, since the internal resistance of the supply will limit the available current. You should be more worried about what is providing the 5V - that won't be too happy.

Looks like the 5V pin providing the 5V

An IO pin? Then you will be stressing that IO pin considerably and sustained usage will result in the death of that IO pin as the high-side drive MOSFET burns out through excess current.

@Roman You can get LED's with integrated resistors if you dont want to use your own resistor

No, not the IO pin. I have little experience with this, but thank you for details. I'll have to bookmark this to read later.

@qwerty10 I have the whole kit from Amazon that comes with 100 resistors. So I think I'll watch and learn from exploding LEDs than use fancy LEDs :-)

Ah. I found it. From the manual:

Without the resistor, the LED would be brighter for a few moments, but quickly burn out.

Since 5V is HIGH on this thing, it looks like 5V would be too much for an LED.
Question 2: You were using the wrong resistor (too much resistance). But even with the incorrect resistor, the blue one shined! Strange.

Blue LEDs tend to be very efficient and will even give a little bit of light when the current is in the micro amps range. PS running too much current through LEDs can be fun. They sometimes give a different color light for a while before dying. They won't explode. They can release a bit of smoke though.

Something else to take into consideration (as if this is not complex enough) is that if you're comparing LEDs visually you're not always going to be able to tell if your math is correct.
The human eye is about 3x more sensitive to blue light (and green light for that matter) than it is to red light.
So, presume that you had 3 absolutely identically manufactured LEDs: 1 Red spectrum, 1 Blue spectrum, and 1 White ("full spectrum"). If they are all hooked up with proper current, the Blue LED will appear to be approximately 3x the brightness of the Red LED (to your human eyeballs) and the White LED will appear to be some large factor brighter than the Red LED as well, and likely some factor brighter than the Blue even as it contains more 'spectrum'.
TL;DR: Check your layouts with a volt meter and math, not with your crummy eyeballs.


text:
Arduino nano select port option is blurred | Driver issue
I have just bought arduino nano board. when i connect the board via usb, system detects the new device but i am not able to select port in arduino ide for writing any code on board. I checked my device manager it says

The drivers for this device are not installed. (Code 28)
There are no compatible drivers for this device.

I have also updated my board and library list in arduino ide.
please help me out?

What USB<->uart chip is on the board? Usually on the back (often FTDI, CH340G or CPxxxx).

CH340 is on board

My PCs and Raspberry Pis that I use to program Arduinos all have already had the CH340 driver installed.  Vista, Win7, Win8.1, Rpi3B with Raspbian - all worked fine.  But it is possible you need to install a driver.  I see your answer describes how to do so.  Kudos.

on my nano board CH340G USB<-->uart chip was present, so i installed driver for that chip and everything works fine now. :P
link for the driver (windows 8,10): http://www.arduined.eu/ch340-windows-8-driver-download/

Good, looks like you managed to fix the issue yourself!

This is good information to have in the stackexchange database.  Thank you for posting the link.


text:
MPU 6050 stuck on same values
I'm having a problem with my MPU6050. I'm using PID to speed up a motor with the MPU values. What could the problem be?
Here is a link to a previous question that I asked concerning a problem with pid: PID not working correctly
These are the values that I'm getting, which repeat forever. The values are:

motor speed;
the value that changes the motor speed;
the MPU value;
the change that PID made.

0.00
0
10900
4800

0.00
0
10900
4800

Here is the code itself.
int16_t ax, ay, az;

double Setpoint, Input, Output;
//Specify the links and initial tuning parameters
double Kp=2, Ki=5, Kd=1;
PID myPID(&Input, &Output, &Setpoint, Kp,Ki,Kd, DIRECT);

void setup() {
 Input = analogRead(ax);
  Setpoint = 100;
  //turn the PID on
   myPID.SetMode(AUTOMATIC);
}

void loop() {
 accelgyro.getAcceleration(&ax, &ay, &az);
  int a=ax+10900;
//Here I set the used variable to around 0. ax is actually around -10900
//This is always true, this won't be in the final code. This is just making        it work.

if(1) {
 int val;
  val = map(a, -1300, 1300, 0, 1023);
   Input = val;
    myPID.Compute();
     Serial.println(Output);

digitalWrite(motorPin2, HIGH);
Serial.print("\t");
Serial.println(ax);
Serial.print("\t");
Serial.println(a);
Serial.print("\t");
Serial.println(val);
     }
}

Please post a Minimal, Complete, and Verifiable example - I don't see, for example, where you are printing the other numbers. And why do you do an analogRead in setup?

I added the prints. I think  my teacher did the analogread. Not sure if its supposed to be there. This code has worked before. I think its the pins thats wrong or something.

Let's deconstruct this down to a simple example which we can test without the MPU6050:
#include <PID_v1.h>

double Setpoint, Input, Output;
//Specify the links and initial tuning parameters
double Kp = 2, Ki = 5, Kd = 1;
PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);

void setup() {
  Setpoint = 100;
  //turn the PID on
  myPID.SetMode(AUTOMATIC);
  Serial.begin (115200);
  Serial.println (F("\n\nStarting\n\n"));
}

void loop() {
  int a = 0;
  int val = map(a, -1300, 1300, 0, 1023);
  Input = val;
  myPID.Compute();
  Serial.print (F("Input = "));
  Serial.println(Input);
  Serial.print (F("Setpoint = "));
  Serial.println(Setpoint);
  Serial.print (F("Output = "));
  Serial.println(Output);
  Serial.println();
  delay (300);
}

Output:
Starting

Input = 511.00
Setpoint = 100.00
Output = 0.00

Input = 511.00
Setpoint = 100.00
Output = 0.00

Input = 511.00
Setpoint = 100.00
Output = 0.00

Input = 511.00
Setpoint = 100.00
Output = 0.00

Indeed it isn't changing. Let's analyze why:

The input is 511
The setpoint is 100
Therefore the error is 100 - 511 = -411
Disregarding (for the moment) the integral and differential terms, you have a proportional term of 2 (Kp) so the algorithm tries to output 2 * Error
Output would be 2 * -411 = -822
However the maximum and minimum limits default to 0 to 255, and thus the output is clamped to 0.
The algorithm outputs 0.
And the next time it does the same thing.

There is a function SetOutputLimits which can be used to change the default minimum and maximum output values.
The Ki and Kd values might eventually have an impact, but you won't notice anything with the output clamped to zero.
For example, adding this line in setup gives different results:
  myPID.SetOutputLimits (-5000, 5000);

Result:
Starting

Input = 511.00
Setpoint = 100.00
Output = -5000.00

Input = 511.00
Setpoint = 100.00
Output = -1233.00

Input = 511.00
Setpoint = 100.00
Output = -1438.50

Input = 511.00
Setpoint = 100.00
Output = -1644.00

Input = 511.00
Setpoint = 100.00
Output = -1849.50

Input = 511.00
Setpoint = 100.00
Output = -2055.00

Input = 511.00
Setpoint = 100.00
Output = -2260.50

Input = 511.00
Setpoint = 100.00
Output = -2466.00

Whether they are valid limits depend on what you are attempting to do exactly.

Im still having the problem that the mpu's value doesnt change

The problem was that I had the SCL and SDA pins connected to the wrong Arduino pins.
Sorry for bothering your time. Thanks for the tips.

authors: محمدرضا کیانی


text:
Controlling DC motor from Android device
Ref: https://robotics.stackexchange.com/q/8526/11146
I want to build a simple android controlled robot
I will connect android phone<usb>arduino<wire>motor controller<wire>dc motor
I wonder why I have to write two programs (android java & arduino c++)?
How can I directly control the DC motor from android java program without writing arduino code?

You could possibly utilize something like Firmata with minimal modifications, or potentially use a USB I/O chip instead of an Arduino, but these are likely to be inferrior to a custom solution - if you aren't willing to touch something as accessible as Arduino code, it's questionable if the project is practical for you.

It's not clear what you'd like to do, but for some applications one of the simpler ways to do this would be to add a wifi module to the Arduino and use a simple web interface to get the commands from the Android.

The short answer is "you can't." For the Arduino to do anything useful it needs to have instructions telling it what to do. In your example the Arduino's job is to do something that the Android can't – turn on and off the DC motor. You could even use a wifi or Bluetooth connection from the Android to the Arduino to make it possible to avoid the hassle of the USB cable.
Your project requires a number of small hunks of code on the Arduino to:

Listen for commands from the Android.
Validate the commands received.
Turn on or off the motor.

Roughly speaking your loop() function might look something like this:
void loop() {
  // look for a command
  // validate the command
  if (valid && turn_motor_on) {
    motor_on();
  } else {
    motor_off();
  }
}

Fortunately the Arduino code can be very simple and there is a lot of example code to help you get started.


text:
Serial printf implementation
Based on this approach I wanted to implement a function for formatted printing data to the serial monitor. I tried the code below:
int PIN = 12;

void _printf(char *fmt, ...) {
  va_list va;
  va_start(va, fmt);
  char buf[vsnprintf(NULL, 0, fmt, va) + 1];
  sprintf(buf, fmt, va);
  Serial.println(buf);
  va_end(va);
}

void setup() {
  Serial.begin(9600);
  Serial.println("serial monitor has been set up");
  char buf0[vsnprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
  sprintf(buf0, "pin %i configured to output", PIN);
  Serial.println(buf0);
  _printf("pin %i configured to output", PIN);
  char buf1[vsnprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
  sprintf(buf1, "pin %i configured to output", PIN);
  Serial.println(buf1);
  _printf("pin %i configured to output", PIN);
  pinMode(PIN, OUTPUT);
  char buf2[vsnprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
  sprintf(buf2, "pin %i configured to output", PIN);
  Serial.println(buf2);
  _printf("pin %i configured to output", PIN);
  char buf3[vsnprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
  sprintf(buf3, "pin %i configured to output", PIN);
  Serial.println(buf3);
  _printf("pin %i configured to output", PIN);
}

void loop() { }

But it gives me some weird output:
serial monitor has been set up
pin 12 configured to output
pin 2263 configured to output
pin 12 configured to output
pin 2234 configured to output
pin 12 configured to output
pin 2205 configured to output
pin 12 configured to output
pin 2176 configured to output

What do 2263 and 2269 mean? Why does it happen only inside the function? What is my mistake and how can I fix it?

Any reason to not use the standard printf()?

Streaming.h lets you write code that's rather more clear, using a lot less memory and producing much less assembly code.  See for example my answer to question 33319 that explains how to use it

The problem with your code is that you are mixing the "normal" and "variadic" forms of the printf functions.
Any printf function starting with V takes a variadic argument list pointer as its last variable. Any printf function which doesn't start with V takes a variadic list of individual variables.
When calculating your buffer size from a list of variables in your main loop you are incorrectly using vsnprintf - you should be using snprintf since you aren't passing it a va_list, but individual variables. In your _printf function you are correctly using vsnprintf to calculate the length of the buffer, but then incorrectly using sprintf with a va_list instead of individual variables.
So your two forms should actually be re-written as:
// Inline version
char buf0[snprintf(NULL, 0, "pin %i configured to output", PIN) + 1];
sprintf(buf0, "pin %i configured to output", PIN);
Serial.println(buf0);

and:
void _printf(char *fmt, ...) {
  va_list va;
  va_start(va, fmt);
  char buf[vsnprintf(NULL, 0, fmt, va) + 1];
  vsprintf(buf, fmt, va);
  Serial.println(buf);
  va_end(va);
}

Remember: if you have a va_list then it goes with a v*printf function. If you have individual variables they go with a *printf function.