text:
Dimmer.h issues with ATmega 128
I am using a ZCD circuit controlling a TRIAC. Now I am using Dimmer library for this purpose. It works fine with ATMega 328 but whenever I try to upload the code in ATMega 128 using Arduino IDE this error pops up:
Arduino: 1.8.4 (Windows 10), Board: "ATmega128, 2.7v, Disabled (default), 16 MHz external"

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp: In member function 'void Dimmer::begin(uint8_t, bool)':

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:15:20: error: 'TCCR2A' was not declared in this scope

 #define _TCCRxA(X) TCCR ## X ## A

                    ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:16:19: note: in expansion of macro '_TCCRxA'

 #define TCCRxA(X) _TCCRxA(X)

                   ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:157:5: note: in expansion of macro 'TCCRxA'

     TCCRxA(DIMMER_TIMER) = TCCRxA_VALUE;         // Timer config byte A

     ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:17:20: error: 'TCCR2B' was not declared in this scope

 #define _TCCRxB(X) TCCR ## X ## B

                    ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:18:19: note: in expansion of macro '_TCCRxB'

 #define TCCRxB(X) _TCCRxB(X)

                   ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:158:5: note: in expansion of macro 'TCCRxB'

     TCCRxB(DIMMER_TIMER) = TCCRxB_VALUE;         // Timer config byte B

     ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:19:20: error: 'TIMSK2' was not declared in this scope

 #define _TIMSKx(X) TIMSK ## X

                    ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:20:19: note: in expansion of macro '_TIMSKx'

 #define TIMSKx(X) _TIMSKx(X)

                   ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:159:5: note: in expansion of macro 'TIMSKx'

     TIMSKx(DIMMER_TIMER) = 0x02;                 // Timer Compare Match Interrupt Enable

     ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:21:19: error: 'OCR2A' was not declared in this scope

 #define _OCRxA(X) OCR ## X ## A

                   ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:22:18: note: in expansion of macro '_OCRxA'

 #define OCRxA(X) _OCRxA(X)

                  ^

C:\Program Files (x86)\Arduino\libraries\Dimmer-master\src\Dimmer.cpp:160:5: note: in expansion of macro 'OCRxA'

     OCRxA(DIMMER_TIMER) = 100 * 60 / acFreq - 1; // Compare value (frequency adjusted)

     ^

exit status 1
Error compiling for board ATmega128.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Any idea what is the issue ?

ATMega328 and ATMega128 are not completely interchangeable .... the header file has either different register names or the registers do not exist in ATMega128

what core you use? it is possible, it has only different names. I checked the Dimmer library with MightyCore and for Atmega16/32/164 I get errors because they don't have the timer used by the library. but your errors a different. MightyCore doesn't support 128 (although it is in readme)

@Juraj I am using Megacore. I need to use 128 because I need a lot of ports.

@jsotola What you have pointed out looks like the problem.. that is obvious. but is there any work around ?

I need a lot of ports .... for what purpose? ..... it appears that this is an X-Y problem ..... you may or may not have a misguided solution to a lack of I/O pins and you are asking your question in an effort to make the solution work

The Dimmer library doesn't support Atmega128/164/16/32. It has
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
#define DIMMER_TIMER 4
#elif defined(__AVR_ATmega32U4__)
#define DIMMER_TIMER 3
#else
#define DIMMER_TIMER 2
#endif

For the Atmega128/164/16/32 it will use timer 2. The main errors are:
'OCR2A' was not declared in this scope
'TCCR2A' was not declared in this scope
'TCCR2B' was not declared in this scope
'TIMSK2' was not declared in this scope

Possible solution:
You could try to use timer 3. Only you need to change the timer number in Dimmer.h and in Dimmer.cpp on line 159 change TIMSKx(DIMMER_TIMER) = 0x02 perhaps to bitSet(ETIMSK, 3);. Check the datasheet. I can't test it, I don't have the chip.


text:
TX pin sends wrong data in Arduino Uno
I want to send some data to an IP Modem from Arduino Uno. That IP Modem has TTL levels TX and RX inputs.
I used this connection between Arduino to the IP Modem:

I am powering Arduino with 12 V plugged in the barrel.
This is the photo of the connections:

I connected the PC to the USB connector of Arduino and I uploaded the following sketch to send "AABB" to the Modem:
void setup(void) {
  Serial.begin(115200);
}

void loop(void) {
 Serial.print("AABB");

 delay(5000); // Envía la temperatura cada 5 segundos
}

When monitoring what is received by the modem, it is
0x5F 0x5F 0xAF 0x2F
If I send just "A", the character received each 5 seconds is 0x5F.
Of course, both ends are configured as 115,200bps, 8N1.
In order to discard Modem problem, I connected RX, TX and GND in Arduino to a DB9 female connector and then to a RS232 - USB converter and started monitoring with my PC.
My surprise was that the data received is exactly the same as the received by the modem when it was connected. As seen in the following picture:

As you see in the picture, "_" twice was shown (ASCII 0x5F), {\xaf} and finally "/" (ASCII 0x2F).
Above test confirms Arduino is sending wrong data.
Something to note. When I monitor using USB cable connected to Arduino and using Monitor Serie in the Arduino IDE, I  see correctly "AABB". The problem is when using TX and RX pins (the same happened if I used other pin along with SoftwareSerial library)
What may be going on?

pins 0 and 1 are used by the serial port to the PC ... choose some other pins and use software serial ...lots of examples can be found

Sorry, but It seems you did not read the whole question. I have connected pins 0 and 1 to the PC. Furthermore, I have done the same using SoftwareSerial library using other port. The same problem happens (as the final of the question tells)

i only read to the first picture ... it shows an interference between USB serial and the IP modem ... it is pointless to read any further

@jsotola as a teaching, don't read only the introduction to get the whole knowledge of a text

i understand what you are saying ... i simply made a comment about the first problem i saw .... please add your sketch that uses software serial

Please see the answer

Arduino and (all that Hardware like Arduino usb adapters) is sending Inverted (passiv is high) an the pc and all the "old" Hardware is sending NOT inverted. Only Software. Srial van send inverted - the hardware Serial can not. Same with ESP32 etc.

@Funkerman Yes.. I realized about that. I am electronical engineer so I understand electronical concepts however I am new to Arduino, but with this kind of problems I am facing, I can understand better how Arduino works. When I have more free time, I will take a look at Arduino cirtuit schematics. Also, if I develop more projects in Arduino, I will evaluate purchasing an oscilloscope to see the actual signals pins are sending.

Since you have already tried SoftwareSerial, also try inverting the serial protocol via SoftwareSerial.  Sometimes a device uses inverted serial protocol and you don't know it.
So initialize inverted add 1 to the end of the contructor like so :
SoftwareSerial mySerial(RXPIN, TXPIN,1); // RX, TX, inverted

you are a genius!! after 2 days of fight, that was the solution!

@jstuardo Additional note for faster research results the next time: Write down the bits as they are sent, and as they are received. Asynchronous serial communications uses LSB first here. 'A' = 0x41 = 0b01000001. Sent:0-1-0-0-0-0-0-1-0-1 Received: 0-1-1-1-1-1-0-1-0-1. I think it's quite obvious. ;-) Alternative way: Use an oscilloscope and watch TX and RX.

@thebusybee that is transparent for the systems. Sender always sends the data using LSB first, and receiver receives the data with LSB first. By the way, if 0x41 (0b01000001) is sent, it is actually sent 1-0-0-0-0-0-1-0 and received 0-1-1-1-1-1-0-1. I don't know why do you showed different bit pattern. And using oscilloscope is interesting, however, it is not really necessary for now. The key point here is that inverted bits are actually transmitted.

Yes, I know about the inverted bits. I added the start and stop bits to show that they are relevant for the analysis. -- And since I don't know your (and future readers') experiences I mentioned "LSB first." Not all serial communication protocols use this.

source: Stack Exchange

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

sort: votes


text:
Sparkfun Spectrum Analyzer: Problems with frequency bands
I bought around 2 years ago the Spectrum Analyzer Shield from Sparkfun, but I never had the time to do something with it. Recently I found the time to start a project to build a graphical equalizer. For that I use the Spectrum Analyzer Shield to split the left and right audio channel into 7 different bands. After I finished to build my first LED-Matrix panel and tested it out with the Spectrum Analyzer Shield I thought that everything works as it should. I made than the second LED-Matrix panel and tested everything again. Well, the result was odd. I noticed that the order of the bands inside of my arrays are switching around between every restart of my Arduino. Here are two example outputs. I played a 64 Hertz tone and expected to see an increase for the right and left channel for the first band.
Band0 R:70 ,L: 76 | Band1 R:92 ,L: 81 | Band2 R:548 ,L: 83 | Band3 R:108 ,L: 575 | Band4 R:76 ,L: 108 | Band5 R:64 ,L: 82 | Band6 R:63 ,L: 83 |
Band0 R:67 ,L: 78 | Band1 R:87 ,L: 83 | Band2 R:552 ,L: 82 | Band3 R:108 ,L: 575 | Band4 R:80 ,L: 109 | Band5 R:68 ,L: 83 | Band6 R:63 ,L: 78 |
Band0 R:77 ,L: 75 | Band1 R:88 ,L: 78 | Band2 R:546 ,L: 83 | Band3 R:105 ,L: 575 | Band4 R:79 ,L: 109 | Band5 R:61 ,L: 79 | Band6 R:59 ,L: 77 |
Band0 R:73 ,L: 74 | Band1 R:92 ,L: 85 | Band2 R:546 ,L: 84 | Band3 R:113 ,L: 572 | Band4 R:78 ,L: 105 | Band5 R:58 ,L: 74 | Band6 R:65 ,L: 78 |
Band0 R:71 ,L: 77 | Band1 R:92 ,L: 82 | Band2 R:550 ,L: 84 | Band3 R:107 ,L: 573 | Band4 R:76 ,L: 107 | Band5 R:59 ,L: 76 | Band6 R:59 ,L: 79 |

After restart of the arduino (pressed 5 sec the reset button)
Band0 R:71 ,L: 576 | Band1 R:86 ,L: 106 | Band2 R:545 ,L: 87 | Band3 R:107 ,L: 82 | Band4 R:76 ,L: 78 | Band5 R:55 ,L: 80 | Band6 R:61 ,L: 79 |
Band0 R:71 ,L: 575 | Band1 R:83 ,L: 105 | Band2 R:549 ,L: 80 | Band3 R:109 ,L: 87 | Band4 R:75 ,L: 79 | Band5 R:55 ,L: 84 | Band6 R:64 ,L: 78 |
Band0 R:69 ,L: 575 | Band1 R:88 ,L: 103 | Band2 R:546 ,L: 79 | Band3 R:109 ,L: 82 | Band4 R:73 ,L: 79 | Band5 R:63 ,L: 78 | Band6 R:62 ,L: 84 |
Band0 R:70 ,L: 575 | Band1 R:87 ,L: 103 | Band2 R:547 ,L: 84 | Band3 R:106 ,L: 82 | Band4 R:76 ,L: 78 | Band5 R:61 ,L: 80 | Band6 R:61 ,L: 90 |
Band0 R:71 ,L: 574 | Band1 R:83 ,L: 106 | Band2 R:550 ,L: 79 | Band3 R:109 ,L: 84 | Band4 R:77 ,L: 77 | Band5 R:57 ,L: 85 | Band6 R:60 ,L: 81 |
Band0 R:64 ,L: 576 | Band1 R:92 ,L: 109 | Band2 R:549 ,L: 80 | Band3 R:105 ,L: 80 | Band4 R:75 ,L: 72 | Band5 R:56 ,L: 76 | Band6 R:60 ,L: 80 |

I experienced the same issue with the source code from Sparkfun: https://github.com/sparkfun/Spectrum_Shield/blob/HW_1.6_FW_1.1/Firmware/SparkFun_Spectrum_Demo/SparkFun_Spectrum_Demo.ino
I modified this code only slightly to log everything.
void Read_Frequencies(){
  //Read frequencies for each band
  for (freq_amp = 0; freq_amp<7; freq_amp++)
  {
    Frequencies_One[freq_amp] = analogRead(DC_One);
    Frequencies_Two[freq_amp] = analogRead(DC_Two);
    digitalWrite(STROBE, HIGH);
    digitalWrite(STROBE, LOW);

    Serial.print("Band");
    Serial.print(freq_amp);
    Serial.print(" R:");
    Serial.print(Frequencies_One[freq_amp]);
    Serial.print(" ,L: ");
    Serial.print(Frequencies_Two[freq_amp]);
    Serial.print(" | ");
  }
  Serial.println("");
}

Hopefully I'm doing something fundamental wrong, if not that would mean I have to buy a new Shield :/

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


text:
Using typedef to declare a buffer type which then to pass by reference as function argument
I'm new to Arduino, but I'm a C/C++ veteran (not to mention some other languages).
Now I was under the impression that the code I'm typing into the Arduino IDE was a C or C++ dialect. However, just now I ended up puzzled because the compiler wouldn't swallow either of the following:
#define RFID_SIZE 5
#define CSUM_SIZE 1
typedef unsigned char rfidbuf_t[RFID_SIZE+CSUM_SIZE];

or my first attempt:
#define RFID_SIZE 5
#define CSUM_SIZE 1
typedef byte rfidbuf_t[RFID_SIZE+CSUM_SIZE];

Now I figure that a #define ought to be cheaper than a constant, so that's why I went for defines. The fact that #include is supported suggested to me there'd be a cpp in the Arduino development environment as well.
What struck me as odd was the fact that I get to see the error only on the next code line (not on the line with the typedef):
rfid_serial.ino:6:18: error: ‘rfidbuf_t’ was not declared in this scope
rfid_serial.ino:6:29: error: ‘code’ was not declared in this scope
rfid_serial.ino: In function ‘bool ReadRFIDTag(byte (&)[6])’:
rfid_serial.ino:15:33: error: ‘bool ReadRFIDTag(byte (&)[6])’ redeclared as different kind of symbol
rfid_serial.ino:6:6: note: previous declaration ‘bool ReadRFIDTag’
rfid_serial.ino: In function ‘void loop()’:
rfid_serial.ino:96:21: error: ‘ReadRFIDTag’ cannot be used as a function

The code I came up with was an attempt at optimizing the way this works. In particular I noticed that String (a class, it seems?!) Increases the size of my code quite a lot. So I thought a reference to the buffer would be a sensible choice here.
Here's the complete code:
#include <SoftwareSerial.h>
#define RFID_SIZE 5 // the code size (digits) of the RFID tag.
#define CSUM_SIZE 1  // the csum size (digits) of the RFID tag.
typedef byte rfidbuf_t[RFID_SIZE+CSUM_SIZE];

SoftwareSerial RFID(2, 3); // RX and TX

void setup()
{
  RFID.begin(9600); // start serial to RFID reader
  Serial.begin(115200); // start serial to PC
}

/* From: https://efxa.org/2013/05/23/simple-function-implementation-for-parsing-rfid-tags-in-arduino/ and adjusted. */
bool ReadRFIDTag(rfidbuf_t& code)
{
  byte value = 0;       // temporary data received from RFID reader.
  byte checksum = 0;    // checksum data of RFID tag received.
  byte bytesRead = 0;   // number of received data from RFID reader.
  byte tempByte = 0;    // temporary value used for checksum calculation.

  bool handled = false; // flag indicating if an RFID tag was handled.

  // if there are any data coming from the RFID reader.
  if (RFID.available () > 0)
  {
    // check for the STX header (0x02 ASCII value).
    if (0x02 == (value = RFID.read ()))
    {
      // read the RFID digits & the checksum digits.
      while (bytesRead < (RFID_SIZE + CSUM_SIZE))
      {
        // if there are any data coming from the RFID reader.
        if (RFID.available () > 0)
        {
          // get a byte from the RFID reader.
          value = RFID.read ();

          // check for ETX | STX | CR | LF.
          if ((0x0D == value) || (0x0A == value) || (0x03 == value) || (0x02 == value))
          {
            // stop reading - there is an error.
            break;
          }

          // convert hex tag ID.
          if ((value >= '0') && (value <= '9'))
          {
            value = value - '0';
          }
          else if ((value >= 'A') && (value <= 'F'))
          {
            value = 10 + value - 'A';
          }

          // every two hex-digits, add byte to code.
          if (bytesRead & 1 == 1)
          {
            // make some space for this hex-digit by shifting
            // the previous hex-digit with 4 bits to the left.
            code[bytesRead >> 1] = (value | (tempByte << 4));

            if (bytesRead >> 1 != 5)
            {
              // if this is checksum byte, calculate the checksum (XOR).
              checksum ^= code[bytesRead >> 1];
            }
          }
          else
            tempByte = value;

          // ready to read next digit.
          bytesRead++;
        }
      }

      // handle the RFID digits & the checksum digits.
      if (bytesRead == (RFID_SIZE + CSUM_SIZE))
      {
        // check if the RFID code is correct.
        if (code[5] == checksum)
        {
          // set that the tag was handled.
          handled = true;
        }
      }
    }
  }

  return handled;
}

void loop()
{
  rfidbuf_t buf = {0};
  if(ReadRFIDTag(buf))
  {
    Serial.println(buf[0]); // TODO
  }
}

Is it impossible to use typedef the same I'm used to from C and C++? Because what I am attempting isn't all too unusual in C or C++ code, but of course references only exist in C++.
Does it mean I should rather into working with avr-gcc directly? I was under the impression that the Arduino IDE is basically built atop avr-gcc and avrdude (and possibly other backend programs).

Side-note: I do know that there are still some issues in the code and it's not a faithful conversion of the linked code, yet. Problem is that I got stuck with the typedef, a seemingly trivial thing.

Compiles fine for me. What version of the IDE / compiler are you using?

@Majenko: 2:1.0.5+dfsg2-4 (latest version on latest Linux Mint).

1.0.5 is preancient. Please consider using something modern, even if you have to download it yourself.

Latest... that'a s a laugh...  You mean the ancient version that got left in APT a decade ago...

@Majenko: no, I meant latest available. Thanks for setting my head straight, nevertheless.

The latest in APT - not the latest available. That is version 1.8.5

Yes, I realize that. But keep in mind, if you don't rely on a  package manager to some extent you're usually a lost case as an admin. But duly noted, apparently I cannot trust that there are reasonably recent versions available via apt.

Your version of the IDE (1.0.5) is incredibly ancient (just because it's in APT doesn't mean it's up to date - only that at some point within the last 20 years someone submitted it).
That version suffers from the problems that Ignacio describes in his answer. More modern versions (we're up to version 1.8.5 now...!) use a different build system which is far more intelligent about how it lays out its function prototypes.
Go to the Arduino website and download the latest version and you won't have these kind of problems and have to work around them with strange things like unnamed namespaces.

The Arduino IDE (un)helpfully copies function declarations towards the top, but fails to handle custom types properly. The solution is to hide the declarations in an unnamed namespace.
 ...
typedef byte rfidbuf_t[RFID_SIZE+CSUM_SIZE];

namespace {
  bool ReadRFIDTag(rfidbuf_t& code);
}
 ...

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


text:
How can I put this display SSD1306 to sleep?
I have built a kitchen timer and it is supposed to spend most of its life in sleep mode in order to save power. I am using the SSD1306Ascii library (SPI) by William Greiman.
In this library I have found hints to power on and off commands but I don't know how to use them:
/** Set Display off. */
#define SSD1306_DISPLAYOFF 0xAE
/** Set Display on. */
#define SSD1306_DISPLAYON 0xAF

From what I could gather from the web, I need to re-initialize the display after turning it off and on again. But before I take care of that (which should be simple as it is done in setup anyway) I need to find out how to use these commands.
Would you help out a rookie?

So doing oled.ssd1306WriteCmd(0xAE); had no effect?

Can you post a link to the data sheet/instructions for the display?

@MaximilianGerhardt It does have aneffect. Even the desirred one. But until you mentioned it I did not know how to use it. I did not stumble upon ssd1306WriteCmd in the documentation - or upon example to be precise. Thank you!

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


text:
How to use one button with interrupt to enable and disable sleep mode?
I have written a program for a kitchen timer. The timer uses just one single rotary encoder with a push button on its axis. It has modes for counting up and for counting down. After counting down it switches into alarm state. When I then push the button the alarm stops and the device goes into sleep mode.
To wake it up I need to either push the button again or twist the encoder.
The problem: When I push the button during alarm the device does go into sleep mode but since that very same button is used to wake it up again, the timer switches into the wrong state and freezes in sleep mode. At least that is my interpretation of the problem:
Pushing the button during alarm triggers sleep mode ( goToSleep() ). During goToSleep I attach to that very button the interrupt that wakes the device.
The solution must be simple, I just can't see it. I just need to ignore any button input beween calling goToSleep() and sleepcpi();. Right?
How can I make this work?
#include <avr/sleep.h>
#include <Rotary.h>
#include <Bounce2.h>

unsigned long timerSeconds = 0;   // Remaining countdown time in seconds. An unsigned int would be enough for more than 18 HOURS!
unsigned long alarmTime = 0;      // The absolute point in time of the alarm

// Variables for updates
unsigned long currentMillis = 0;
unsigned long previousMillis = 0;
unsigned long currCountMillis = 0;
unsigned long prevCountMillis = 0;

// Setup Pins & Variables
Rotary rotary = Rotary(3, 4);     // Needs to be pin 2 or 3 in order to use as interrupt
const byte encBtnPin = 2;         // Needs to be pin 2 or 3 in order to use as interrupt
const byte beepPin = 5;

byte encBtnState;
byte prevEncBtnState;
bool encBtnPushed = false;
Bounce debouncer = Bounce();

// Setup state machine
typedef enum { NONE, SETTING, COUNTING_DOWN, COUNTING_UP, WAS_COUNTING, ALARM } states;
states state = NONE;

void setup() {
  Serial.begin(9600); //remove after testing

  pinMode(encBtnPin, INPUT_PULLUP);
  debouncer.attach(encBtnPin);
  debouncer.interval(10);
  pinMode(beepPin, OUTPUT);

  // Turn off ADC
  ADCSRA = 0;
}

void loop() {
            Serial.println("Top of loop"); // Remove after testing
            Serial.print("State: "); // Remove after testing
            Serial.println(state); // Remove after testing
  switch (state) {
    case NONE:
      goToSleep();
      break;
    case SETTING:
      setCountdown();
      break;
    case COUNTING_DOWN:
      startCountdown();
      break;
    case COUNTING_UP:
      startCounter();
      break;
    case ALARM:
      alarm();
      break;
  }
}

void readEncButton() {
  encBtnState = digitalRead(encBtnPin);     // Check if button state has changed
  if (encBtnState != prevEncBtnState) {
    if (encBtnState == LOW) {
      encBtnPushed = true;
      beep();
    }
  }
  prevEncBtnState = encBtnState;

  if (encBtnPushed) {                     // If Button has been pushed ...
    encBtnPushed = false;                 // ... reset button and do one of the following ...
    switch (state) {                      // Core state machine (state changes)
      case NONE:
        break;
      case SETTING:
        if (timerSeconds != 0) {          // Start countdown only if timer is not = 0 ...
          state = COUNTING_DOWN;
              Serial.print("State: "); // Remove after testing
              Serial.println(state); // Remove after testing
        }
        else {                            // If timer = 0, go to sleep
          state = NONE;
              Serial.print("State: "); // Remove after testing
              Serial.println(state); // Remove after testing
        }
        break;
      case COUNTING_DOWN:
        timerSeconds = (timerSeconds / 10) * 10;        // Set last digit to zero ...
        state = SETTING;                                // ... then go back to setting time
        break;
      case COUNTING_UP:
        timerSeconds = 0;
        state = SETTING;
        break;
      case ALARM:
        state = NONE;
        break;
    }
  }
}

void setCountdown() {
  // Read rotary encoder input
  unsigned long timeOut = millis();
  while (state == SETTING) {
    unsigned char result = rotary.process();
    if (result == DIR_CW) {
      timerSeconds += 10L;
      timeOut = millis();
      writeDisplay();
    }
    else if (result == DIR_CCW) {
      timerSeconds -= 10L;
      timeOut = millis();
      writeDisplay();
    }
    if ( millis() >= timeOut + 30000L ) {         // Go to sleep after 30 seconds idle
      state = NONE;
    }
    // Read rotary encoder button
    readEncButton();
  }
}

void startCountdown() {
  alarmTime = millis() + (timerSeconds * 1000L);  // Determine absolute alarm point in time in milliseconds (only once on countdown start)
  while (state == COUNTING_DOWN) {
    updateDisplay();
    timerSeconds = ( alarmTime - millis() ) / 1000L;            // Calculate new remaining number-of-seconds
    readEncButton();
  }
}

void startCounter() {
  while (state == COUNTING_UP) {
    currCountMillis = millis();
    updateDisplay();
    if (currCountMillis - prevCountMillis > 999) {              // Update counter once per second
      prevCountMillis = currCountMillis;
      timerSeconds ++;
    }
    readEncButton();
  }
}

void updateDisplay () {
  currentMillis = millis();

  // Only once every 1000ms ...
  if (currentMillis - previousMillis > 999) {
    previousMillis = currentMillis;                           // Reset the timer for display updates
    writeDisplay();
  }
}

void writeDisplay() {
  int cHours = timerSeconds / 3600L;                        // Update variables to display
  int cMinutes = timerSeconds % 3600L / 60;
  int cSeconds = timerSeconds % 3600L % 60;
  // Format and print display data
  if (cHours == 0 || cHours < 10) {Serial.print("0");}      // Add leading "0" if necessary
  Serial.print(cHours);
  Serial.print(":");
  if (cHours == 0 || cMinutes < 10) {Serial.print("0");}    // Add leading "0" if necessary
  Serial.print(cMinutes);
  Serial.print(":");
  if (cSeconds == 0 || cSeconds < 10) {Serial.print("0");}  // Add leading "0" if necessary
  Serial.println(cSeconds);
  // Alarm trigger follows here since alarm is supposed to sound AFTER the nillth second has been displayed
  if (state == COUNTING_DOWN && timerSeconds == 0) {
    state = ALARM;
  }
}

void beep() {
  tone(beepPin, 1000, 120);
}

void alarm() {
  int alarmRep = 0;
  attachInterrupt(digitalPinToInterrupt(encBtnPin), endAlarm, LOW);
  while (state == ALARM && alarmRep < 30) {
    for (int i = 0; i < 4; i ++) {
      tone(beepPin, 2000, 100);
      delay(120);
    }
    delay(500);
    alarmRep ++;
  }
  goToSleep();          // Go to sleep after alarm (state is changed to NONE in sleepmode-setup)
  //state = NONE;       // Need condition to prevent state = NONE in case previous while-loop was left due to state change
}

void endAlarm() {
  detachInterrupt(digitalPinToInterrupt(encBtnPin));
  state = NONE;
}

/* Sleep mode and stuff *
************************/

void wakeToSet() {
  sleep_disable();
  detachInterrupt(digitalPinToInterrupt(3));          // Hard-coded to pin 3
  detachInterrupt(digitalPinToInterrupt(encBtnPin));  // Encoder button can no longer wake up CPU
  state = SETTING;
}

void wakeToCount() {
  sleep_disable();
  Serial.println("Detaching interrupts ...");         // Remove after testing
  detachInterrupt(digitalPinToInterrupt(3));          // Hard-coded to pin 3
  detachInterrupt(digitalPinToInterrupt(encBtnPin));  // Encoder button can no longer wake up CPU
  beep();
  Serial.println("Waking up to count ...");           // Remove after testing
  state = COUNTING_UP;
}

void goToSleep() {
  Serial.println("Starting goToSleep()");             // Remove after testing
  timerSeconds = 0;                                   // Reset everything
  alarmTime = 0;
  state = NONE;
  sleep_enable();
  attachInterrupt(digitalPinToInterrupt(3), wakeToSet, LOW);             // Hard-coded to pin 3
  attachInterrupt(digitalPinToInterrupt(encBtnPin), wakeToCount, LOW);   // Encoder button can wake up machine
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  Serial.print("State: "); // Remove after testing
  Serial.println(state); // Remove after testing
  Serial.println("Going to sleep now..."); // Remove after testing
  delay(250);
  sleep_cpu();
}

You need to change to the NONE state on button release, instead of press. Of have the goToSleep function wait till the button is released (while(dititalRead(encBtnPin)==LOW){delay(10);}). I used a PRE-SLEEP state in one of my projects. Then when the button is released and you are in the PRE-SLEEP state, move to the SLEEP (NONE) state.

Thank you. That one line (delay) fixed the whole thing. Thanks. I'll keep the PRE-SLEEP state in mind for future projects.

couple of thoughts: a fritzing Diagram of your Connections may help. as far as i can tell you connect the (?data?) lines of the Encoder to the Interrupt lines? do you want to trigger an Interrupt on Input value Change? like from 4 minutes to 5minutes? did you Thing of debouncing your switches? (just saw you do it in Software... consider a simple RC lowpass instead. Maybe the debouncing uses a timer and then collides with the remaining logic...) do you really Need to now the previous Button state? another Thing i see is you just have an awful lot of Code. consider taking out a piece of paper and draft a state Diagram for the statemachine your About to realise. and then share it here (makes life a lot easier!)

Thank you for your time looking into this. To reply to your questions in order: 1) Trigger an interrupt on input value change? Yes. 2) No. Only during sleep mode. 3) yes but this solution seems easier to implement. 4) Yes, I really need to know. state diagram: I'll do it next time it is necessary (I hope not). Thank you.


text:
Why can I wake Arduino only once with this code?
This is my enhanced code for a daylight alarm on Arduino UNO with an added MP3-Player.
The device is supposed to sleep all the time except when I hit the play button (then it is supposed to play music) or when the RTC wakes it up, both via interrupt. When the RTC wakes it up it will start its actual daylight alarm routine.
I just implemented the sleep/power-down code and got it working so that I could wake it up and put it to sleep with pins 9 (sleep) and 2 (wake up via interrupt). There was a problem though and I had to change the code.
Apparently while trying to fix it I broke something. The current behiour upon startup is:
1. Go to sleep (correct)
2. When I bridge pin 2 and ground, it wakes up. (correct)
3. When I then bridge pin 9 and ground it goes to sleep. (correct).
4. When I bridge pin 2 and ground again it does not wake up again.
I have changed the code so that in addition to playing music the builtin LED will light up.
#include <avr/sleep.h>
/************ init mp3-player ***************/
#include <SoftwareSerial.h>

#define ARDUINO_RX 4  //should connect to TX of the Serial MP3 Player module
#define ARDUINO_TX 5  //connect to RX of the module

SoftwareSerial mp3(ARDUINO_RX, ARDUINO_TX);
static int8_t Send_buf[8] = {0}; // Buffer for Send commands.  // BETTER LOCALLY
String sbyte2hex(uint8_t b);

#define CMD_SLEEP_MODE    0X0A
#define CMD_WAKE_UP       0X0B
#define CMD_SEL_DEV       0X09
#define CMD_PLAY          0X0D
#define CMD_STOP_PLAY     0X16  // Stop playing continuously.
#define CMD_FOLDER_CYCLE  0X17
#define CMD_SET_DAC       0X1A
#define DAC_ON            0X00
#define DAC_OFF           0X01
#define DEV_TF            0X02

/**************** init the real time clock ***************/
#include <Rtc_Pcf8563.h>
Rtc_Pcf8563 rtc;

/**************** setup pins & buttons ***************/
const byte led = 11; // Pin LED is connected to
const byte sixAmPin = 6; // Pin for set-alarm-to-6am-button
const byte sevenAmPin = 7; // Pin for set-alarm-to-7am-button
const byte eightAmPin = 8; // Pin for set-alarm-to-8am-button
const byte stopPin = 9; // Pin for stop button
const byte timeResetPin = 10; // Pin for reset-clock-to-9am-button (useful e.g. after battery failure)
const byte playPin = 2; // Pin for play-music-button (and interrupt!)
const byte rtcIntPin = 3; // Pin for RTC interrupt

byte sixAmButton = 1; // State of 6am-set-button
byte sevenAmButton = 1; // State of 7am-set-button
byte eightAmButton = 1; // State of 8am-set-button
byte stopButton = 1; // State of stopButton
byte timeResetButton = 1; // State of time-set-button
byte playButton = 1; // State of play-music-button

byte brightness = 0; // LED brightness
bool wakeupMode = false;
unsigned long prevStepTime = millis();
unsigned long time;

/*************** Changeable variables here **************/
byte setHour = 6;
byte setMin = 30;
byte fadeDuration = 30; // Duration of fade in minutes (default: 30)
byte afterBurn = 30; // Keep light on after alarm for this many minutes (default: 30)
/********************************************************/

unsigned long keepLight = afterBurn * 60000UL; // Calculate time to keep LED on after fade (in ms)
int fadeStepLength = fadeDuration * 60000 / 255; // Calculate step duration for increasing LED brightness (in ms) (default: fadeDuration * 60000 / 255)

void setup() {
  /*DEBUG*/
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, HIGH);
  /*DEBUG END*/

  // Serial.begin(9600); //uncomment after testing
  mp3.begin(9600);
  delay(500);

  sendCommand(CMD_SEL_DEV, 0, DEV_TF);
  delay(500);

  // declare LED pin to be an output:
  pinMode(led, OUTPUT);

  // declare button pins as inputs:
  pinMode(stopPin, INPUT_PULLUP);
  pinMode(sixAmPin, INPUT_PULLUP);
  pinMode(sevenAmPin, INPUT_PULLUP);
  pinMode(eightAmPin, INPUT_PULLUP);
  pinMode(timeResetPin, INPUT_PULLUP);
  pinMode(playPin, INPUT_PULLUP);
  pinMode(rtcIntPin, INPUT_PULLUP);

  attachInterrupt(digitalPinToInterrupt(playPin), wakeUpPlay, FALLING);
  attachInterrupt(digitalPinToInterrupt(rtcIntPin), wakeAlarm, FALLING);
}

void loop() {
  goToSleep();
}

void wakeup() {
  // If wake-up-mode is true and brightness < 255, add +1 to brightness every 7 seconds (256 steps)
  wakeupMode = true;
  while (wakeupMode == true) {
    //update clock
    time = millis();

    // If current time is wakeup-time, increase LED brightness slowly over the course of 30 minutes
    if (brightness < 255 ) {
      // Delay brightening in steps. Do only if interval has passed.
      if (time > prevStepTime + fadeStepLength) {
        brightness ++;
        prevStepTime = millis(); // Resets counter to restart interval
      }
     }
    // Turn off light and exit wakupMode x minutes after max brightness
    else if (brightness == 255 && time > prevStepTime + keepLight) {
      brightness = 0;
      wakeupMode = false; // Exit wakeupMode loop
    }
    readButtons(); // Check for button input
    analogWrite(led, brightness); // Set LED brightness accordingly
  }
  goToSleep;
}

void readButtons() {
  // Always run this:
  // Check if alarm gets set for 6, 7 or 8am
  sixAmButton = digitalRead(sixAmPin);
  if (sixAmButton == LOW) {
    rtc.setAlarm(5, 30, 99, 99);
  }
  sevenAmButton = digitalRead(sevenAmPin);
  if (sevenAmButton == LOW) {
    rtc.setAlarm(6, 30, 99, 99);
  }
  eightAmButton = digitalRead(eightAmPin);
  if (eightAmButton == LOW) {
    rtc.setAlarm(7, 30, 99, 99);
  }

  // If stopButton is pressed: stop playing music, turn off LED, sleep mp3-player, sleep arduino
  stopButton = digitalRead(stopPin);
  if (stopButton == LOW) {
    wakeupMode = false;
    brightness = 0; // uncomment after testing
    analogWrite(led, brightness); // Set LED brightness accordingly
    sendCommand(CMD_STOP_PLAY);
    sendCommand(CMD_SLEEP_MODE);
    delay(200);
    goToSleep();
  }

  // If timeResetButton is pressed, reset RTC to 9am
  if (timeResetButton == LOW) {
    rtc.setTime(9, 0, 0);
  }

  // If Play music button is pressed, start playing music
  playButton = digitalRead(playPin);
  if (playButton == LOW) {
    playMusic();
    }
}

void playMusic(){
  digitalWrite(LED_BUILTIN, HIGH);
  sendCommand(CMD_WAKE_UP);
  delay(200);
  sendCommand(CMD_FOLDER_CYCLE, 1, 0);
  while (1){
    readButtons();
  }
}

void wakeUpPlay(){
  sleep_disable();
  detachInterrupt(digitalPinToInterrupt(playPin));
  detachInterrupt(digitalPinToInterrupt(rtcIntPin));
  playMusic();
}

void wakeAlarm(){
  sleep_disable();
  detachInterrupt(digitalPinToInterrupt(playPin));
  detachInterrupt(digitalPinToInterrupt(rtcIntPin));
  wakeup();
}

void goToSleep() {
  sleep_enable();
  attachInterrupt(digitalPinToInterrupt(playPin), wakeUpPlay, FALLING);
  attachInterrupt(digitalPinToInterrupt(rtcIntPin), wakeAlarm, FALLING);
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  digitalWrite(LED_BUILTIN, LOW);
  delay(500);
  sleep_cpu();
}

/**************************/
/** Stuff for MP3 player **/
/**************************/

/********************************************************************************/
/*Function: Send command to the MP3                                             */
/*Parameter: byte command                                                       */
/*Parameter: byte dat1 parameter for the command                                */
/*Parameter: byte dat2 parameter for the command                                */

void sendCommand(byte command){
  sendCommand(command, 0, 0);
}

void sendCommand(byte command, byte dat1, byte dat2){
  delay(20);
  Send_buf[0] = 0x7E;    //
  Send_buf[1] = 0xFF;    //
  Send_buf[2] = 0x06;    // Len
  Send_buf[3] = command; //
  Send_buf[4] = 0x01;    // 0x00 NO, 0x01 feedback
  Send_buf[5] = dat1;    // datah
  Send_buf[6] = dat2;    // datal
  Send_buf[7] = 0xEF;    //
  Serial.print("Sending: ");
  for (uint8_t i = 0; i < 8; i++)
  {
    mp3.write(Send_buf[i]) ;
    Serial.print(sbyte2hex(Send_buf[i]));
  }
  Serial.println();
}

/********************************************************************************/
/*Function: sbyte2hex. Returns a byte data in HEX format.                       */
/*Parameter:- uint8_t b. Byte to convert to HEX.                                */
/*Return: String                                                                */

String sbyte2hex(uint8_t b)
{
  String shex;

  shex = "0X";

  if (b < 16) shex += "0";
  shex += String(b, HEX);
  shex += " ";
  return shex;
}

/********************************************************************************/
/*Function: shex2int. Returns a int from an HEX string.                         */
/*Parameter: s. char *s to convert to HEX.                                      */
/*Parameter: n. char *s' length.                                                */
/*Return: int                                                                   */

int shex2int(char *s, int n){
  int r = 0;
  for (int i=0; i<n; i++){
     if(s[i]>='0' && s[i]<='9'){
      r *= 16;
      r +=s[i]-'0';
     }else if(s[i]>='A' && s[i]<='F'){
      r *= 16;
      r += (s[i] - 'A') + 10;
     }
  }
  return r;
}

I can only imagine that the problem lies in the way I send Arduino to sleep when playing music (i.e. the way I call goToSleep(); from the wakeUpPlay()-class). Waking up from sleep does work when sleep was induced from the main loop (apparently). Do you have any idea what is wrong?
(I thought about reducing my code to the bare minimum so it is less confusing for you - but then I'd probably change too much to find the bug).

reducing the code to bare minimum is the way to go for finding the bug   ...... just comment out sections of code

True - I did reduce it but couldn't find the problem. But for asking the questioned I figured it would be better to present the code in its entirety.

All your music playing code is inside a interrupt. While an interrupt is running all other interrupts are disabled. It's advised to keeps interrupt routines as short as possible.
You could have the interrupt routine set a boolean variable. Then in the loop function read that variable and call the play-music function.
volatile boolean startPlayback = false;

...

void wakeUpPlay(){
  startPlayback = true;
  sleep_disable();
  detachInterrupt(digitalPinToInterrupt(playPin));
  detachInterrupt(digitalPinToInterrupt(rtcIntPin));
}

...

void loop() {
  goToSleep();
  if( startPlayback )
  {
    startPlayback = false;
    playMusic();
  }
}

Do something similar with wakeAlarm.

Thanks. I did wonder where the program ends up once it got inside the wakeUpPlay routine - or where it would go afterwards. But I did not take the step back necessary to get a look at where it "came from" and so I just did not realize it was essentially still inside the interrupt.


text:
Global or local
I'm new to Arduino and embedded, but understand that it is often better to use global instead of local variables (such as here or here).
I have this simple code (from here):
//Libraries
#include <DHT.h>;

//Constants
#define DHTPIN 2     // what pin we're connected to
#define DHTTYPE DHT22   // DHT 22  (AM2302)
DHT dht(DHTPIN, DHTTYPE); //// Initialize DHT sensor for normal 16mhz Arduino

//Variables
float hum;  //Stores humidity value
float temp; //Stores temperature value

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

}

void loop()
{
    //Read data and store it to variables hum and temp
    hum = dht.readHumidity();
    temp= dht.readTemperature();
    //Print temp and humidity values to serial monitor
    Serial.print("Humidity: ");
    Serial.print(hum);
    Serial.print(" %, Temp: ");
    Serial.print(temp);
    Serial.println(" Celsius");
    delay(2000); //Delay 2 sec.
}

My ancient C programmer training (Unix servers) says I must move variables hum and temp to loop(), or is it better on Arduino to leave them as globals?

This depends on how you define "better". For instance, when is "global" necessary? When can a "local" work just as well?

Since the AVR CPU is a register-rich system, putting the variables in loop may well cause the compiler to go "Oh, I have enough registers to store this information. I don't need these variables in memory since they get thrown away straight after using them. I'll delete them and just use internal registers instead.".  Optimizations are great :)

If you are an ancient C programmer, then try functions with parameters "by reference". The compiler can do more optimizations with that. Passing a global variable by reference is almost the same for the compiler as using the global variable in the function, but with the parameter by reference it still does look good because the used variables are nicely declared as parameters. By the way, the dht22 is not accurate, try something better.

@Jot - it's cheap! And my project is not critical. Or is there something better in the same price bracket?

The humidity that the dht22 returns is not accurate, it is only an indication and can be used to check if the humidity goes up or down. When it measures 60%, the relative humidity can be between 40% and 80%. The good sensors with i2c are still 2% or 3% inaccurate. Those sensors are for example the bme280, bme680, htu21d, sht31-d, si7021. Those sensors are 3.3v and the arduino uno is 5. You might need level shifters for the i2c bus. For just the temperature, the ds18b20 is the best choice, good and cheap.

When you look at the hardware itself, there are no memory protections at all.  (at least at the low end - modern desktop machines might have some)  This means that at the hardware level, everything is global no matter how or where you declared it.  That said though, it's still useful to use the scope idea to keep from running over yourself (or your teammate(s)), and to give the compiler an opportunity to optimize, but that's really all it is.

No. If you have the choice, locals are usually better, because they
minimize the risk of name collision, and they help make the program
clearer by keeping the variable definition close to the place where it
is used. In your example, hum and temp should be locals, as there is
no good reason to make them globals.
However, sometimes you don't have the choice. If a variable is used in
both setup() and loop(), then it needs to be global. This is the
case of dht in your example.
Sometimes a variable is used in many functions. Even if you can make it
local, by passing it around through function parameters, doing so
doesn't make the program more readable. In that case you may also prefer
to keep it global.
Sometimes a variable that is used in only one function needs to be
statically allocated in order to preserve its value across calls to the
function. In this case the variable could be a static local. However,
since the static keyword is somewhat obscure for beginner programmers,
Arduino tutorials tend to use globals whenever static storage is needed.
You are not required to follow this practice, although you may want to
if you are writing for an audience of novices.
In any case, the take away of your first two links is not that you
should prefer globals: it's that sometimes there is a good reason for
making a variable global, and that's fine.

Thanks for all your answers, I've changed the code, and it's good to know I don't need to change my practices too much :) (Global variables were banned in all the development environments I worked in in the 1990s) So am I right to conclude that I only NEED to use a global if I refer to it in setup() and loop()? Everything else can be local and passed around?

@minisaurus: Yes, that's right. However, now that he ban is lifted, I suggest you try to avoid thinking of globals as evil. If you find yourself passing a variable around through many functions, consider making it global: does that hurt the program's readability? If the answer is “no”, then a global is probably a good choice.

I'm out of touch, but is the ban really lifted in professional environments with several developers, APIs, libraries and who knows how many files of source code? But I can see how globals maybe aren't a big problem in these single file small Arduino projects.

@minisaurus: I don't know on these environments. My answer is specifically for the kind of programs you write on smallish embedded devices.

The general rule of good practice is to minimize the scope of a variable to necessary minimum. Write the code to be readable and maintainable, don't do premature optimization.
The variables hum and temp should be defined only in loop(). The compiler can optimize it by putting them to global space or using MCU registers only, to avoid repeated creation on stack.

Not an answer, but I thought some of you may be interested in the C coding standards of some projects in the 1990s (based on the EDS standards, if I remember correctly).
A summary of the rules is:

No goto
No global variables
All functions (including main) to return an integer which is either SUCCESS or FAILURE
All variables declared at start of function
All variables declared on a separate line
No "in-line" initialising of variables
All variables initialised, usually to zero, including mallocs
No in-line if's
Probably more things that I can't remember

An example program:
#include <stdio.h>
#include <stdlib.h>

#define SUCCESS 0
#define FAILURE !SUCCESS

int log_error(char *msg) {
  int rv;

  rv = SUCCESS;

  fprintf(stderr, "%s\n", msg);

  return(rv);
}

int function2(void) {
  int rv;

  rv = SUCCESS;

  return(rv);
}

int function1(void) {
  int rv;
  int i;
  char *mem;

  rv = FAILURE;
  i = 0;
  mem = 0;

  if(NULL == (mem = malloc(400))) {
    log_error("Malloc error");
  } else {
    for(i=0; i<400; i++) {
      mem[i] = 0;
    }
    if(SUCCESS != (rv = function2())) {
      log_error("function2");
    } else {
      rv = SUCCESS;
      free(mem);
    }
  }
  return(rv);
}

int main(int argc, char **argv) {
  int rv;

  rv = FAILURE;

  if(SUCCESS != (rv = function1())) {
    log_error("function1 error");
  }

  return(rv);
}

Bit different to the way K&R wrote UNIX, and perhaps not too relevant to embedded? I'm not sure which I prefer, I guess both styles have their place depending on the makeup of a team :)

You very wisely pointed out that not all of these rules are universal. Just to provide an illustration, the Linux kernel coding style contradicts several of the above, including the bans on gotos (sec. 7) and global variables (sec. 4), having to always return a status code (sec. 16), and variable initialization within the declaration (example on sec. 7).


text:
About ATmega32 event system
From my reading on internet i found that the Event system allows peripherals to trigger each other without involving the CPU...does the event system is software or hardware?also does ATmega32 support it? also can any one give me a real application for event system?

Where did you read this? Can you provide a link?

@NickGammon https://www.microchip.com/design-centers/8-bit/peripherals/core-independent/event-system

The Atmega32 is not listed in the device list for the event system, that is on that site

@chrisl could you give me some example for event system?

Which Arduino are you using? This question might be better put to the AVR Freaks web site as it doesn't seem to directly involve any Arduino as such.

@NickGammon I don't use arduino..I use Atmega32

The 'old' ATmega 8 bit microcontrollers don't have an event system peripheral. The new "megaAVR 0 series" has an event system. Atmega 4809 on Arduino Uno WiFi Rev2 and on Nano Every is "megaAVR 0-series". The event system of the new ATmegas is similar to SAMD event system I know.
ARM MCUs for example SAMD by Atmel/Microchip used in Arduino Zero and MKR have an event system. Event system is a MCU peripheral. It enables direct communication between peripherals without the involvement of the CPU of the MCU.
The MCU peripherals are what makes the MCU a MCU. Examples of peripherals are GPIO pins, external interrupts, timers, SERCOM, watchdog...
To give you an example of use of the event system. To perform AC phase cutting with a Triac the Triac must be pulsed at right time after zero crossing. (It turns off self at next zero crossing.) To achieve this with MCU, the MCU must sense the input from the zero crossing detection circuit, then start timing the requested off time, then start a pulse to triac's gate and then stop the pulse.
It can be implemented with an external interrupt function for zero crossing, which starts a timer to generate a pulse on a wave output pin.
On ARM MCU it is possible to setup the event system to start the timer on external interrupt over an event, without an interrupt function. Then the CPU of the MCU is not involved in phase cutting after the initial configuration of the peripherals.
After setting up the zero crossing detector input pin for external interrupt without interrupt function and setting up the timer to execute one-shot pulse, the event system will re-trigger the timer on external interrupt.
a simple Arduino SAMD lib for a Triac/ZC module (in development):
#ifndef _TRIAC_LIB_
#define _TRIAC_LIB_

namespace Triac {

const unsigned long AC_WAVE_MICROS = 10000; // at 50 Hz
const int TIMER_PRESCALER = 8;
const unsigned long PULSE_PERIOD = ((F_CPU / 1000000) * 200) / TIMER_PRESCALER;

Tcc* TCC;

void syncTCC() {
  while (TCC->SYNCBUSY.reg & TCC_SYNCBUSY_MASK);
}

void zeroCrossing() {
}

void setup(byte zcPin, byte triacPin) {

  // setup the external interrupt
  attachInterrupt(zcPin, zeroCrossing, RISING);
  uint8_t ulExtInt = g_APinDescription[zcPin].ulExtInt;
  EIC->EVCTRL.reg |= (1 << ulExtInt);// enable event
  EIC->INTENCLR.reg = EIC_INTENCLR_EXTINT(1 << ulExtInt); // turn-off interrupt

  const PinDescription& pinDesc = g_APinDescription[triacPin]; // Arduino pin description
  TCC = (Tcc*) GetTC(pinDesc.ulPWMChannel);
  uint8_t tcChannel = GetTCChannelNumber(pinDesc.ulPWMChannel);

  // setup the pin as TCC wave out pin
  PORT->Group[pinDesc.ulPort].PINCFG[pinDesc.ulPin].bit.PMUXEN = 1;
  PORT->Group[pinDesc.ulPort].PMUX[pinDesc.ulPin >> 1].reg |= PORT_PMUX_PMUXE_F;

  // setup the timer

  REG_GCLK_CLKCTRL = (uint16_t) (GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK0 | GCLK_CLKCTRL_ID(GCM_TCC0_TCC1)); // assign clock
  while ( GCLK->STATUS.bit.SYNCBUSY == 1 );

  TCC->CTRLA.bit.SWRST = 1; // reset timer
  syncTCC();
  TCC->WAVE.reg |= TCC_WAVE_WAVEGEN_NPWM; // normal PWM as wave output mode
  syncTCC();
  TCC->CTRLBSET.reg = TCC_CTRLBSET_ONESHOT | TCC_CTRLBSET_DIR; //one shot and count down
  syncTCC();

  TCC->PER.reg = ((F_CPU / 1000000) * AC_WAVE_MICROS) / TIMER_PRESCALER; // initial value of period (triac off)
  syncTCC();
  TCC->CC[tcChannel].reg = PULSE_PERIOD; // pin on at compare match and off at 0 (timer counts down)
  syncTCC();

  TCC->EVCTRL.reg |= TCC_EVCTRL_TCEI0 | TCC_EVCTRL_EVACT0_RETRIGGER; // retrigger on event
  syncTCC();
  TCC->CTRLA.reg |= TCC_CTRLA_PRESCALER_DIV8 | TCC_CTRLA_ENABLE; // set prescaler and enable
  syncTCC();

  // event system
  PM->APBCMASK.reg |= PM_APBCMASK_EVSYS; // power it on
  GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID(EVSYS_GCLK_ID_0) | GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN(0); // assign a clock
  while (GCLK->STATUS.bit.SYNCBUSY);

  EVSYS->CTRL.bit.SWRST = 1; // reset
  while(EVSYS->CTRL.bit.SWRST);

  EVSYS->USER.reg = EVSYS_ID_USER_TCC0_EV_0 | EVSYS_USER_CHANNEL(1); // set user TCC0 event 0 on channel 0
  EVSYS->CHANNEL.reg = EVSYS_CHANNEL_CHANNEL(0) | EVSYS_CHANNEL_PATH_ASYNCHRONOUS | // channel 0 is async
      EVSYS_CHANNEL_EDGSEL_FALLING_EDGE | EVSYS_CHANNEL_EVGEN(EVSYS_ID_GEN_EIC_EXTINT_0 + ulExtInt); // source is ext.interrupt
  while (!EVSYS->CHSTATUS.bit.USRRDY0);
}

/*
 * r is from interval <0.0, 1.0>
 */
void setPeriod(float r) {
  unsigned long period = ((F_CPU / 1000000) * ((1.0 - r) * AC_WAVE_MICROS)) / TIMER_PRESCALER;
  TCC->PER.reg = period + PULSE_PERIOD;
  syncTCC();
}

}
#endif

other SAMD example

Thank you sir...your answer is very helpful...

The ATmega32 has a coupe of peripheral-to-peripheral communication
features that are in some way similar to the Event System:

You can use the analog comparator to trigger an input capture on
Timer 1.
You can use the analog comparator, external interrupt 0, Timer 0, or
Timer 1 to trigger a conversion on the ADC.

These are the only ones I know about. As you can see, it's a very
limited functionality. From what I read, the Event System looks like a
generalization of this idea. You have many peripherals that can trigger
events (event emitters), many that can be triggered by such events
(event receivers), and you can connect any event emitter to any event
receiver. You thus have much more flexibility than the very limited
peripheral-to-peripheral communication facilities provided by the
ATmega32.
The configuration of the event system (emitter to receiver connections)
is performed by your software. However, once the connection is
established, the peripheral-to-peripheral communication is entirely
hardware, and does not depend on the CPU.

Thank you sir....I am very thankful...


text:
How to parse data most efficiently coming through mqtt with ESP8266
I am writing a program that is currently set up like so:
Python script running on my computer.
Raspberry pi is the broker for the mqtt data transmission
An ESP8266 is programmed to listen to/subscribe to data coming through on a specific channel.
The data comes through with this format: "255,255,255" for example.
It is parsed on the "," saving the values to apply to the red green and blue channel of an led.
I can manually type colors to send from my python program and the led updates correctly. When I update the python script to send a stream of values that produce an effect of fading through the rainbow, that also works for the most part BUT, the data gets sent so quickly and it seems to get backed up. This causes the LED to continue running through the loop even after I stop the python program. The longer the program runs before I stop, the longer the led continues fading after stopping.
This is a problem because I was hoping to scale this up greatly to control many led strips throughout my house. I imagine I could slow down the rate at which I send values, I would need to find the sweet spot of how fast I could send values without them getting backup (because if I change the pattern I want the change to happen immediately, and to not need to wait for all the values of the previous pattern to complete) This gets harder with the more individual strips I try to control at once.
Is there a more efficient way to parse the incoming values?
callback() and splitAndSaveRGBValues() handle parsing the values
The esp8266 code is:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

#define CLIENT_NAME "ESP8266_1" // just a name to identify this client
WiFiClient wifiClient;
PubSubClient mqttClient("10.0.0.131", 1883, wifiClient);

//set rgb led pins
int pinGreen = 4;
int pinBlue = 14;
int pinRed = 12;

void setup()
{
  Serial.begin(9600);
  //set rgb led pins to output

  pinMode(pinRed, OUTPUT);
  pinMode(pinGreen, OUTPUT);
  pinMode(pinBlue, OUTPUT);
  digitalWrite(pinRed, HIGH);
  digitalWrite(pinGreen, HIGH);
  digitalWrite(pinBlue, HIGH);

  mqttClient.setCallback(callback);
  WiFi.begin("partyHouse", "whatsthepassword");
  connectToWiFiAndBroker();
}

void connectToWiFiAndBroker()
{
  Serial.print("\nConnecting to WIFI");
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(500);
  }
  Serial.println("Connected to WIFI!");

  Serial.println("Connecting to broker");
  while (!mqttClient.connect(CLIENT_NAME))
  {
    Serial.print(".");
    delay(500);
  }
  Serial.println("Connected to broker!");

  mqttClient.subscribe("InterestingTopics/#");
}

//savaing for use when sending data

//#define MILLISEC_DELAY_BETWEEN_PUBLISH 10000
//unsigned long lastTime = 0;
//unsigned long currentValue = 1;
//char msg[50];

void loop()
{
  if (!mqttClient.connected())
  {
    connectToWiFiAndBroker();
  }

  mqttClient.loop();
  //Savaing as a refernce for how to send data

  //  if(millis() - lastTime > MILLISEC_DELAY_BETWEEN_PUBLISH)
  //  {
  //    lastTime = millis();
  //    Serial.println("Publishing a new value");
  //    snprintf (msg, 75, "%ld", currentValue);
  //    Serial.println(currentValue);
  //    mqttClient.publish("ESP8266/CurrentValue", msg);
  //    currentValue++;
  //  }
}
int red;
int green;
int blue;

//the topic is the path based on the subscription
void callback(char* topic, byte* payload, unsigned int length)
{
  char colorCommand[length+1];
  for (int i = 0; i < length; i++)
  {
    colorCommand[i] = (char)payload[i];
  }
  colorCommand[length+1] = '\0';
  splitAndSaveRGBValues(colorCommand);
  updateRGBFromIncomingValues();
}
void splitAndSaveRGBValues(char *colorCommand) {
  char *color;
  color = strtok (colorCommand,",");
  red = atoi(color);
  int increment = 1;
  while (color != NULL)
  {
    color = strtok (NULL, ",");
    if (increment == 1) {
      green = atoi(color);
    } if (increment == 2) {
      blue = atoi(color);
    }
    increment ++;
  }
}

void updateRGBFromIncomingValues() {
  analogWrite(pinRed, red);
  analogWrite(pinGreen, green);
  analogWrite(pinBlue, blue);
}

I have considered changing the approach from streaming values constantly, to coding patterns that could be called from functions saved on each device, but I would need to upload need code (containing the additional patterns for use) to each device each time I think of a new pattern.
Current approach would allow patterns to be created on my computer  and the path used with the MQTT would control which chip to send values to.
The con of my current approach is that leds would only work if I was running the program on my computer to control them (Id like the leds to be able to run their previous pattern if freshly turned on).
I am completely open to suggestions on different ways I can attempt to accomplish my goals if my current approach is insufficient: many nodes/arduinos that have X number of led strips that could be controlled individually, or sync'd up. That would run the previous pattern if turned on, and could be controlled from a single interface

you need to identify the data bottleneck ... if you have to throttle the python script on your computer, then the bottleneck may be between the computer and the MQTT server ... until then, the post is not about the arduino

I thought the bottle neck was the parsing of the data, due to the symptoms from sending data quickly. Is that not right?


text:
How to execute commands over desired amount of time
I have a program that receives 4 commands on 4 channels to change the color of an LED using mqtt communication. Lets just focus on two of the channels, the time and the red.
I am sending a length of time that I would like to complete the color change by, and a new color value.
I have ran my test runs to calculate the amount of time it seems to take to update a single value. I calculate this by setting the intervalRed value to 0.01
with a duty cycle of 1024, commanding the led to go from its starting value to its ending value of fully on, by the interval value would be 10,240 ticks.
when I send that command, take the resulting execution time ( 287ms ) and calculate the time to update a single tick I get a value of 0.028027 ms to complete a single increment.
When I set the hardcoded tickTime to that value: 0.028027
and I send a color change from off to on/vice-versa with a requested completion time of 1000ms, the actual execution time varies.
the larger the requested execution time varies, causes a greater difference between the actual and requested time.
I ran many test trials with a set interval to gain a value for the length of time for a single tick but no matter when value I use, there are still discrepancies. I dont believe using a hardcoded value for the length of time for a single tick is the correct way to assure the color change will occur over a given time.
I am happy to provide the terminal output for any attempts to show the output of values used in my calculations if needed (But I believe I need a difference approach all together)
What is the best way to assure the color change completes in the requested amount of time?
Perhaps some calculation based on the amount of time passed rather then calculating a hardcoded value for the time of a single tick?
    #include <ESP8266WiFi.h>
#include <PubSubClient.h>

#define CLIENT_NAME "ESP8266_1" // just a name to identify this client
WiFiClient wifiClient;
PubSubClient mqttClient("10.0.0.131", 1883, wifiClient);

//set rgb led pins
int pinGreen = 4;
int pinBlue = 12;
int pinRed = 14;

float currentRed = 1024;
float currentGreen = 1024;
float currentBlue = 1024;

int nextRed = -1;
int nextGreen = -1;
int nextBlue = -1;

float intervalRed = -1;
float intervalGreen = -1;
float intervalBlue = -1;

//the float time was calculated by
//IntervalValue(set to 0.01)/Value Change (1024 when going from on to off) = 10,240 ticks
//ExecutionTime (beginning time - end time) /# of ticks = 0.0347643
// I seem to be getting varying execution times so I have tried values between 0.028 and 0.04
float tickTime = 0.028027;
int executionTime = 1;
int showTime = 1;
int beginningReceivedData;

void setup()
{
  Serial.begin(9600);
  //set rgb led pins to output

  pinMode(pinRed, OUTPUT);
  pinMode(pinGreen, OUTPUT);
  pinMode(pinBlue, OUTPUT);
  digitalWrite(pinRed, HIGH);
  digitalWrite(pinGreen, HIGH);
  digitalWrite(pinBlue, HIGH);

  mqttClient.setCallback(callback);
  WiFi.begin("partyHouse", "whatsthepassword");
  connectToWiFiAndBroker();
}

void connectToWiFiAndBroker()
{
  Serial.print("\nConnecting to WIFI");
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(".");
    delay(500);
  }
  Serial.println("Connected to WIFI!");

  Serial.println("Connecting to broker");
  while (!mqttClient.connect(CLIENT_NAME))
  {
    Serial.print(".");
    delay(500);
  }
  Serial.println("Connected to broker!");

  mqttClient.subscribe("InterestingTopics/#");
}

void loop()
{
  if (!mqttClient.connected()) {
    connectToWiFiAndBroker();
  }
  mqttClient.loop();

  updateColors();
}
//------------------------------------------------------------------------------------------------------------------------
//The CallBack for processing incoming data
//------------------------------------------------------------------------------------------------------------------------
//the topic is the path based on the subscription
void callback(char* topic, byte* payload, unsigned int length)
{
  //for tracking the time it takes to process the data, as well as the time it takes to complete updating the colors over the desired time
  beginningReceivedData = millis();
  char commandValue[length+1];
  for (int i = 0; i < length; i++)
  {
    commandValue[i] = (char)payload[i];
  }
  commandValue[length+1] = '\0';
  if (strcmp(topic, "InterestingTopics/time") == 0) {
    executionTime = atoi(commandValue);
  }
  if (strcmp(topic, "InterestingTopics/red") == 0) {
    showTime = 1;
    nextRed = atoi(commandValue);
    intervalRed = (nextRed - currentRed)/(executionTime/tickTime);
    //manual Interval value used for calculating the tickTime
    if (nextRed < currentRed) {
      intervalRed = -0.1;
    } else {
      intervalRed = 0.1;
    }

    Serial.print("next: ");
    Serial.print(nextRed);
    Serial.print(" Current: ");
    Serial.print(currentRed);
    Serial.print(" Interval: ");
    Serial.println(intervalRed, 10);

    Serial.print("time to process incoming single value (red): ");
    Serial.println(millis() - beginningReceivedData);
  }
  if (strcmp(topic, "InterestingTopics/green") == 0) {
    nextGreen = atoi(commandValue);
    intervalGreen = (nextGreen - currentGreen)/(executionTime/tickTime);
  }
  if (strcmp(topic, "InterestingTopics/blue") == 0) {
    nextBlue = atoi(commandValue);
    intervalBlue = (nextBlue - currentBlue)/(executionTime/tickTime);
  }
}

void updateColors() {
  //------------------------------------------------------------------------------------------------------------------------
  //Updating the Red
  //------------------------------------------------------------------------------------------------------------------------
  if (currentRed != nextRed && nextRed > -1) {
    currentRed = currentRed + intervalRed;
    //if value decreasing and it passes the next value, set values equal to prevent passing
    if (intervalRed < 0 && currentRed < nextRed) {
      currentRed = nextRed;
    }
    if (intervalRed > 0 && currentRed > nextRed) {
      currentRed = nextRed;
    }
    analogWrite(pinRed, (int)currentRed);
    //this else exists just to print the different in time from receiving the value to the time it took to update
  } else if (currentRed == nextRed && nextRed > -1 && showTime == 1) {
    //showTime set to zero to only print the time once
    showTime = 0;
    Serial.print("full color change has completed taking this much time: ");
    Serial.println(millis() - beginningReceivedData);
  }
  //------------------------------------------------------------------------------------------------------------------------
  if (currentGreen != nextGreen && nextGreen > -1) {
    currentGreen = currentGreen + intervalGreen;
    //if value decreasing and it passes the next value, set values equal to prevent passing
    if (intervalGreen < 0 && currentGreen < nextGreen) {
      currentGreen = nextGreen;
    }
    if (intervalGreen > 0 && currentGreen > nextGreen) {
      currentGreen = nextGreen;
    }
    analogWrite(pinGreen, (int)currentGreen);
  }
  if (currentBlue != nextBlue  && nextBlue > -1) {
    currentBlue = currentBlue + intervalBlue;
    //if value decreasing and it passes the next value, set values equal to prevent passing
    if (intervalBlue < 0 && currentBlue < nextBlue) {
      currentBlue = nextBlue;
    }
    if (intervalBlue > 0 && currentBlue > nextBlue) {
      currentBlue = nextBlue;
    }
    analogWrite(pinBlue, (int)currentBlue);
  }
}

Don't assume an update takes a fixed time and blast constant changes. Write code that calculates change/millisecond. Then record the starting millis() value when you begin a sequence, and each time through your loop, calculate float(millis()-startTime)/sequenceTime. That will give you the % of color change to apply now. Then use that percentage to calculate the interpolated color value.
That will give you an adaptive system that will set the color value to the approximate desired color for the current stage in your animation, regardless of how long each iteration the loop takes. If the loop lags for some reason, you will get more coarse changes between color values, but it will still track your desired pacing.

Note that you'll get more responsive code by adapting the above to use fixed-point math, since most Arduinos don't have hardware floating point support and their floating point is quite slow as a result. Mapping arbitrary floating point to fixed point is a little bit tricky, however. I'd suggest just writing it using floating point to start, and then optimizing it to fixed point math if it's too jumpy.

Thank you for the suggestion of fixed point math, I did see a significant difference in execution time when I went from double to float in my math. Not sure I understand how to convert to fixed but, time to do more research

Fixed point math uses a fixed "binary decimal place" and treats all values as between 0 and 1 (or 0 and 2, or 0 and 4, depending on where you put the assumed binary decimal place. If you scale all of your values to the range of your fixed-point, you can do integer math on the values, and then interpret the results as fixed-point values, and get much, MUCH faster performance. Figuring out the scaling and ranging takes some thought though.

Note that you could also try using short floating point values rather than float. That will be faster still, and easier to program than fixed point math. It makes your calculations pretty low precision however.


text:
Serial data not parsed correctly
The code I have works for the most part but when I send data via bluetooth received over software serial, too quickly, it is not parsed correctly.
I'm a bit stuck with what can be done to a void the incorrect formatting, since it works correctly if I send data slowly.
I could have a buffer to not send data more than once every set amount of time, but more responsiveness is preferred.
I am sending a string "center:255,0,255;"
it saves the command in a char array untill it sees the ":", then it saves the red in a  char array breaking on "," then same for the blue and green. when it  reaches the ";" it send the four arrays to print to a console. Later it the data will be used to light specific leds based on the command, but when I send data too quickly it gets parsed incorrectly, for example:
command: center
red:195
green:0
blue:255
command: center
red:208
green:0center:221
blue:0,255
command: center
red:246
green:0
blue:255

the 'green:0center:221' isnt correct, its either not seeing the "," or seeing the ";" too soon. Not sure how to avoid it.
#include <SoftwareSerial.h>
SoftwareSerial mySerial(6,7); // RX, TX

void setup() {
  Serial.begin(9600);
  mySerial.begin(57600); //required when using the hm-10 with an arduino nano
  mySerial.listen();
}

void loop() {
  while (mySerial.available () > 0) {
    processIncomingByte (mySerial.read ());
  }
}

const unsigned int MAX_INPUT = 50;

void processIncomingByte (const byte inByte) {
  static int parse_the_string = 0;
  static char command [MAX_INPUT];
  static char red [MAX_INPUT];
  static char green [MAX_INPUT];
  static char blue [MAX_INPUT];
  static unsigned int input_pos = 0;
  switch (parse_the_string) {
    case 0:
      switch (inByte) {
        case ':':
          command [input_pos] = 0;  // terminating null byte
          input_pos = 0;
          parse_the_string ++;
          break;
        default:
          if (input_pos < (MAX_INPUT - 1))
            command [input_pos++] = inByte;
          break;
      }
      break;
    case 1:
      switch (inByte) {
        case ',':   // end of text
          red [input_pos] = 0;  // terminating null byte
          input_pos = 0;
          parse_the_string ++;
          break;
       default:
          if (input_pos < (MAX_INPUT - 1))
            red [input_pos++] = inByte;
          break;
      }
      break;
    case 2:
      switch (inByte) {
        case ',':   // end of text
          green [input_pos] = 0;  // terminating null byte
          input_pos = 0;
          parse_the_string ++;
          break;
        default:
          if (input_pos < (MAX_INPUT - 1))
            green [input_pos++] = inByte;
          break;
      }
      break;
    case 3:
      switch (inByte) {
        case ';':   // end of text
          blue [input_pos] = 0;  // terminating null byte
          // terminator reached! process input_line here ...
          process_data (command, red, green, blue);
          input_pos = 0;
          parse_the_string = 0;
          break;
        case '\r':   // discard carriage return
          break;
        default:
          if (input_pos < (MAX_INPUT - 1))
            blue [input_pos++] = inByte;
          break;
      }  // end of switch
      break;
    default:
      break;
  }
}

void process_data (const char * command, const char * red, const char * green, const char * blue)
  {
  // for now just display it
  Serial.print ("command: ");
  Serial.println (command);
  Serial.print ("red:");
  Serial.println (red);
  Serial.print ("green:");
  Serial.println (green);
  Serial.print ("blue:");
  Serial.println (blue);
  }

Set higher baud rate for Serial and in Serial Monitor. It slows down the processing and the mySerial buffer overflows.

thats embarrassing, how simple >_< Thank you so much


text:
Alternative IDE for compiling and running arduino code?
I am not super experienced with c++ and I know that the syntax for C++ and the code written/compiled by the arduino IDE are slightly different.

I would like to be able to write code, compile it the same way the arduino IDE does, and run it, without uploading it to a board.

I dont need to test any code that interacts with any hardware. I simply want to be able to test basic syntax to make sure my concepts work before integrating with the full program.
I have written a few Arduino programs and I think the most complicated thing I've used were pointer functions, but I'd like to be able to test out code without needing to upload to a board for every change, while relying on Serial.print.
I have found alternatives that help with debugging and although that is helpful, I'd like to avoid the need to upload to a board every time I want to test changes for basic concepts

google arduino emulator

Thats a reasonable option, but i still would need to upload to a board, just an emulated one, I could just use a throwaway board I have and skip the hassle of dealing with the emulator. I appreciate the suggestion though

it is now unclear what you are asking ... you want to compile and run  Arduino code without any hardware, real or virtual ... what would the program do? ... it would have no way to interact with you

Use proteus with arduino library.

similar to using repl.it - I would like to be able to write code, that gets compiled and ran similar to what the arduino ide does. I am trying to test out different syntax for concepts I dont understand. I dont need to test working with hardware.

sorry if this is a stupid question. I was just hoping to reduce some steps in the process so I could learn the language quicker. I am a web developer but for some reason c++ is harder for me than id like to admit

"... syntax for C++ and the code written/compiled by the arduino IDE are slightly different." The Arduino IDE accepts standard C++. What it does differently, to assist learners, is to notice when you've referred to a library (that it know about!) and provides it even if you forgot to '#include" it, and forward declarations for functions, if you forgot those. If you write correct C++, it will compile in any standard C++ environment, including the Arduino IDE.

The difference of C++ and higher level (script) languages is that C++ is really near to the hardware. So running compilations on a PC, can be different from running it on a raspi or an Arduino.  And there are differences even then you don't use Hardware function directly. e.g an int on a Arduino can have another size then on a PC. And beside that, what is the purpose of learning Arduino C++ without Hardware functions? This language is designed for a MCU, that's pure hardware. You can learn how pointers work (and so on), by using plain C++.

Thank you for clarifying the difference, I suppose I can just use repl.it or even visual studio. I appreciate everyone's input!

You can use any C++ IDE you like, best when bundled with a compiler, for example Code::Blocks. Assuming you're using Windows: A combination of a decent editor like Notepad++ and some good compiler chain like MinGW will do, too. If you absolutely have to you could also use MS Visual Studio, I don't bother.
Then create standard console programs with this main():
void setup();
void loop();

int main()
{
    setup();
    for (;;)
    {
        loop();
    }
}

And append your hardware-less Arduino code.

Need to get rid of Serial.print at least :) :-)
But alas, with a debugger, you don't need that Serial.print at all.

One could write a simple Serial class with a minimal interface that prints to stdout or the native debugger channel.

PlatformIO is a plugin for Visual Studio Code that has support for many embedded device, including most Arduinos

The principle question seems to be about testing their code, in some capacity, without having to upload to an Arduino on each test.  It would probably help to say how PlatformIO enables this.


text:
How to use a precompiled library in a project with Arduino-IDE
I'm discovering the Arduino development and after quite some googling, I can't find an answer to the following question.
I'd like to distribute some code as mylib.h + precompiled mylib.o (this will be code ported from sources which I can't divulgate).
How is it possible to build a sketch using this precompiled mylib.o in the Arduino-IDE environment?
Do I simply have to put this mylib.o in a specific path and include the mylib.h in the sketch? If yes, which path? If no, what specific configuration steps do I have to follow?
Thanks in advance.

See https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification

library.properties file format
  [...]
  precompiled - (available from Arduino IDE 1.8.6/arduino-builder 1.4.0) (optional) set to true to allow the use of .a (archive) and .so (shared object) files. The .a/.so file must be located at src/{build.mcu} where {build.mcu} is the architecture name of the target the file was compiled for. Ex: cortex-m3 for the Arduino DUE. The static library should be linked as an ldflag.

So with the correct metadata and file layout the precompiled objects should be available.
You'll need to set the architectures property to indicate you're using esp8266 as your tag suggests.
More info on the library manager here https://github.com/arduino/Arduino/wiki/Library-Manager-FAQ including how to add to the public library list.


text:
Which is a better? GPRS SIM800L or GPRS SIM900?
I will implementate the GPRS technologity in my Arduino project, but before buy the module, I want to know which is a better. If GPRS SIM800L or GPRS SIM900? My needs are send JSON array through POST request.
Thanks and best regards.

Better from what perspective?

From perspective of a vehicle running. Which has more confiability/stability in sending data? Or why is better one than other? Thanks.

If it's for a car, maybe you have in mind "location of the car". In that case notice SIM800 dont have GPS. The location a SIM800 can give is the location of tower cell which can be far from the device. For sending data, saving them and so on I suggest to have a look at hologram.io SIM card. I use them for IoT project and that's pretty nice.

Hi Peter, I understand your comment about the GPS. Actualy in my project use a GPS module of UBLOX, the NEO-6M. Also thanks you for share me your hologram technology, it looks very interesting and useful. Best regards.

SIM900 is older type. SIM800L has FM build it and it uses same AT cmds as SIM900.
Also, they are in same quadband. I guess both will work just fine.


text:
SIM900/Arduino UNO R3 serial communication not working
For some reason I cannot establish serial connection between the two devices. The shield is connected to the network because my number can be called, but I cannot send it any commands via the serial.
I tried several ways to wire it up:
shield rx&tx (the ones that require female jumper) to 7 & 8 of arduino, declaring 7 & 8 in the serial.
shield pins 7 & 8 (they have (serial) as label) to 7 & 8 of arduino, declarting 7 & 8 in the serial.
shield rx&tx the little holes to 7 & 8 of arduino, declaring 7 & 8 in the serial.
Tried even different pins other than 7 & 8. None worked.
I'm powering the shield with 12v transformator that can provide up to 3Ah and the arduino is connected to laptop.
Any suggestions ?
Here's the code:
#include <SoftwareSerial.h>

//Create software serial object to communicate with SIM900
SoftwareSerial mySerial(7, 8); //SIM900 Tx & Rx is connected to Arduino #7 & #8

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

  //Begin serial communication with Arduino and SIM900
  mySerial.begin(9600);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT"); //Handshaking with SIM900
  updateSerial();

  mySerial.println("AT+CMGF=1"); // Configuring TEXT mode
  updateSerial();
  mySerial.println("AT+CMGS=\"+ZZxxxxxxxxxx\"");//change ZZ with country code and xxxxxxxxxxx with phone number to sms
  updateSerial();
  mySerial.print("Last Minute Engineers | lastminuteengineers.com"); //text content
  updateSerial();
  mySerial.write(26);
}

void loop()
{
}

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

And also, why are there so many RX/TX on the shield ? I see RXD/TXD and RX/TX.

What shield? A link to the product please.

https://www.amazon.com/SODIAL-Quad-Band-Modules-Development-Arduino/dp/B077953H5P there you go friend

To make everything work fine with this exact code and wiring from the lastminuteengineers, you need to change the jumper (black plastic piece) position in J11. it has to connect the pins D8(RX) and D7(TX), which are the pins at the top of the yellow plate, to the two pins in the middle of the yellow plate.

And also, why are there so many RX/TX on the shield ? I see RXD/TXD and RX/TX.

There aren't.  There is only one of each. They just have them in multiple convenient places.
J11 selects the pins to use on the shield. Make sure that is set to D7 and D8. You then use pins D7 and D8 on the shield. Normally that would be mounted directly onto an Arduino and you would just use those pins in your code.
However, if you want to attach it to something that doesn't have an Arduino UNO footprint you can solder wires to the TX/RX pins in the J10/J17 "UART" header. That ignores the J11 jumpers, which only pertain to using the Arduino UNO shield headers.
As to why you can't communicate, my guess is:

You have 9600 baud in your code:

mySerial.begin(9600);

However, on the Amazon product you linked to:

The factory default setting for the GPRS Shield UART is 19200 bps 8-N-1. (Can be changed using AT commands).

Using 19200 instead of 9600 should improve matters somewhat.

It doesn't improve anything. I've tried ALL the rates. If there was a mismatch, I'd at least see some squares or other strange shapes, but I don't see anything on the serial at all!

Does your shield have jumpers on J11? The picture shows them missing.

Compare it to the one shown in this tutorial: https://randomnerdtutorials.com/sim900-gsm-gprs-shield-arduino/

I pulled out all the wires so I   could take a picture.
https://imgur.com/a/jhpzyI7
That's how j11 and j12 look. I've tried plugging females to the pointy ones. The tutorial above has some jumper caps that I have no idea what they are.
edit: I took a closer look and itseems mine are not in the same position, but I never thought these could be plugged out and replugged in, lol. That's the first thing I am going to try after work. Could you explain about those ?

Looks like its set right. Just plug it direct into your arduino. No need for wires.

The middle pair of pins are  tx and rx. the outer pairs of pins connect to the headers. The jumpers just link the two.

No, mine is not the same as the toturial. I just made them just like in the tutorial, copied the code and STILL AT wont respond!
I've also tried stacking them together.

I still haven't resolved my issue. Any other help would be greatly appreciated!
I'm also up for a video talk if this is what it takes. I absolutely want to run this.


text:
Is there any arduino microphone that can record heart sound?
I'm currently undergoing a project where I record heart sound (mechanical response) and send it over bluetooth to an app.
However I'm finding it really hard to find an arduino microphone or just general microphone that can listen to heart sound.
Any guide would be highly appreciated.
Thanks

Sounds like you need three things: a microphone, and amplifier, and an A2DP sender. No need for anything Arduino there.

How is it possible to connect your microphone to A2DP sender? @Majenko

With an amplifier and wires.

it would be better to use an adruino heart beat module, about $2 on ebay...

First, there is no such thing as an Arduino microphone. There are boards specifically for Arduino which have a microphone, but also these are just generic 'electronic sound sensors'.
In principle any microphone would be a valid choice, but you have to test what are the requirements (distance to heart, environment noice). You also could use piezo sensors for vibration checking possibly.

Apologies for pointing such non existing device. What I'm looking for is a simple micrphone that can just detect heart sound and send over bluetooth. The environment: lets assume a classroom. And generally speaking the microphone should be attached close to your heart (as in your chest).

https://www.gearbest.com/development-boards/pp_75530.html?currency=GBP&vip=760250&gclid=CjwKCAjwhOvPBRBxEiwAx2nhLlhykouF1qt4QXcvS-roOTPu6pJfeAN4x3KBNUvmFtm34ohKPtwyEhoCQzQQAvD_BwE

Have a look at this link. Would you think this would be suitable?

I don't know if it is suitable ... I would say for 2 dollars, buy it and check. If not buy a better one. It could work, since the heart will be close. Btw, for bluetooth sending you need another device, completely unrelated to microphones. Do one step at a time. Hopefully you don't mean 'in your body' ... in that case many more requirements should be met.

Also for detecting heartbeats there might be a simpler device possible: same as what sport watches use: a 'special ?'  led on a wrist watch on the inside checking the wrist blood-vain.

As part of this research, I'm opting out from any consumer complete products. ANd yes your right I should take one step at a time. Currently Im so baffled by how we can send microphone data over bluetooth.

Sending microphone data over bluetooth or any other data does not make much difference. Unless you want to send a lot (like the 'waveform raw data'  of the microphone. But I don't have experience with bluetooth

Just a thought, depending on your requirements, you might want to consider the use of a small microphone inserted in the tube of a modified stethoscope, or some such.  Prior to their invention, doctors would use a short tube, with one end over the heart, and the other at the ear, thus making the sound readily audible.  I think that detecting the heart beat is the easy part.  Your problem will be sending data by bluetooth, how to then receive and then analyse to produce useful information.


text:
Can an accelerometer be used to detect heart sound?
I've recently come across accelerometer and how it can detect electrical mechanical response. I was wondering can it be used to detect heart sound? Lets say you attach the device close to your chest (where heat lies) and detect sounds and send it over bluetooth? LPMS-B2 OEM

An accelerometer detects motion (acceleration) of the physical device.
If you can convert the sound of the heart into physical vibration then the accelerometer can detect that vibration.
Converting the tiny amount of sound the heart produces into a large enough vibration for the accelerometer to detect would entail (realistically) using a microhone, amplifier, and speaker, with the accelerometer attached to the speaker cone.
So while theoretically yes, you can do it, practically why would you when you can just use the microphone and amplifier that you'd be using anyway. It's pointless.
So in reality: no, you can't.

Well said Majenko, I was thinking the same, and quite frankly, most people agree with your reasoning! Cheers!


text:
Updating firmware on Adafruit Huzzah ESP8266
tldr: I'm trying to re-flash a previously working Adafruit Huzzah ESP8266 breakout module to use the latest AT firmware. The re-flash doesn't seem to be working and I'm getting rather confused. This is the first time I've re-flashed one of these modules.
What I did:
I installed the latest version of esptool.py using pip, and downloaded the latest Espressif AT firmware from github. With the Huzzah on a breadboard I grounded GPIO0 and connected the serial port header to my PC using a FTDI cable. VC on the cable is 5v. The red power light lit. I then ran the following commands:

esptool.py --port COM4 --baud 115200 write_flash -fm dio -fs 32m
  0x00000 boot_v1.1.bin
esptool.py --port COM4 --baud 115200 write_flash -fm dio -fs 32m
  0x01000 user1.bin
esptool.py --port COM4 --baud 115200 write_flash -fm dio -fs 32m
  0x7C000 esp_init_data_default.bin
esptool.py --port COM4 --baud 115200 write_flash -fm dio -fs 32m
  0x7E000 blank.bin

Each upload seemed to complete ok, but I found that I couldn't upload the next until I pressed the reset button on the module first, otherwise I got the error:

A fatal error occurred: Failed to connect to Espressif device: Timed
  out waiting for packet header

This doesn't seem right to me.
After uploading all 4 components as above I disconnected GPIO0 and cycled the power on the module. I then tried connecting using putty at 115200 baud but I get no echo back from the module, and it doesn't respond to commands.
Observations:

The module previously worked and I could connect to it with putty.
If I reset it while connected to putty at 115200, I get a consistent pattern of garbage characters, so my guess is its alive but confused somehow.
I've tried connecting at various baud rates: 9600, 14400, 19200, 38400, 57600, as well as 115200. Same result.
I've found walkthroughs that show firmware like node.mcu being uploaded as a single binary. Should I be somehow merging the four bin files into one before uploading the the Huzzah?

What am I doing wrong here?

I'm confident that I've resolved this now. I'll leave the question here in case it is useful to anyone in the future.
The problem was they way I was downloading the individual bin files from the github repo, using right click -> Save As in Chrome. This downloads a file with the correct name, but it is actually the content of the file's html page, not the binary itself. Downloading the repo as a zip file, extracting the bin files,  and then uploading them to the Huzzah using a single command gave me a properly flashed device.
What happened was I noticed that esptool can upload multiple files in one go so, with the original bin files, I tried the command:

esptool.py --port COM4 --baud 115200 write_flash -fm dio -fs 32m 0x00000 boot_v1.1.bin 0x01000 user1.bin 0x7C000 esp_init_data_default.bin 0x7E000 blank.bin

and got the following error

esptool write_flash: error: argument  : Detected overlap at address: 0x1000 for file: user1.bin

Thats when I noticed that boot_v1.1.bin was way to big to fit in the space between 0x00000 and 0x01000. Examining it in notepad++ revealed that it was html.
A learning experience...

this just happened to me.. so annoying, never would have thought to open the file contents


text:
Inserting myself in serial communication
I am assigned on a project involving Arduino and Raspbery PI. I have plenty of experience with Arduino and 0 with Raspbery or Linux. Person working quit and there are some problems that need me to start debuging.
The project involves control of input and output by Arduino and a touch screen and SMS aplication in Raspbery. They comunicate with standard Serial port using USB.
I want to read that communication on my PC terminal. What would be the simplest way of inserting myself without modifying anything on Raspbery?

What kind of Arduino?

It is not clear who is doing the talking.  Only that communications is over a USB.  So, simplest answer is to use a USB bus protocol analyzer.  Most cost hundreds of dollars.

If you use an Arduino with no native USB support, you can tap the RX and TX pins, that are connected to the USB Serial chip (some Arduino boards have multiple Serial interfaces, so you need to connect to the right one)

@Majenko Arduino Mega2560

@st2000 Raspbery sends commands and expects a reply to them, and Arduino regularly (every 300ms) sends status report

@chrisl Can I just add another pair of wires to used RX and TX pins and read it without interruption?

As st2000 stated in the comments, tapping on USB is a complex task and certainly not the way to go.
Maybe there is a program for Raspbian, that pipes the Serial data to 2 programs simultaneously. (I don't know one and that would be off topic here)
So your best way would be to tap the Serial (UART) communication between the USB-Serial chip (which translates USB to real serial UART) and the Atmega2560 (the main chip on the Arduino Mega). Reading Serial (UART) is a completely passive action. You don't disturb the communication with it; only if you try to send something from your tapping device. The Mega uses the first Serial interface for communication over USB, meaning that you need to tap the pin 0 and 1 (marked with TX and RX).
Now about the tapping device: You have multiple possibilities here. You could use the RX pins of 2 other Arduinos or of 2 USB to UART adaptors. But I would suggest to directly buy a logic analyser. That is a small USB device, that let's you plot digital signals (like the serial communication) on your PC. I use one with the software Pulseview. It can also analyse the digital signal for different communication protocols, for example UART. With the logic analyser you would reach your goal of tapping the serial communication, but you would also have a very capable tool for your future Arduino projects (you can analyse all sorts of digial signals with it). They are rather cheap (I got one with little clamps to attach it to a circuit for about 15€).
In the end, it's up to you to decide, which way you want to go and what you want to buy.

You may be able to sniff the communication from the Raspberry Pi itself,
with no extra hardware. Assuming the program on the Pi can be configured
to use a serial port other than /dev/ttyACM0, a sniffing
program could create a pseudo-terminal pair, then forward data back and
forth between /dev/ttyACM0 and the master pseudo-terminal, while
logging everything. If you point your Pi application to the slave
pseudo-terminal, you have your man-in-the-middle logger:
Arduino --(/dev/ttyACM0)-- logger --(pseudo-tty)-- application

The interesting thing about a slave pseudo-terminal is that, as far as
the application is concerned, it behaves exactly like a regular serial
port.
There seem to be quite a few implementations if this idea. C.f. the
answers to these other stack exchange questions:

How can I monitor serial port traffic?
Sniff serial port on Linux

Just as an example, the README of
interceptty states:

interceptty is designed to sit between a serial port (or other
  terminal device, or program, or socket, or something connected to a
  file descriptor) and a program which is communicating with that
  device, recording everything that goes back and forth between the two.
  It does this by opening the real device, creating a pseudo-tty, then
  forwarding everything between the two, recording whatever it sees.

If all you want to do is monitor what is going on then you can take a pair of USB to UART adaptors and connect the RX pin of each to the Arduino - one to the RX pin to see what the Arduino is receiving, and one to the TX pin to see what the Arduino is transmitting.
You then have to open both COM ports in separate applications (unless you can find an application that will allow you to open both together) to see what each channel has going through it.