text:
When GPS can't see satellites, how can I continue to tick off a smooth-ish time?
I'm getting 10 updates/sec from my GPS unit (The MTK3339 used in the Adafruit breakout board), and using it to update a clock display. This works well enough, though there's one minor problem that I'd like to solve and one major one that I have to solve.
The minor issue first; I don't get an update every 100ms. I get one roughly every 100ms... plus or minus about 20-30ms. If a late and an early update arrive back-to-back right when the display goes from n to n+1 seconds, it's noticeable that it's not ticking at a regular cadence. It's not fatal, but the arythmic stutter of it is deeply painful to watch.
The major issue is - what do I do when the GPS can't find a signal? Maybe the device is driving through a tunnel for a minute or there's some other sky obstruction. I still want the clock to update in a best-guess sort of way.
You can't just update the seconds display and then, 1000 (arduino-measured) milliseconds later, update the clock if a new message hasn't arrived. 1000 real-world milliseconds can be anywhere from 700 - 1400ms measured by an arduino, depending on the board and the quality of the crystal. Worse yet, the discrepancy is far from consistent within a single crystal. Seeing the processor speed up and slow down by several percent over the course of a few minutes isn't uncommon.
So what I'd like is a mechanism that will constantly smooth the received (GPS) time to give a best-estimate of current actual time. I'm okay with it being a second or two off (at most) from real time, as long as the cadence feels like actual seconds, and a loss of GPS for a few minutes can be quickly corrected when the signal is re-acquired.
I'm somewhat aware of (strikethrough)DIP(/strikethrough) PID methods, but I'm not sure how to apply them here. It seems that someone must have solved the problem for the sake of syncing internet time, so I shouldn't be reinventing a solution.

why not use the Time library?

Re “[one true second] can be anywhere from 700 - 1400ms measured by an arduino”: Either your Arduino is physically broken, or you are doing something terribly wrong in your code.

Many things can interfere with accurate Arduino time counting; without context it's impossible to know why you're seeing such results--that's pretty far off of anything I've seen on pretty much any Arduino or clone. Why not add an RTC?

What you want, namely something to “smooth the received (GPS) time”,
is called a GPS disciplined oscillator. Obviously, you are not
after the high accuracy of commercial GPSDOs, but the working principle
of what you are describing is essentially the same.

what do I do when the GPS can't find a signal?

In GPSDO lingo, this is called the “holdover” state. At this point you
rely solely on your local oscillator (here, millis() or micros()),
and steer it to correct for is natural drift, as determined while the
GPS reception was good. Or you can go fancy, measure the chip
temperature, and apply a temperature compensation.

I'm somewhat aware of DIP methods, but I'm not sure how to apply them
  here

I guess you mean “PID”.
You apply this to the phase of the oscillator. If the local oscillator
is ahead of the GPS (positive phase error), you lower its frequency. For
example, you could increment the seconds count every 1,000,100
microseconds (as measured by micros()), instead of every 1,000,000.
This will make your clock a little bit slow, and resynchronize it with
the GPS. Conversely, if your clock is behind the GPS, you slightly
increase its frequency to make it run faster.
In other words, the error value of your PID is the phase error of your
clock, and the control variable is the frequency adjustment. By
applying the PID technique this way, you are building what is known as a
phase-locked loop, or PLL. This is the standard way of
implementing a GPSDO.

It seems that someone must have solved the problem for the sake of
  syncing internet time

Sure, but NTP implementations can be quite complex, as they have to deal
with multiple servers having different round-trip delays and different
levels of trust. I am not aware of any Arduino library that does
anything similar. You may search for “time synchronization” or “PLL”. If
you don't find any, you can pick a PID library and apply it to your
oscillator.
A couple of final remarks:

You wrote “speed up and slow down by several percent over the course
of a few minutes isn't uncommon”. This shows there is something
awfully wrong with either your Arduino or your code. Over a few
minutes, you expect frequency variations of the order of one part
per million on an Arduino clocked off a ceramic resonator, and a few
parts per billion if yours is clocked off a crystal. See this
experimental study on the stability of an Arduino clock.
This stability problem is the very first thing you should investigate
and fix.
Many GPS modules have the option to give you a 1PPS (one pulse per
second) signal. If you can use this signal, you may get a quite
accurate measurement of your phase error. Relying on the NMEA
sentences will give you lots of jitter, which you would then have to
compensate for by setting the time constant of the PLL to a very long
value.

You can't just update the seconds display and then, 1000
  (arduino-measured) milliseconds later, update the clock if a new
  message hasn't arrived.

Why not? I'd do just that:

Maintain an in-memory clock
Update whenever a GPS message arrives
Every 1000ms (by millis), tick the clock if a message hadn't arrived, and in any case, update the display.

Something like:
SimpleTimer Timers;
unsigned long MyClock_sec = 0;
bool clockIsTicked = false;

void setup()
{
   Timers.setInterval(10L,  GpsCallback);     // if msg, upd MyClock & set flag
   Timers.setInterval(1000, DisplayCallback); // if no flag, ++MyClock; upd display
}

void loop(){
   Timers.run();
}

void GpsCallback(void){
   // if gps message {
   //    MyClock = <<GPS_TIME>>;
   //    ++clockIsTicked;
   // }
}

void DisplayCallback(void){
   if( !clockIsTicked )
      ++MyClock;

   // update the display
   clockIsTicked = false;
}

(Not compiled or tested - consider it a pseudo-code outline).

An accuracy of 700-1400 ms seems like a big issue on your side. Usually it's like +- 10-20 ms. Are you able to provide your code? Or at least important parts of it? Is it possible that you used the delay function?
If so, you should definitely read into the millis function, and how to use it as a timer. This will significantly improve the "accuracy". Because upon calling the delay function, the chip not only waits a given amount of seconds. The chip also calls the yield function. This one is mostly used to make sure that all background work is done before continuing.
What also might me a problem is every type of modification of the chip clock. I've seen some code where people modify the frequency of the PWM-signal. This also affects the clock in every other way.

A ceramic resonator (like, e.g., on the Uno) is usually something like 0.1% off (1 ms per second). Worst case 0.5% off. A crystal is way better.


text:
My Servo Won't Sweep Smoothly
So I've tried this a few times and I always get the same issue. When I try to run the sweep example the servo goes round 180 degrees but only in steps. Anyone know a way to fix this?
The servo I'm using is a Tower Pro Micro Servo 9G SG90
// Sweep
// by BARRAGAN <http://barraganstudio.com>
// This example code is in the public domain.

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
                // a maximum of eight servo objects can be created

int pos = 0;    // variable to store the servo position

void setup()
{
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()
{
  for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 degrees
  {                                  // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees
  {
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

Video: http://vidd.me/A40

does it hummmmm in between the "steps"?

no just the usual ticking on each step

You don't tell us anything about the set up (schematic?). My guess would be it doesn't have enough voltage.

I've set it up exactly as shown in the sweep example

My only advice is make sure the Arduino is getting enough power and check your connections. Consider external power if you're not on USB.

What's the maximum voltage input?

What power supply do you use? USB, power adapter, battery... Please indicate characteristics (voltage, max current...)

Currently USB from my MacBook so I would guess 5v

Have you checked that your Arduino is running at the right frequency? This can be easily done by just uploading the usual blink sketch and checking the LED on pin 13 blink period. If it's fine then try the same blink sketch but add the Servo library and myservo.attach(); (no call to myservo.read()) to see if the presence of the servo has an impact on frequency.

I've seen disappointingly step-y behavior from a similar cheap servo with an entirely different microcontroller.  Don't rule out low quality.  Generally you should not use USB (or anything coming through the Arduino) to power servos though.  http://www.thebackshed.com/Forum/forum_posts.asp?TID=5611&PN=9&TPN=3  Seems to suggest that different frame rates might yield better results.

@chris-stratton Would a 9v battery be a more suitable power source?

No.  9v batteries should not be used for high current applications.  And without a switching regulator, you'd waste nearly half of your (limited and relatively expensive) power as heat in the linear regulator.

Complete stab in the dark but nothing seems to be working as of now: change the delay to something slower (150 maybe)? Your servo might be getting low power and not wanting to move reliably.

To be fair, you'd better not "step" te servo?
Try to set it from 0 (1sec delay) to 180 (1sec delay) to 0 ... this should give a relatively smooth motion.

In electronics, as usual in situations where a cricuit is misbehaving and we don't understand why, a solution that generally works is to add a decoupling cap between +5V and GND.
In your case, I would put at least 220uF; that would ensure two things:

the voltage used to control the servo never drops
the voltage brought to Arduino by the USB does not drop either (which would have very bad impact on the Arduino, probably resetting it)

Electrolytic caps are a must-have for every electronics hobbyist (and professional as well, of course).
You can read more about decoupling capacitors on Wikipedia.
Edit:
According to @gwideman comment, it seems that using a decoupling capacitance above 10uF in a USB 2.0 device would violate USB specs and may damage the USB host controller on the computer.
I was not aware of this limitation but I have already used decoupling capacitance up to 100uF in my circuits and never got any issue with my USB computer port.
It might be due to extra electronics on the Arduino board that would "isolate" USB power from Arduino +5V anf d GND pins, I don't know (that should probably be the topic of a specific question); or maybe I have just been lucky all this time...

Would you happen to have a schematic for this?

You don't need a schematic just to add a decoupling cap! You just need the right cap and put it (on breadboard preferrably but you could also solder it directly to the servo) between +5V and the GND pins; just ensure you put the cap right as it is polarized (if you put it reverse it will explode)

Like this? http://imgur.com/thfEQtY

Yes exactly like that.

I've tried the following setup with no luck. Any more ideas? http://imgur.com/lprLvm4

What cap did you use? Didn't that change anything at all?

A 2.2uF as you suggested and everything acted exactly the same

I did not say 2.2uF but 220uF, which is a much bigger cap; if you don't have a 220uF or bigger, try to find a 100uF that may be enough.

USB requires that connected devices limit inrush current. This limits the size of bulk capacitor between VBUS and Ground to 10uF in USB 2.0. See USB 2.0 standard section 7.2.4.1 –  Inrush Current Limiting.  Using a larger capacitor, particularly one much larger than the source (computer) is required to supply on its end (120uF) would possibly lead to damage to the computer, or at least disruption of its operation.

More detail on the USB bypass capacitance limitation: http://www.edn.com/design/analog/4313897/Current-limiter-allows-large-USB-bypass-capacitance

Thanks @gwideman for this precision; however, to verify that this applies to an Arduino-based circuit, one has to check first what in Arduino diagram lies between USB power and 5V pin (I did not check it). For what it's worth, I have already used 100uF decoupling capacitor in one of my Arduino UNO based circuits and never got any USB issue at all; your mileage may vary.

What lies between USB power and the +5V net is a fuse and the Ron resistance of the FET that switches between USB and external power. Neither offers much resistance, and the fuse will not operate on a time scale to offer protection in this case. It is true that hosts (computers) are not required to break down when a USB device presents too much capacitance :-), and it obviously behooves computer makers to guard against such damage. Indeed, the Arduino UNO already presents 47uF x 2 bulk capacitance (and it looks like Duemilanove has 100uF x 2).

More likely issues are that hot-plugging will cause other USB-connected devices to experience glitches, especially if sharing a hub.

It's worth noting that USB is often quite tolerant of devices that are MASSIVELY out of spec. It depends on the host implementation, and lots of computers are willing to provide connected devices considerably more current then the specifications say the need to.

I've experienced same behavior with this type of servos. In my case it was easier to spot since Arduino frequently rebooted when servo was approaching the boundaries of the swing - so it was clear it was consuming too much power, and USB port was unable to deliver that.
Cheap dedicated 9V 1A AC/DC converter usually solves the problem. But if you can't wait for one to get delivered, get an iPad USB charger (nowadays everyone has it or has a neighbor/friend who has one). It is rated 10W, and it doesn't suffer from voltage drops even under high loads. Power your setup from it, and if you'd see it moves smoothly, you will have your answer.

It looks like your sketch runs in slow motion.
Check if you wrote delay(150) or have an additional delay in your loop.
Check twice and - just to make sure - upload the corrected sketch again.
Edit:
If possible, test with another servo and even test with another Arduino board.

I can assure you that's not the case. I've tried everything from 1 to 15 for the delay and even without the delay. I've also tried having just one for loop

Ok. Without delay, the servo should move at the actual processor speed.
Which board type do you use? And is the code above the original code that is running on the board?
did you try to set pin 9 as digital out?
Code in setup(){ ... pinMode(9, OUTPUT);   // sets the pin as output ... }

give a 9v supply +ve terminal to Vin and -ve ground.
since the arduino board cannot supply enough power to the servo, this will provide
this worked for me and workin just fine

The program is faulty. 1) No servo can react to a command in 15 milliseconds. Delay should be more like 500 milliseconds (.5 seconds). 2) The for loops are not designed to work together. The 1st loop feeds a value of 181to the second loop which is designed to start with a value of 180. The 2nd loop feeds a value of -1 back to the first loop, which is designed to start with a value of 0.

Please tell me what is incorrect about my for loop analysis. Could use some help.

There are some pretty serious misunderstandings in this - the given delay is only between the finest increments, the actual time of the sweep is  2.7 seconds, well within the capability of a servo.  Using a 20ms delay (possibly with larger increments to compensate) would indeed be more in keeping with typical servo update rates, but that is not what you recommend.  Also your analysis of the for loops is incorrect.

The contents of the for loop only execute if the condition is true, so only conditions which satisfy it are written to the servo.  Both for loops initialize their variable.

source: Stack Exchange

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

sort: votes


text:
Can a stepper motor be controlled directly from an Arduino?
I'm planning to build a simple XY plotter, and have been looking at the possibility of using a pair of small 5V 4-phase steppers to provide the movement. In my research, I've often seen stepper driver boards advertised, ranging from very big and expensive, through to quite small and cheap. Some of them actually look like little more than a darlington array on a PCB.
Do I really need one of those external driver boards, or can I control the steppers directly from my Arduino?

Do you have the datasheet for the steppers? What would be the DC resistance of the coils? You probably need a driver anyway, but sizing has to do with the power the stepper draws. I estimate you can only drive max 125mW from an Arduino directly, probably even less.

No part number, unfortunately, and minimal info from the supplier. I figured the current draw was likely to be too much, but thought it was worth asking anyway.

Generally, stepper motors cannot be controlled by an Arduino pin. They have a current draw of over the 20mA any single pin can supply.
Kickback is also a problem. Because the motors have moving magnetic parts inside, they will continue to generate electricity after power has been cut. this will almost certainly cause enough negative voltage that is enough to fry your Arduino.
A solution is to use a motor driver chip or shield. This one is a good example. These have transistor based chips that can drive enough current to power a motor, and diodes to mitigate the kickback from the motors.

You do not need moving components to produce inductive kickback. All you need is inductance, which requires no moving parts at all.

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


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

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

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

}

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

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

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

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

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

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

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

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

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

Any reason you make this o convoluted?

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

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

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

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

void turnOn() {
    running = true;
}

void turnOff() {
    running = false;
}

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

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

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

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

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


text:
Arduino Ethernet shield cannot establish connection
I bought a Chipdot Ethernet shield from Amazon. It does not have any MAC address on it. I connected this shield to an Arduino Uno. I tried to run the DHCPAdressPrinter code from Ethernet library on it, using the default MAC address of this code. And Serial monitor shows

Failed to configure Ethernet using DHCP

I have tried all the MAC IDs one by one as suggested on reviews but nothing worked. Is there any way to configure or assign a MAC ID to the Ethernet shield? Or is there are any way to know the Ethernet shield's  MAC address?
Thanks in advance.

The W5100 chip doesn't have a mac address by itself. You can assign any mac address to it that you want. With Ethernet.begin(mac); you assign the mac address to the W5100 chip.
The official Arduino Ethernet shield comes with a paper with a unique mac address. That is a nice service, but that is just a number, the Ethernet shield hardware is without any mac address.
There has been complaints about wrong resistor values near the ethernet connector. Can you read the numbers on those resistors ? They should be labeled as "510" and not as "511" : Arduino forum about ethernet resistors.
The Ethernet Shield uses more power than most other shields, and the W5100 can get pretty hot. Do you have enough power ? Is the 5V pin still above 4.5V ?
It is possible that your router does not accept the old W5100.
If the resistors are okay, I suggest to try an example with both mac and ip: Ethernet.begin(mac, ip);

I have checked the resistor which has 4 pin and placed on backside of RJ45. This resistor labeled as "511". I also checked the voltage on 5V pin multi meter display shows 3.76 volt below 4.5 volt but the IC W5100 getting too much hot.

That means you have a shield with wrong resistor values. That link to the Arduino forum shows how to add resistors to get the desired value of 50 ohms, or else try to return the shield. The 3.76V is too low. Find a better usb cable or power the Arduino board with a power supply of 7.5V to the power barrel jack. The W5100 does get hot, often too hot to keep a finger on it. Others say that it is "normal", but I have added a heatsink to my W5100. Would you consider buying an Ethernet Shield with the new W5500 ? All you have to do is include ethernet2.h instead of ethernet.h in your sketch.

okay I will look how to change resistor to get desired value. It's not power supply problem.. Arduino uno giving correct voltage from it's 5V pin but whenever I attach this shield the voltage goes down to 3.76 volt. the temperature of W5100 is above normal but not too hot to touch it. still I have not decided to buy new shield.  have faced the same problem with your shield?

No, my Ethernet Shield has the good resistors. The Arduino 5V pin should still be near 5V when the Ethernet Shield is attached. It might work with 3.76V but that will be very unreliable. You really have to fix that. Perhaps the low voltage is the problem ! If your Ethernet cable is short and your router is not too picky, then the ethernet might work, even with the wrong resistors. In my project I have a DC-DC converter to power everything, so I have more than enough power.


text:
Standalone ATMEGA328: Verification mismatch on random byte on -subsequent- uploads only
I have an Arduino Pro Mini as an ISP programmer with the ArduinoISP sketch running on it (19200 baud), and an addition in boards.txt that has a 'Standalone ATMEGA328 8MHz Internal' entry that specifies 8MHz and a bootloader file, along with some other things.
I'm trying to upload a simple blink sketch to an ATMEGA328 (not 328p, though the issue persists with that board as well) with no external components (internal clock)
The Problem
I can flash the bootloader no problem. I can also upload code the first time just fine. The problem is when I try to upload any different code after the first time, it gives a verification mismatch error at a seemingly random byte, complaining that 0xsomebody != 0xsomeotherbyte (also seemingly always different). This usually causes the sketch the stop working, and the LED to behave erratically.
IDE Verbose Outputs
Verbose output for burning the bootloader
Verbose output for first upload of simple sketch: basically Blink.ino
Verbose output for second upload of modified sketch: changed first delay to 1200 (side note: uploading an identical sketch doesn't give the verification mismatch error)
Verbose output for sufficiently different sketch (four digital writes, ie heartbeat example)
The Sketch
void setup() {
  pinMode(6, OUTPUT);
}

void loop() {
  digitalWrite(6, HIGH);
  delay(1100);
  digitalWrite(6, LOW);
  delay(400);
}

Bootloader Files
This is the boards.txt entry that I'm using:
##############################################################

atmega328bb.name=ATmega328 on a breadboard (8 MHz internal clock)

atmega328bb.upload.protocol=arduino
atmega328bb.upload.maximum_size=30720
atmega328bb.upload.speed=19200

atmega328bb.bootloader.low_fuses=0xE2
atmega328bb.bootloader.high_fuses=0xDA
atmega328bb.bootloader.extended_fuses=0x05

atmega328bb.bootloader.file=atmega/ATmegaBOOT_168_atmega328_pro_8MHz.hex
atmega328bb.bootloader.unlock_bits=0x3F
atmega328bb.bootloader.lock_bits=0x0F

atmega328bb.build.mcu=atmega328
atmega328bb.build.f_cpu=8000000L
atmega328bb.build.core=arduino:arduino
atmega328bb.build.variant=arduino:standard

atmega328bb.bootloader.tool=arduino:avrdude
atmega328bb.upload.tool=arduino:avrdude

I've added this entry to Users/me/Local/Arduino/packages/arduino/hardware/avr/1.6.17 as well as Program Files(x86)/hardware/arduino/avr
Here's the HEX file for the bootloader incase that's useful as well
The Programmer
Here's a schematic of the programmer:

The solder jumper 'CAP1' is soldered closed.
And the connections to the ATMEGA328

simulate this circuit – Schematic created using CircuitLab
And lastly, a photo of the setup:
Thanks in advance

Bootloader  specs might be relevant – generally, bootloader files set the fuses as well as loading boot loader code.  ¶  For an ArduinoISP question, I'd expect to see details of what you do to keep the Pro Mini from resetting, wiring diagram, photo of setup, and verbatim pastes of commands you entered and responses you got.  Figuring out ArduinoISP problems can be difficult even with all info available first hand; trying to do it at second hand without details isn't worthwhile, IMO.

Thanks for the info! I've edited my original post to include hopefully all relevant information about my problem.

I got some help from someone today. I oversaw a small detail when using the Arduino IDE with an ISP programmer: Hold shift when uploading to target the MCU at the end of the line rather than the MCU in the programmer.
So yeah, I hold shift when clicking upload and everything works great now. Sometimes it's the simplest things you'd never expect.


text:
NodeMCU doesn’t send the sensor read while powering with Vin
I have connected a NodeMCU ESP 12 with the Vin (6 volts) shared with 2 other NodeMCU. The sensors are getting power from the NodeMCU but the NodeMCU isn’t sending to the ThingSpeak cloud unless I plugged it to the PC and unplug the Vin.
Help please.

Four of AA battery @LookAlterno

@LookAlterno I didn’t understand that topic

@LookAlterno I tried to power only one nodemcu and nothing changed

@LookAlterno  check it now please

@LookAlterno thanks a lot dude ! Now it’s work!


text:
how can I send a variable to println?
this is my method
void mensaje_sms()
{
  string numero = "777777";  // this is my variable
  SIM900.print("AT+CMGF=1\r");
  delay(100);
      SIM900.println("AT+CMGS=\"591"numero"\"");
//IM900.println("AT+CMGS=\"59177777777\""); //only in this way does it work
      delay(100);
      SIM900.println("SEND NUMERO VARIABLE RODO");
      delay(100);
      SIM900.println((char)26);
      delay(100);
      SIM900.println();
      delay(5000);
      Serial.println("SMS sent successfully");
    }

how can I send a variable to println?

What variable? What do you want to happen?

this is my variable int numero = 777777; I need to put that in the println

Change:
SIM900.println("AT+CMGS=\"591"numero"\"");

to
SIM900.print("AT+CMGS=\"591");
SIM900.print(numero);
SIM900.println("\"");

Note that only the final call is to println() (which just prints a carriage-return character at the end.)


text:
Stacking 3 of the same shields on top of each other and instructing them in sync
Context:
I have an audio track separated into individual channels grouped by frequency and speaker location. I need to play all three of these channels simultaneously and perform instructions like play, stop, repeat, skip across all channels to keep them in sync.
This is part of an outdoor installation so the solution must be modular and robust.
If possible, the most elegant solution I could come up with is to use an Arduino Leonardo and stack 3 Adafruit Music Maker Shield on each other.
Reasons why I think it might be technically feasible:
1. Each shield can share communication over I2C

Looking at the VS1053b Datasheet (the IC used in the shield) the chip at max load consumes Maximum 60mA, and typically 37mA. Arduino can drive a max of 500mA so these three shields should consume a small portion of that.
The Arduino will also be powered via 12v power supply.

Details i'm not so clear on:

How will I differentiate between each shield when sending instructions or do I need to even need consider this if I want them to function as one?

the shield in link uses SPI

Using 12V as a power source isn't great. The voltage regulator has to burn off 7V to get down to 5V. With these 3 shield and the Leonardo itself, you are looking at around 1 Watt of power the voltage regulator is converting to heat. This will make it quite warm.

I'd personally ditch the Arduino entirely and use something more powerful. Something with an I2S interface, and connect up a CODEC with enough channels to suit your needs. Then you play a single file that has all the channels in it. You know - like surround sound does.

@Gerben So do you recommend to use a 5V 500mA power supply?

@Majenko Due to technical limitations we can't export a track to more than stereo. I'm not the audio guy, I'm the tech guy so I'm have to work with what I'm given.

A 5V supply would be ideal. Connect it to the USB, not the barrel jack.

The shields use SPI. There are more slave select pins on the shield for different devices of the shield. The first shield can use the default pins, but on next shields you must bend the default pins of the shield to side and connect them with a jumper cable to other set of pins of Arduino.
Then in sketch you need to define the select pins in constructor for each instance of the handling object Adafruit_VS1053.
Adafruit_VS1053_FilePlayer musicPlayer =
  Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);
Adafruit_VS1053_FilePlayer musicPlayer2 =
  Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS_2, SHIELD_DCS_2, DREQ_2, CARDCS);
Adafruit_VS1053_FilePlayer musicPlayer3 =
  Adafruit_VS1053_FilePlayer(SHIELD_RESET, SHIELD_CS_3, SHIELD_DCS_3, DREQ_3, CARDCS);

They will be not in microseconds sync since you must instruct them individually.
Use only one SD card because the SD library can't support more of them. Advantages of one SD card are only one cs pin and less active devices on SPI. There is no direct read by the player from SD card on the same shield.
Note: The SPI device is the SD card not the adapter. An empty adapter is nothing on bus so you can put the card for example into the shield on top and do not need bend the SD card cs pins on other shields.

The audio is sound scapes so there are no vocals or beats to align so it being microseconds out of sync will be okay.
Why use only one SD card?
Each channel will be exported to its own track and each track will be on it's own SD card which will therefore have it's own shield so they can be all played together

added to answer

I must use three separate SD cards as each channel has been exported as it's own track. So all three tracks must play at once.
I still dont quite understand why you are suggesting to use one SD card in this case.

your tracks are files. 3 files on one SD card. the player opens a file from the SD card reads the next buffer and closes the file. when the buffer is almost empty, the player opens the file, reads the next part and closes the file. the 3 players can read files from the same SD card. SD library can't work with multiple SD cards.

I understand now. Thank you for your help @Juraj

and one more note:.. the SPI device is the SD card not the adapter. an empty adapter is nothing on bus so you can put the card for example into the shield on top and do not need bend the SD card cs pins on .shields

My components have come and I started working on the project today. I have rewired the pins and have been able to communicate with multiple shields and play the files individually - but not yet simultaneously. I have a suspicion that that data rate required to play multiple tracks is lacking on the shield (I'm using a class 10 SD) but maybe I'm jumping the gun as I'm getting an "exit status 1" error when I invoke the ".useInterrupt(VS1053_FILEPLAYER_PIN_INT)" method. I will make a new post for this error.

perhaps you will need to modify the mp3 library. increase the buffer size and make changes so not all players play the buffer to end at the same time

The shield actually uses SPI.
So you will need to trace the chip select and make sure that each shield uses a different arduino pin.

Would that mean rerouting MCS, DCS and CCS for all shields?
https://learn.adafruit.com/adafruit-music-maker-shield-vs1053-mp3-wav-wave-ogg-vorbis-player/pinouts#main-control-breakouts-2-3

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


text:
Sending char arry via nRF24L01
I am trying to send a char array using Arduino Uno board and nRF24L01 modules
Here is the code for both transmitter and receiver:
 #include <SPI.h> //~ #include <TMRh20nRF24L01.h> //~ #include <TMRh20RF24.h>
 #include <nRF24L01.h>
 #include <RF24.h>

 #define CE_PIN   9
 #define CSN_PIN 10

 // NOTE: the "LL" at the end of the constant is "LongLong" type //
 These are the IDs of each of the slaves const uint64_t slaveID[2] =
 {0xE8E8F0F0E1LL, 0xE8E8F0F0E2LL} ;

 RF24 radio(CE_PIN, CSN_PIN); // Create a Radio

 char
> dataToSend[64]="e7665072be018b6b58ea9e40cf38553d6dc293cda4c9d94cda6e91ca61b3a073";

 unsigned long currentMillis; unsigned long prevMillis; unsigned long
> txIntervalMillis = 1000; int txVal = 0; float ackMessg[2]={1,2}; byte
 ackMessgLen = 4; // NB this 4 is the number of bytes in the 2 ints
 that will be recieved

 void setup() {

    Serial.begin(9600);
     Serial.println("Track Control Starting");
     radio.begin();
     radio.setDataRate( RF24_250KBPS );
     radio.enableAckPayload();
     radio.setRetries(3,5); // delay, count }

 //====================

 void loop() {

     currentMillis = millis();
     if (currentMillis - prevMillis >= txIntervalMillis) {

     radio.openWritingPipe(slaveID[0]); // calls the first slave
                                         // there could be a FOR loop to call several slaves in turn

     bool rslt;
     rslt = radio.write( dataToSend, sizeof(dataToSend) );
     Serial.print("\nRSLT (1 = success) ");
     Serial.println(rslt);
     Serial.print("Data Sent ");
     Serial.print(dataToSend[0]);
     Serial.print("  ");
     Serial.println(dataToSend[1]);
     if ( radio.isAckPayloadAvailable() ) {
         radio.read(ackMessg,ackMessgLen);
        Serial.print("Acknowledge received: ");
        Serial.print(ackMessg[0]);

 #include <SPI.h>
 #include <nRF24L01.h>
 #include <RF24.h>

 #define CE_PIN   9
 #define CSN_PIN 10

 // NOTE: the "LL" at the end of the constant is "LongLong" type

 const uint64_t   deviceID = 0xE8E8F0F0E1LL; // Define the ID for this slave

int valChange = 1;

 RF24 radio(CE_PIN, CSN_PIN);

 char  dataReceived[64];
 int ackData[2] = {12,23};

 void setup() {

     Serial.begin(9600);
     delay(1000);
     Serial.println("Hand Controller Starting");
     radio.begin();
     radio.setDataRate( RF24_250KBPS );
     radio.openReadingPipe(1,deviceID);
     radio.enableAckPayload();
     radio.writeAckPayload(1, ackData, sizeof(ackData));
     radio.startListening();
 }

 void loop() {

     if ( radio.available() ) {
         radio.read( dataReceived, sizeof(dataReceived) );
          for (int x = 0; x <64; x++) {
       //if (dataReceived[x] < 16) {
       //  Serial.write('0');
     // }
       Serial.print(dataReceived[x]);}
       Serial.println();
         radio.writeAckPayload(1, ackData, sizeof(ackData));

         ackData[0] += valChange; // this just increments so you can see that new data is being sent
     }
}

And here is the output that I get

Hand Controller Starting
e7665072be018b6b58ea9e40cf38553d

you get what you send. continue reading

yes i know that i got what i sent,my question was how to get the full char array as its size is more than payload size

To send a larger package you will need to split the data into a sequence of packages of PAYLOAD_MAX(32) size at the sender. And then reassemble the data at the receiver.

I would expect that the library sends the input in parts even if send in one function call. But I don't know this library. But the receiving must be coded expecting chunks of data.

yes i am trying to find a way to split big payload into chunks

Why send 64 characters in hex decimal notation when you can send 32 bytes with the same data?

how can i do that ?

byte dataToSend[32] = { 0xe7, 0x66, 0x50, 0x72, ..., 0x61, 0xb3, 0xa0, 0x73}; or write a function that translates from character string to byte vector as above.

thank u very much,but the array is generated from a hash function in sha256 library,i just simplified the code here to discuss the concept

Yes, the SHA256_BLOCK_SIZE is 32 which happens to be the RF24_PAYLOAD_MAX. The vector size (64) is your example is the textual (ASCII character) hex decimal representation of the block. Double the size as a byte (8-bits) is represented as two ASCII characters (0..15 mapped to '0'..'9', 'A'..'F').

so can i send the unencoded output from the hash function then map it at the receiver side?

TX code
#include "sha256.h"
#include <Arduino.h>
#include "./printf.h"

#include <SPI.h>
//~ #include <TMRh20nRF24L01.h>
//~ #include <TMRh20RF24.h>
#include <nRF24L01.h>
#include <RF24.h>

#define CE_PIN   9
#define CSN_PIN 10

// NOTE: the "LL" at the end of the constant is "LongLong" type
// These are the IDs of each of the slaves
const uint64_t slaveID = 0xE8E8F0F0E1L  ;

RF24 radio(CE_PIN, CSN_PIN); // Create a Radio

unsigned long currentMillis;
unsigned long prevMillis;
unsigned long txIntervalMillis = 1000;
int txVal = 0;
int ackMessg[6];
byte ackMessgLen = 4;

uint8_t* hash;
uint8_t copy[32];
void printHash(uint8_t* hash) {
  int i;
  for (i=0; i<32; i++) {
    Serial.print("0123456789abcdef"[hash[i]>>4]);
    Serial.print("0123456789abcdef"[hash[i]&0xf]);
      copy[i]=hash[i];
  }
  Serial.println();
}

void setup() {
  printf_begin();

  uint32_t a;
  unsigned long ms;

  Serial.begin(9600);

  radio.begin();
    radio.setDataRate( RF24_2MBPS );
    radio.enableAckPayload();
    radio.setRetries(3,5); // delay, count

  // SHA tests
  Serial.println("Test: FIPS 180-2 B.1");
  Serial.println("Expect:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
  Serial.print("Result:");
  ms = micros();
  Sha256.init();
  Sha256.print("abc");
  printHash(Sha256.result());
  Serial.println();
  for(int x=0;x<32;x++)
        {   Serial.print(copy[x]);
            Serial.print(" ");
                                  }
            Serial.println();

  Serial.print(" Hash took : ");
  Serial.print((micros() - ms));
  Serial.println(" micros");
  Serial.println();

  }

void loop() {

  currentMillis = millis();
    if (currentMillis - prevMillis >= txIntervalMillis) {

    radio.openWritingPipe(slaveID);
    bool rslt,rsltt;
    rslt = radio.write( copy, 32 );

    if ( radio.isAckPayloadAvailable() ) {
        radio.read(ackMessg,ackMessgLen);
        Serial.print("Acknowledge received: ");
        Serial.print(ackMessg[0]);
        Serial.print("  ");
        Serial.println(ackMessg[1]);
    }
    prevMillis = millis();
 }

}

Rx code
// HandController - the slave or the receiver

    // http://tmrh20.github.io/RF24/

    //~ - CONNECTIONS: nRF24L01 Modules See:
    //~ http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo
    //~ 1 - GND
    //~ 2 - VCC 3.3V !!! NOT 5V
    //~ 3 - CE to Arduino pin 9
    //~ 4 - CSN to Arduino pin 10
    //~ 5 - SCK to Arduino pin 13
    //~ 6 - MOSI to Arduino pin 11
    //~ 7 - MISO to Arduino pin 12
    //~ 8 - UNUSED

#include <SPI.h>
//~ #include <TMRh20nRF24L01.h>
//~ #include <TMRh20RF24.h>
#include <nRF24L01.h>
#include <RF24.h>

#define CE_PIN   9
#define CSN_PIN 10

// NOTE: the "LL" at the end of the constant is "LongLong" type

const uint64_t   deviceID[2] ={ 0xE8E8F0F0E1LL,0xE8E8F0F0E1LL}; // Define the ID for slaves

int valChange = 1;

RF24 radio(CE_PIN, CSN_PIN);
RF24 radioo(CE_PIN, CSN_PIN);
uint8_t  dataReceived[32];

int ackData[2] = {12,23};

void setup() {

    Serial.begin(9600);
    Serial.println("Hand Controller Starting");
    radio.begin();
    radio.setDataRate( RF24_2MBPS );
    radio.openReadingPipe(1,deviceID[1]);
    radio.enableAckPayload();
    radio.writeAckPayload(1, ackData, sizeof(ackData));
    radio.startListening();

}

void loop() {

 unsigned long startTimer = millis();

    if ( radio.available() ) {
        radio.read( dataReceived, sizeof(dataReceived) );
        radio.writeAckPayload(1, ackData, sizeof(ackData));
        Serial.println();
        //Serial.println(startTimer);
        Serial.println();
        for(int x=0;x<32;x++)
        {Serial.print(dataReceived[x]);
        Serial.print(" ");}}
        ackData[0] += valChange; // this just increments so you can see that new data is being sent

    }

it is fully working now with both outputs on the same size

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


text:
Programming ATmega2560 processor with FTDI instead of ATmega32
Has anyone tried to program an ATmega2560 with an FTDI chip as is done in the Arduino Nano (this is for a custom design).
Will it work?

That will work. The only think to look out for is how to reset the board. Either manually reset it before uploading, or connect the DTR pin of the FTDI, via a capacitor, to the reset pin.

It actually worked!

Reworded question to remove confusing references to the Arduino Mega, which is not what this question is about (see OP's comment below).

In fact, the basic Arduino Mega (with the ATmega 1280) utilizes an FT232RL, so yes, it will work if you connect it correctly.
It is only the newer Mega2560 (along with the similar-generation Uno, etc) which utilizes an ATmega16u2 or similar as the USB bridge.
Generally speaking, the bootloader doesn't care - you should be able to use either target chip with either USB bridge (or others).

The Arduino Mega already has a built-in USB-UART bridge, so there's no need for a separate chip.
The ATmega1280 on the other hand is just a bare AVR MCU and does require either a separate USB-UART bridge for serial programming (provided it is programmed with an appropriate bootloader) or an ISP programmer for ISP programming.

Sorry, I expressed my self wrong. My goal is to program the Atmega2560 (with the bootloader already burned in) with the FTDI chip instead the AVR USB bridge from the Arduino Mega original design. Do you think that might work assuming the connections are correct? Or in other words, is the Arduino IDE expecting some sort of response from the programmer that the AVR bridge will provide and the FTDI will not?

The FTDI chip is a USB-UART bridge, so I would expect not. But to be perfectly honest, I'd use a ISP programmer and save myself the cost of the bridge and the time of burning the bootloader.

Your comment seems either confusing or wrong.  Why would you expect an FTDI bridge not to work, when it is what the official Arduino Mega actually utilizes?  The Arduino IDE doesn't speak USB for the ATmega boards anyway; it relies on the host operating system to present a Serial API, so it has no idea of the implementation detail to tie to a particular board.

@ChrisStratton: "... is the Arduino IDE expecting some sort of response from the programmer that the AVR bridge will provide and the FTDI will not?"

If you think there is a difference there you are quite mistaken.  The bridge is merely a proxy.  The response comes form the bootloader on the target MCU.  As I'd mentioned previously the IDE (avrdude actually) relies on the operating system Serial API.  It doesn't care what USB bus operations or VID/PID are involved.  It merely cares that whatever operating system Serial device you point it at in the menu has a bootloader that responds at the baud rate configured for the board entry.  Take a look in boards.txt at the FTDI- vs. ATmega16u2 interfaced boards.

I don't understand why you've gone off on this tangent. Of course the bridge doesn't care about the protocol; it's just a bridge.

No tangent.  Just the illogical nature of your "I would expect not" comment.  I read that as you expecting this not to work.  Did you mean that you expected there to be no difference, ie, are you responding to the second question and not the first?


text:
Auto acknowledge failed with nRF 24L01+ and Arduino
My transceivers are running fine. I've written a few code and got them running. Then I decided to check the auto acknowledgement feature wherein we can return data back to the sender WITHOUT manually changing the radio modes on both units. But I find that the serial monitor always shows "failed to transmit". Why is this happening, because otherwise they work fine?
I am using maniacbug's RF24master library.
The Tx code is:
#include<SPI.h>
#include<nRF24L01.h>
#include<RF24.h>

int msg[1] = {1};
int rec[1] = {0};
bool stat = true;
RF24 radio(9,10);
const uint64_t pipe[1] = {0xF0F0F0F0E1LL};

void setup()
{
  Serial.begin(57600);
  radio.begin();
  delay(1000);
  radio.setAutoAck(true);
  radio.enableAckPayload();
  radio.openWritingPipe(pipe[0]);
  radio.setRetries(15,15);
 }
void loop()
{
  if(stat)
  {
    radio.stopListening();
    bool ok = radio.write(msg,sizeof(msg));
    delay(100);
    if(ok)
    {Serial.println("transmitted successfully !!");}
    else
    {Serial.println("faileed to transmit");}
    msg[1]++;
    if(msg[1]>=200)
    {msg[1]=1;}
    stat = false;
    //delay(20);
  }
  if(!stat)
  {
    if(radio.isAckPayloadAvailable())
    {
      radio.read(rec,sizeof(rec));
      Serial.print("received ack payload is : ");
      Serial.println(rec[1]);
      stat = true;
    }
  }

}

and the Rx part is:
#include<SPI.h>
#include<nRF24L01.h>
#include<RF24.h>
const uint64_t pipe = 0xF0F0F0F0E1LL;
RF24 radio(9,10);
int rec[1] = {0};
int ack[1] = {1};
void setup()
{
  Serial.begin(57600);
  radio.begin();
  delay(100);
  radio.setAutoAck(true);
  radio.enableAckPayload();
  radio.openReadingPipe(1,pipe);
  radio.startListening();
  radio.setRetries(15,15);
}
void loop()
{
  if(radio.available())
  {
    Serial.println("payload available....");
    bool ok = radio.read(rec,sizeof(rec));
    if(ok)
    {
        Serial.println("message received !!");
        Serial.print("integer got is : ");
        Serial.println(rec[1]);
        radio.writeAckPayload(1,ack,sizeof(ack));
    }
    else
    {Serial.println("failed to receive the message");}
  }
}

Note that you need to provide the AckPayload before you receive a message, not after.

no,no we have to provide the ack payload after we receive a msg.my code is buggy.i wrote a new and better one and it is working !!! btw thanks for checking out the ques!!

If you found a solution to your question, please post it as an answer and accept it, so that people who have a similar problem an benefit from your experience.

my blog is up and running. the auto ack code and discussion is here http://shantamraj.wordpress.com/2014/07/19/exploring-the-auto-ack-feature-of-the-transceiver/ @jfpoilpret .

@jfpoilpret Please post the answer and accept it here.

I'm voting to close this long abandoned question because the issue has never been clearly stated, and the asker seems to have long since found their own solution and published it on their blog.

To achieve that you have to do the following -
if ( radio.available() ) { // make sure the read will succeed
radio.writeAckPayload( 1, buf, len ); // prep the ack payload
radio.read( &got_time, sizeof(unsigned long) ); // also shunts out ack payload
}

So your program finally becomes -
#include<SPI.h>
#include<nRF24L01.h>
#include<RF24.h>
int msg[1] = {1};
int rec[1] = {5};
bool stat = true;
RF24 radio(9,10);
const uint64_t pipe[1] = {0xF0F0F0F0E1LL};

void setup()
{
  Serial.begin(57600);
  radio.begin();
  delay(100);
  radio.setAutoAck(true);
  radio.enableAckPayload();
  radio.enableDynamicPayloads();
  radio.stopListening();
  radio.openWritingPipe(pipe[0]);
  radio.setRetries(15,15);
 }
void loop()
{
if(stat)
{
    if(radio.write(msg,sizeof(msg)))
    {
      Serial.print( msg[0] );
      Serial.println("...tx success");
      if(radio.isAckPayloadAvailable())
      {
        radio.read(rec,sizeof(int));
        Serial.print("received ack payload is : ");
        Serial.println(rec[0]);
      }
      else
      {
        stat = false; //doing this completely shuts down the transmitter if an ack payload is not received !!
        Serial.println("status has become false so stop here....");
      }
      msg[0]+=3;;
    if(msg[0]>=100)
    {msg[0]=1;}
    }
 }
}

And the RX part becomes -
#include<SPI.h>
#include<nRF24L01.h>
#include<RF24.h>
const uint64_t pipe[1]= {0xF0F0F0F0E1LL};
RF24 radio(9,10);
int rec[1] = {2};
int red;
void setup()
{
  Serial.begin(57600);
  radio.begin();
  delay(100);
  radio.setAutoAck(true);
  radio.enableAckPayload();
  radio.enableDynamicPayloads();
  radio.openReadingPipe(1,pipe[0]);
  radio.startListening();
  radio.setRetries(15,15);
}
void loop()
{
  if ( radio.available() ) {
    radio.writeAckPayload( 1, rec, sizeof(int) );
    radio.read( &red,sizeof(red) );rec[0]+=2;
    Serial.print("integer got is : ");
    Serial.println(red);
}
}

Know more about it at the following pages -
https://shantamraj.wordpress.com/2014/07/19/exploring-the-auto-ack-feature-of-the-transceiver/
https://shantamraj.wordpress.com/2014/11/30/auto-ack-completely-fixed/


text:
Can't communicate with SIM800 module
I am using Arduino Uno R3 and a SIM800L (voltage regulator built in). My initial setup included a 10kΩ resistor soldered between the lower end of the RX and GND pins on the SIM800L, and a 4.6kΩ resistor soldered on the jumper connecting SIM800L's RX and Arduino's declared TX (pin 7). SIM800L has its own power supply (5v-2A). This is a setup I have used previously on two different SIM800L modules, and everything worked fine without any (visible) problems.
Baud rate is set to 9600 in Arduino IDE, PC port (via Device manager), and the module, through the sketch.
After loading the sketch (first one) shown on this site, the SIM800L connects to the GSM network (I can tell by the delay between blinks), but the module does not respond to AT commands send via serial monitor.
The sketch
#include <SoftwareSerial.h>

//SIM800 TX is connected to Arduino D8
#define SIM800_TX_PIN 8

//SIM800 RX is connected to Arduino D7
#define SIM800_RX_PIN 7

//Create software serial object to communicate with SIM800
SoftwareSerial serialSIM800(SIM800_TX_PIN,SIM800_RX_PIN);

void setup() {
  //Begin serial comunication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);
  while(!Serial);

  //Being serial communication witj Arduino and SIM800
  serialSIM800.begin(9600);
  delay(1000);
}

void loop() {
  //Read SIM800 output (if available) and print it in Arduino IDE Serial Monitor
  if(serialSIM800.available()){
    Serial.write(serialSIM800.read());
  }
  //Read Arduino IDE Serial Monitor inputs (if available) and send them to SIM800
  if(Serial.available()){
    serialSIM800.write(Serial.read());
  }
}

Things tried
Thinking that the resistors might be causing this, I removed all of them, and made a clean connection with Arduino. And the problem persisted.
I tried resetting the module, by passing the ATW command into a sketch:
serialSIM800.write("ATW\r\n");

and that also gave no results. Further testing with:
if(!serialSIM800.available()) {
    Serial.println("Not working");
}

indicated where the problem might be.
I have also tried changing the baud rate to 48000, 57600, and 115200, but that did not solve my problem.
The question
Am I right in assuming that a reset to factory settings could solve my problem? If so, how can I reset the module, without the AT commands? If resetting would do me no good, what else could I try?

Serial communications (UART/USART) requires the RX/TX pins of the sender and receiver be swapped.  So connect the TX from the Uno to the RX of the Sim800L, and RX from Uno to TX on module.  (Or, just swap the pin numbers for your softwareserial setup above...)

You're right about the sending and receiving, of course - even the SoftwareSerial.h says, when defining the method - SoftwareSerial(receivePin, transmitPin, inverse_logic=false). But, the setup already works like that, it's the original sketch that swaps the naming for attempted clarity (SIM's TX to Arduino's D8 - Arduino receives on D8, SIM's RX to Arduino's D7 - Arduino sends through D7). I've tried swapping the pins, just to be on the safe side, and, as expected, there was garbled output in Serial monitor. Something along the lines of ÿÿÿ ÿ ÿÿÿÿÿÿÿ ââââ

This is widely happen problem - serial communication with SIM800L stopped working.
You can do reset, but in my case it didn't help: on powered SIM800L module shortcut "RST" pin with the ground for half of second - unit should reset and restart. I think it's defective architecture/firmware, but unfortunately SIMCOM dropped support for this model, so best advise is to avoid SIMCOM until they study how to make quality products.


text:
IDE 1.6.10 on LinuxMint 17.3 Cinnamon
When compiling I get the error
'as: unknown option »-mmcu=avr5« exit status 1'
I succeeded now using your piece of advise. Thank you so much.

Turn on verbose compilation and check the commands it is running.

I deleted the .arduino15 directory. Have I to delete also the directorie with all data of arduino?

Delete or rename the old "Arduino15" directory located at /home/(username)/.arduino15    (a.k.a. ~/.arduino15) and re-install 1.6.10.


text:
How to expand program memory on an arduino?
Sometimes I run out of space of the program size for the embedded C program that I want to put on an arduino. So what chip do I need to expand the program memory of the arduino so that I can use bigger C programs with my arduino?

Considering that a fellow by the name of Petri Häkkinen put an arcade-style game on an Atmega328P, maybe you should look at saving space in your code? If that isn't practical, as some of the answers say, you can get a bigger chip with more program memory. The Atmega644, for example, comes in a DIP-chip package, amongst others.

See also https://forum.arduino.cc/index.php?topic=226465.0

can you please explain a bit more your answer ? 2) The Arduino has SPI, so an SD card can be accessed. Any code on the SD card would need to be loaded into executable memory. This is complicated and not for beginners... You mean that you can change or re-program de instruction memory while the program is running ?
Can the running program call the bootloader and load new instructions on a different addresses ? Won´t this age the program memory ? A different solution may be identify rutines in your program and all the "call´s" stored whith the data on a spi external memory... Thanks !

An ATmega2560 is the chip to add for more memory when you run out of program memory on an Uno.  Referring to the Memory webpage at arduino.cc, you'll see that it has Flash=256KB, SRAM=8KB, EEPROM=4KB, where the ATmega328 chip on the Uno has Flash=32KB, SRAM=2KB, EEPROM=1KB.
When you run out of program memory on an Uno, you have about three choices that are practical:  make the program smaller; remove the bootloader (to free up one or two KB); use a different board with a more-capable processor.  The CPU on an Uno board doesn't have a way to access program bytes from places other than the on-chip 32KB flash.  The CPU on a Mega2560 board starts out with 8 times as much flash, so it can hold bigger programs than an Uno can.
If you remove the bootloader, you could instead program using a USBASP board, as described in a
“Program AVR chip using a USBASP with 10 pin cable” article at learningaboutelectronics.com.

but if you free up the bootloader then how would i use the arduino IDE to program?

@qwerty10, see last paragraph of edit.   Arduino IDE supports USBASP ok.

Wouldnt it work with any programmer that can upload code to ATMEGA? Instead of only a USBASP. As I understand it itns not actually using 10 pins but a subset of those pins.

@qwerty10,  USPASP is an ISP (in system programming) programmer.  Generally, any ISP programmer  can be used to program a chip (with or without a bootloader on it) as long as MOSI, MISO, SCK, RST, VCC, and GND pins are available on the target chip.

Current Unos use the very compact optiboot bootloader. Removing it will only free 512 bytes.

@qwerty10: There are versions of the USBASP with a 6 pin connector. The 10 pin connector has 4 redundant pins.

@Edgar Bonet . I have another question Edgar. If I take out the atmega 328 chip from its socket on the Uno and replace it with using atmega8-16PU instead and I burn this 512 bytes bootloader-does that mean I can use the arduino Uno with the atmega8 like the atmaga328 (but with a subset of the features of the 328). The atmega8 is of course an older chip than the 328 but it still has same pinouts.

@qwerty10: I am quite confident it should work on the physical level. On the software level however, you will have to convince the Arduino IDE to play well with it. You may try to tell the IDE your board is actually an “Arduino NG or older w/ ATmega8”.

@Edgar Bonet. So using it as an Arduino NG with atmeg8 chip does this mean that the bootloader will set the fuses on the arduino's atmega8 to use the crystal on the arduino pcb? Or does the bootloader set the fuses on the arduino's atmega8 to use its internal oscillator? This clock info needs to be known to move  from arduino prototype to a permanent PCB version of circuit. How  much memory is left after writing bootlader to atmega8 -is it 7.5 KB instead of 8KB?

@qwerty10: Your are drifting very far from your original question. That should really be a new question.

@Edgar Bonet. I would guess, the answer as, because it pin for pin subset of the  atmega328 (i.e. the pins of the 328 can be the same as the mega8) of the uno board hence it  would require a crystal and capacitors.

Another way (other than MCU with more memory) is not using Arduino framework and its libraries. Such level of abstraction is expensive in both ways - memory usage and speed. But that's much harder way. If you need some library, you have to port it (if you haven't found native one) or at least provide required functions from Arduino.
For example in Arduino IDE 1.6.11 empty sketch is using up 444 Bytes of flash. Using one pinMode and digitalWrite(13, ! digitalRead(13)); + delay(500); means 964 Bytes. Of course, these are most likely one-timers. If you use six more pins and toggle it, it uses much less program memory than using first one (1192B). But it still grows really fast.
In pure C empty program is about 134 Bytes long. Same functionality (toggling one pin every 500ms) takes 158 Bytes (and it's way faster).
But for hobby project i would go for ATMega2560 or ATMega644/1284 instead.
And you can use direct access to hardware too. Toggle pin sketch with using registers directly and _delay_ms from avr libraries uses 468 Bytes instead of 964B. With delay from Arduino core libraries it's 602B.

You mean _delay_ms().

This has the added benefit of actually learning about the mcu that you're using. The AVRs on these Arduinos are much more capable than the "standard library" would have you believe. ++

When asking a broad question, it is helpful to include some details.  Like how much memory you need and why you think you need it.
I once specified a processor at 2 KB program space, 64 bytes RAM and 1 KIPS.
The engineer asked, "MIPS?", and I explained thousands per second.  He replied, "They don't come that slow".  At the end of the project, a huge UI was added and memory got tight... but it still fit with no problem.
So, consider being more thoughtful about the resources being used.
To answer the question:

The Arduino does not provide a convenient bus to fetch memory over.
So, there is no way to plug in a chip to get more memory.

The Arduino has SPI, so an SD card can be accessed.
Any code on the SD card would need to be loaded into executable memory.
This is complicated and not for beginners...

As suggested, tighten up you code.  This is probably a good way to learn.

Move to a larger Arduino.

There are different Arduino processors.  Some in the ACR line, others in the ARM line.  Going to a different device in the same family is a relatively modest change and can provide up to 368 Bytes of program FLASH.  But these are not Arduino boards exactly.
The Arduino ARM based devices are very different and use different libraries.
Check out the Arduino Mega 2560 it is very similar to the Uno, has a similar footprint, code should port relatively easily and is inexpensive.
There are also larger devices in the AVR family.
Note, the AVR32 is a different processor and the peripherals are enough different that it is a different device.
If you want to get into very large programs (gigabytes of memory) check out the Beagleboard.  It has a full linux, with virtual memory (see #2 above) and has more powerful I/O mechanisms.

Perhaps fix some typos, like Wen, 3, and differnt

I mean, if you fix those typos, someone might vote up your answer...

You could also look into other platforms. For instance, a Teensy 3.2 is Arduino compatible and has a 2KB eeprom and 64KB of RAM.

What about a raspberry pi zero?  I have a couple and use them quite often as arduinos.

Other architectures should indeed be considered, but an embedded linux system with mandatory SD card booting like the pi adds a lot of complexity and is fragile in unique ways, even if not more expensive.  There are a lot of boards based on smaller, more highly intergrated ARM MCUs which are much more similar to an Arduino in terms of applications, while being drastically more capable.  But if you need a lot of processing, or megabytes of memory, then yes, these complexities start to be worthwhile.

I also prefer the zero because it is so flexible.  You can add more storage or embed it in projects while also having a large enough processor to do pretty much anything.


text:
Difference between Ciao REST server and Ciao REST connector and when to use each or the other
I'm reading the Ciao library and can't make out the difference between Ciao REST server and Ciao REST connector.
When is the connector suitable and at what point do I need the server?
This is a graphic of what im thinking to do:

The yun tag was the only i coul set. I would like to set library-ciao.

I don't know about "Ciao" but generally a rest server answers requests from a client that is connecting via a rest connector.
You client will use POST, GET, PUT, etc. to ask the server to provide a service.  This could be as simple as "GET .\index.htm" or more likely posting information to be stored in a database.
The server will sit waiting for these requests and will have handling routines for each specific request and might supply a response.

yes, im fully aware of REST as api but my queston is about the confusing thing that Ciao is used on a microprocessor board that has another cpu processor beside it. It hosts a LininoOS that is a full server. Now im connecting to a Raspberry Pi Server as well and i down't understand the different servers meaning.
Thats why im asking so high level about the difference of the two libraries.

added a graphic to make it more clea what thee types of systems i mean.


text:
BridgeServer REST API with more string values
I wold like to make me a REST API with string values and more string Keys.
like: ~http://url.tld/foo/bar/xy to get "bar" and do more...
Can somebody tell me how to get the second word out of the URL? In this case "bar".
The tutorial show's how to use /arduino/digital/13/1 as to set pin 13 High.I would like to get a different syntax.
Something like this: arduino/device1/switch/on
By now i searched quite long and tested different things as you can see below, but i can't get more than one word caught to trigger from the client object.
is boils down to the question why my client object changes the payload.
this part:
void process(BridgeClient client) {
  String url0 = client.readString();
  Console.print("process url0: ");      // --> is "bar/xy"
  Console.println(url0);
  String command = client.readStringUntil('/');
  String url1 = client.readString();
  Console.print("process url1: ");
  Console.println(url1);               // --> is "" aka:empty!

i made a MWE to show what i already did:
// Libraries:
#include <Bridge.h>
#include <BridgeServer.h>
#include <BridgeClient.h>
#include <Console.h>

// Constants:
const bool on = HIGH;
const bool off = LOW;

// Objects:
BridgeServer server;

void setup() {
  pinMode(6, INPUT_PULLUP);
  Bridge.begin();
  server.begin();
  Console.begin();
  while (!Console);
  Console.println("setup done..");
}

void loop() {
  BridgeClient client = server.accept();
  if (client) {
    process(client);
    client.stop();
  }
}

void process(BridgeClient client) {
    String url0 = client.readString();
    Console.print("process url0: ");   // --> is "bar/xy"
    Console.println(url0);
    String command = client.readStringUntil('/');
    String url1 = client.readString();
    Console.print("process url1: ");
    Console.println(url1);             // --> is "" aka:empty!
  if (command == "device1") {
    device1(client);
  }
  if (command == "status") {
    Console.print("process: command == status  | command: ");
    Console.println(command);
    statusCommand(client);
  }
}

void device1(BridgeClient client) {
  String URL = client.readString();
  Console.println("URL:");
  Console.println(URL);                               // ---> is "on"
  String mode = client.readStringUntil('\r');
  Console.println("mode:");
  Console.println(mode);                            // ---> is ""
  String value = getStringPartByNr(URL, '/', 1);
  Console.println("value:");
  Console.println(value);                            // ---> is ""
  power(on);
  if ( URL == "on"){
    client.print(F("found /on"));
    power(on);
  }
  else if ( URL == "off"){
    client.print(F("found /off"));
    power(off);
  }
}

void power(bool on_off){
  bool checkpin = digitalRead(6);                          // machine state
  if (checkpin == LOW && on_off == HIGH) {        // means power is off and on is called
    digitalWrite(13, HIGH);
    Console.print(" checkpin == LOW && on_off == HIGH [1] ");
  }
  else if (checkpin == HIGH && on_off == LOW) { // means power is on and off is called
    digitalWrite(13, LOW);
    Console.print(" checkpin == HIGH && on_off == LOW [2] ");
  }
}

void statusCommand(BridgeClient client) {
}

// splitting a string and return the part nr index split by separator
String getStringPartByNr(String data, char separator, int index) {
    int stringData = 0;        //variable to count data part nr
    String dataPart = "";      //variable to hold the return text
    for(int i = 0; i<data.length()-1; i++) { //Walk through the text one letter at a time
        if(data[i]==separator) { //Count the number of times separator character appears
            stringData++;
        } else if(stringData==index) { //get the text when separator is the rignt one
            dataPart.concat(data[i]);
        } else if(stringData>index) { //return text and stop if the next separator appears
            return dataPart;
            break; // - to save CPU-time
        }
    }
    return dataPart; //return text if this is the last part
}

maybe you should not create a copy of the Cllient object when passing it into a function. use reference parameter BridgeClient &client

i added it as screenshoot. its not clear visible because the console is white as well but underneeth the console output you see that im calling [myarduino].local/device1/on in a browser and the output of url0 [String url0 = client.readString();] is the full string but then after one time calling client.readStringUntil('/') the client seams to be manipulated and url1 [String url1 = client.readString(); ]  is empty.

same for 'BridgeClient &client'.

so you read all the input into ur10 with readString() and the expect to read what from it with readStringUntil()?

i expect url1 to be same as url0 because im reading the same object. why is it not the same?

You misunderstand the networking Client class concept. It is a stream like the Serial object. Bytes are stored in the Client object's buffer only until you read them.

ok, so how can i pass it thorugh a function without to loose the information about the "xy" string (of http://myarduino/foo/bar/xy)?

https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/ or http://forum.arduino.cc/index.php?topic=396450.0

or read it to / and then to / etc.

Do you mean to read to device1/foo/bar/ and then to device1/foo/ ?
thats not possible because readStringUntil('/'); finds the first and cuts away the rest of the string...

not cuts away, stores into output

I can’t follow...

the rest is still waiting in buffer to be read with the next readStringUntil

true. I cold swear i tested that with a negative result. now it works.

ah, i found a underlaying issue. somehow the string of the device1 gets recognzed by an if(command == "device1"){ switch(client)}; but not the switch afterwords wich takes the second readStringUntil("/") part... like void switch(client){ String command = client.readStringUntil('/'); if(command == "on"){ turn(client);}
the on does not get recogized. but im able to print command "on" to console.

but after the on, there is no /. the readStringUntil reads the rest of input and then waits a second and returns. I bet you have "on\r\n" in the String. and that is not equal to "on".

your my hero. that works. can you explain me what \r\n means and why it is that i have to expect (guess) that?

it is a 'new line' code. in this case at the end of the HTTP GET request's first line. on next lines are the HTTP headers


text:
Can I change this code to use a potentiometer instead of a push button
The following code is for a pyrograph power supply that uses an ATtiny85. I want to change it, so instead of a push button I have a potentiometer being the control of the temperature. Can anyone guide me on how to accomplish this with this code?
//Written by Tyler Gerritsen
//2017-10-21
//Pyrography Pen Power Supply Controller
//Written for ATTiny85 w/ Internal 1MHZ Clock

const byte btn = 2;
const byte led = 1;
const byte pwr = 0;
byte rate = 0;
unsigned long nextChange = 0;
boolean onOff = false;
unsigned long blinkyCount = 2000000000;
unsigned long nextBlink = 0;
unsigned long debounceTimer = 2000000000;
const unsigned int debounceDelay = 400;
const unsigned int onDelay[5] = {6800, 6300, 5800, 6300, 4800};
const unsigned int offDelay = 5000;

void setup() {
  pinMode(btn, INPUT_PULLUP);
  digitalWrite(btn, HIGH);
  pinMode(led, OUTPUT);
  pinMode(pwr, OUTPUT);
  digitalWrite(pwr, LOW);
  debounceTimer = 60000000;
  while (digitalRead(btn)) {
    checkButton();
  }
  analogWrite(led, 0);
  nextChange = micros();
  debounceTimer = millis() + debounceDelay;
  blinkyCount = 1;

}

void loop() {
  runBurner();
  checkButton();
}

void runBurner() {
  if (micros() > nextChange) {
    if (onOff) {
      digitalWrite(pwr, LOW);
      onOff = false;
      nextChange += onDelay[rate];
    } else {
      digitalWrite(pwr, HIGH);
      onOff = true;
      nextChange += offDelay;
    }
  }
}

void checkButton() {
  if (!digitalRead(btn) && millis() > debounceTimer) {
    debounceTimer = millis() + debounceDelay;
    rate++;
    rate %= 5;
    blinkyCount = (rate) * 2 + 5;
    nextBlink = millis();
  }
  if (blinkyCount > 1 && millis() > nextBlink) {
    if (blinkyCount % 2) {
      digitalWrite(led, LOW);
      blinkyCount--;
      nextBlink += 150;
    } else {
      analogWrite(led, 10);
      nextBlink += 150;
      blinkyCount--;
    }
  } else if (blinkyCount == 1) {
    analogWrite(led, 10);
    blinkyCount = 0;
  }
}

This bit of code from you is the key part:
if (!digitalRead(btn) && millis() > debounceTimer) {
  debounceTimer = millis() + debounceDelay;
  rate++;
  rate %= 5;
  blinkyCount = (rate)*2+5;
  nextBlink = millis();
}

Specifically, the rate++ and rate %= 5 lines.
You have a 5-step temp setting. The analogRead() function returns a value from 0 to 1023, which you have to map to 0 to 4 (5 steps). Also, you can read the Potentiometer without worry about debouncing; thus:
if (true) {
  rate = map(analogRead(A0), 0, 1023, 0, 4);
  blinkyCount = (rate)*2+5;
  nextBlink = millis();
}

If you desire to have more than 5 "settings" for temperature, you could get a continuous range by eliminating the table onDelay[] and mapping the analog value between the high and low range of the acceptable onDelay values, so you get a finer control of the "on" delay time.
// No longer needs to be an array or a const
unsigned int onDelay = 6800;

Within checkButton():
if (true) {

  // Key Change here
  onDelay = map(analogRead(A0), 0, 1023, 6800, 4800);

  blinkyCount = (rate)*2+5;
  nextBlink = millis();
}

Update to runBurner():
void runBurner(){
  if (micros() > nextChange){
    if (onOff){
      digitalWrite(pwr, LOW);
      onOff = false;

      // Key Change here:
      nextChange += onDelay;

    }
    else {
      digitalWrite(pwr, HIGH);
      onOff = true;
      nextChange += offDelay;
    }
  }
}

thank you so much this really helps clear some things, and will try this code to give it a test, I really appreciate your time helping me with this

Correct - I only addressed the value-from-pot question and did not further debug the code.


text:
how can I break from this case by IRremote even if it's not finished yet?
I want to give a pause to case 0xFF02FD or at least to break from that case by entering the case 0xFFA25D even if the 1st case not finished, when I press power button wich has hexa code ( 0xFFA25D) I turn On the led and when I press playButton(0xFFA25D ) I turn on the piezoo and turn off the led (as you can see in my code) but I can't get out from that case by pressing powerButton again I should wait till it ends .
void loop() {
  if (irrecv.decode(&results)) {
    // If it's been at least 1/4 second since the last
    // IR received, toggle the relay
    Serial.println(results.value,HEX);
    irrecv.resume();
  }

  switch(results.value){
    case 0xFFA25D:
      digitalWrite(redPin,HIGH);
      break;

    case 0xFF02FD:
      digitalWrite(redPin,LOW);
      firstSection();

      //Play second section
      secondSection();

      //Variant 1
      beep(f, 250);
      beep(gS, 500);
      beep(f, 350);
      beep(a, 125);
      beep(cH, 500);
      beep(a, 375);
      beep(cH, 125);
      beep(eH, 650);

      delay(500);

      //Repeat second section
      secondSection();

      //Variant 2
      beep(f, 250);
      beep(gS, 500);
      beep(f, 375);
      beep(cH, 125);
      beep(a, 500);
      beep(f, 375);
      beep(cH, 125);
      beep(a, 650);
      delay(500);
      break;
  }
}

with if (something) break;?

that won't help, if  I can break by if condition I can do this just by calling another case,
the only way to use if ()break; is by setting the condition before entering that case, which is not effective.

you want to go to start of loop() ? use return;

for clarity: I know from the start what OP wants. But I answer what he asks, because Google likes StackExchange and people will come here to find an answer to the question, not what OP had in mind.

you need to clarify the problem in your mind ... it actually has nothing to do with the switch/case statement ... the real problem is how to interrupt a long subroutine with a button press..

You are not asking to simply exit a switch-case statement, but to react to your IR remote button press during the execution of other code. With a normal push button directly connected to the Arduino you would normally do this through an interrupt routine. Maybe the library, that you are using, supports decoding IR signals trough interrupts.
If not, you have one more option:
From your code it seems, that the IR receiving part is non-blocking. This means, that it only executes, if there is really something to receive, else it would let the program execute the rest of the code, not blocking the execution. Then you have to program your piezo code (the code in the case 0xFF02FD:) as non-blocking code (maybe using PWM hardware or timer interrupts to output the right frequency and just setting trigger variables in your switch-case statement).
When the piezo code is non-blocking, the decode function of the IR library is executed also during your beep sequence, so your program can react to the results of it.

thanks for your answer, so the best thing is to use timer interrupts,
is it ok to use timer0 to define an interrupt handler isn't this gonna mess with millis() or delay() ?

Yes, timer0 is used for millis() and delay() and you cannot simply define your own ISR for it without disabling the one defined somewhere in the avr includes (currently don't remember where exactly). Why not using another timer? The ATmega328P, which is used in Arduino UNO and Nano, has 3 timers. But be sure, that the timer you choose isn't used by the IR library.

actually, the IR library was using timer2 and I change it to timer3 because it was interfering with tone() function.
and thank you again.

If this answered your question, please mark it as the correct answer

Because you only check if (irrecv.decode(&results)) at the top of loop(), that is the only point in your code that you can change your action based on a new IR input.
While not an ideal solution, you could just insert if (irrecv.decode(&results)) {return;}in between all beep() calls.
//Variant 1
beep(f, 250);
if (irrecv.decode(&results)) {return;}
beep(gS, 500);
if (irrecv.decode(&results)) {return;}
beep(f, 350);
if (irrecv.decode(&results)) {return;}

and so on.
A better solution would be to avoid re-typing the same code by using loops and functions. You call beep() repeatedly with only the note and duration changing. You could put your sequence of notes and durations in an array and writing a new function that calls beep() for one element in the array and then increments a pointer to the next note to play. Your loop() calls this function and checks to see if there is any IR code ready also.
An even better solution would be to set up a hardware timer to produce regular interrupts and the ISR would check if there is IR data ready and set a global flag that is checked in the program.

thanks for your help,
what I did is I made 4 arrays of frequency and duration of tones and I put them in for loops for every function, and then I insert the  irrecv.decode(&results) on this loops, it works but it's a pain in the butt,

As noted in the other excellent answer by @chrisl, you are mixing non-blocking code and blocking code, but to have the ability to break out at any instant, you would need to have all your code be non-blocking. But beep() is a blocking function -- it doesn't return control until it's done. And to do what it does in a non-blocking way is a bit more complicated. An alternative is to edit IRrecv library so it can call a user function when a code is received, but again -- complicated.

I want to use timers interrupts but I'm not expert and I'm afraid to mess with delay or millis() ,that's why I was looking for an easy solution .
it seems that as you mentioned before using loops and arrays is the easiest thing I can do , so thanks.


text:
How to stop a loop when using attachInterrupt to catch the change of a button
This what the program does:

There is 1 button to start/stop the engine, when the motor is running
  the green LED will go on, when stopped the red LED is on. The second
  button is used to change the direction of the DC-motor. When the
  temperature is above 20° the motor will stop and the servo motor will
  go to the position of the red LED. Otherwise the servo motor is in a
  neutral position. When the engine is running there a music playing that should sound as a car.

So what my problem is if I pressed the button to stop the DC-motor but the music is still playing it won't stop. I read something about a break. Can you combine this with the attachInterrupt()? I also found something called interrupts() and noInterrupts(). What do I need to so when I pressed the button the DC-Motor directly stops and the led turns red?
The init
#include <Servo.h>
#include "notebook.h";
#include "themes.h";

const int input1OfTheDCMotor = 9;
const int input2OfTheDCMotor = 10;
const int pwmInputOfTheDCMotor = 6;
const int buttonToStartStopTheDcMotor = 2;
const int buttonToShowToChangeTheDirectionOfTheDCMotor = 3;
const int greenLed = 12;
const int redLed = 8;
const int tempSensor = A0;
const int servoPin = 11;
Servo servo;

volatile byte stateOfTheButtonToStartStopTheDCMotor = LOW;
bool isRunning = LOW;
bool changeDirection = LOW;
bool isEngineSoundsPlaying = HIGH;

The setup()
void setup() {
  //Leds setup
  pinMode(greenLed, OUTPUT);
  pinMode(redLed, OUTPUT);
  digitalWrite(redLed, HIGH);
  //buttons
  pinMode(buttonToStartStopTheDcMotor, INPUT);
  pinMode(buttonToShowToChangeTheDirectionOfTheDCMotor, INPUT);
  //DC motor
  pinMode(input1OfTheDCMotor, OUTPUT);
  pinMode(input2OfTheDCMotor, OUTPUT);
  digitalWrite(input1OfTheDCMotor, LOW);
  digitalWrite(input2OfTheDCMotor, HIGH);
  //pwm signal
  pinMode(pwmInputOfTheDCMotor, OUTPUT);
  //Servo
  servo.attach(servoPin);
  //interrupts
  attachInterrupt(digitalPinToInterrupt(buttonToStartStopTheDcMotor), readTheChangeToStartStop, RISING );
  attachInterrupt(digitalPinToInterrupt(buttonToShowToChangeTheDirectionOfTheDCMotor), readTheChangeToChangeDirection, RISING );
}

The loop()
void loop() {
  int valueOfTheSensor = analogRead(tempSensor);
  float voltage = (valueOfTheSensor / 1024.0) * 5.0;
  float temp = (voltage -0.5) * 100;
  if (temp >= 20.00)
    isRunning = LOW;
  }
  changeTheStateOfTheLights(isRunning);
  startTheDCMotorAndStopIt(isRunning);
  changeTheDirectionOfTheDCMotor(changeDirection);
}

The function readTheChangeToStartStop():
void readTheChangeToStartStop () {
  isRunning  = !isRunning;
  changeTheStatusOfTheEnginePlaying();
}

The function readTheChangeToChangeDirection():
void readTheChangeToChangeDirection () {
  changeDirection = !changeDirection;
}

The function changeTheStatusOfTheEnginePlaying():
void changeTheStatusOfTheEnginePlaying (){
  if (isRunning == HIGH){
    isEngineSoundsPlaying = HIGH;
  } else {
    isEngineSoundsPlaying = LOW;
  }
}

The function changeTheStateOfTheLights():
void changeTheStateOfTheLights(bool stateOfLight) {
  digitalWrite(greenLed, stateOfLight);
  digitalWrite(redLed, !stateOfLight);
}

The function startTheDCMotorAndStopIt():
void startTheDCMotorAndStopIt(bool isRunning){
  if (isRunning == HIGH) {
    digitalWrite(pwmInputOfTheDCMotor, HIGH);
    playCarMusicStart();
    changeToNeutral();
  } else {
    digitalWrite(pwmInputOfTheDCMotor, LOW);
    changeToRedLight();
  }
}

The function changeTheDirectionOfTheDCMotor():
void changeTheDirectionOfTheDCMotor(bool changeDirection) {
  digitalWrite(input1OfTheDCMotor, changeDirection);
  digitalWrite(input2OfTheDCMotor, !changeDirection);
}

The function changeToRedLight():
void changeToRedLight() {
  servo.write(0);
  delay(15);
}

The function changeToNeutral():
void changeToNeutral() {
  servo.write(40);
  delay(15);
}

The function playCarMusicStart():
void playCarMusicStart(){
  if (isEngineSoundsPlaying == HIGH) {
    for (int thisNote = 0; thisNote < (sizeof(carSounds_note)/sizeof(int)); thisNote++) {
      int noteDuration = 1000 / carsounds_duration[thisNote];
      tone(4, carSounds_note[thisNote], noteDuration);
      int pauseBetweenNotes = noteDuration * 2.70;
      delay(pauseBetweenNotes);
      noTone(4);
      isEngineSoundsPlaying = LOW;
    }
  }
}

Solution
A big thanks to @ratchet freak
I need to change my loop() to this:
void loop() {
  int valueOfTheSensor = analogRead(tempSensor);
  float voltage = (valueOfTheSensor / 1024.0) * 5.0;
  float temp = (voltage -0.5) * 100;
  if (temp >= 20.00) {
    isRunning = LOW;
  }
  changeTheStateOfTheLights(isRunning);
  startTheDCMotorAndStopIt(isRunning);
  changeTheDirectionOfTheDCMotor(changeDirection);

  playCarMusicStart();
}

I also needed to change the PlayCarMusicStart():
void playCarMusicStart(){
  if (isEngineSoundsPlaying == HIGH && currentNote < (sizeof(carSounds_note)/sizeof(int))) {
      int noteDuration = 1000 / carsounds_duration[currentNote];
      tone(4, carSounds_note[currentNote], noteDuration);
      int pauseBetweenNotes = noteDuration * 2.70;
      delay(pauseBetweenNotes);
      noTone(4);
      currentNote++;
   } else {
      currentNote = 0;
   }
}

And the least is to set the isEngineSoundsPlaying equal to HIGH, I changed the function startTheDCMotorAndStopIt() for:
void startTheDCMotorAndStopIt(bool isRunning){
  if (isRunning == HIGH) {
    isEngineSoundsPlaying = HIGH;
    digitalWrite(pwmInputOfTheDCMotor, HIGH);
    changeToNeutral();
  } else {
    isEngineSoundsPlaying = LOW;
    digitalWrite(pwmInputOfTheDCMotor, LOW);
    changeToRedLight();
  }
}

The key will be to split up playCarMusicStart and instead create a playCarMusicStep that will do just one iteration of the loop and returns. Call it every time in loop() akin to blinkWithoutDelay.
In playCarMusicStart you then setup the playing state so it starts playing correctly.
And when you need to stop it you then stop the music by setting the correct variable.

You mean this with blinkWithoutDelay https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay

The music loops takes 7400ms so when I pressed the button how can I stopped immediately without waiting 7400ms

by returning immediately after starting the music and calling the function again when new processing needs to occur for the next note/pauze

Thanks I updated the question with the solution a big thanks for helping me!