message:
How do i run multiple functions simultaneously on a LCD screen?

I have little to no experience in programming and i'm very slowly and gradually getting the hang of it. My next project is that i'm making a clock, and wanted to use multiple functions for the hour:minute:seconds instead of just using one for everything. But after reading some i came to the conclusion that the arduino can only run one function at a time. So my question is how can i make the illusion of multiple functions running simultaneously on a LCD screen.

My code:

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

    int lcd_key     = 0;
    int adc_key_in  = 0;
    #define btnRIGHT  0
    #define btnUP     144
    #define btnDOWN   329
    #define btnLEFT   504
    #define btnSELECT 741
    #define btnNONE   5

    int read_LCD_buttons()
    {
     adc_key_in = analogRead(0);

     if (adc_key_in > 1000) return btnNONE;
     if (adc_key_in < 50)   return btnRIGHT;
     if (adc_key_in < 195)  return btnUP;
     if (adc_key_in < 380)  return btnDOWN;
     if (adc_key_in < 555)  return btnLEFT;
     if (adc_key_in < 790)  return btnSELECT;
     return btnNONE;

    }
    unsigned long minInterval = 60000UL; // Interval for minutes in milliseconds
    unsigned long secInterval = 1000UL;  // Interval for seconds in milliseconds
    unsigned long prevMinMillis = 0UL;   // Holds the timestamp of the last time Minute() was called
    unsigned long prevSecMillis = 0UL;   // Holds the timestamp of the last time Second() was called

    void setup()
    {
     lcd.begin(16, 2);
    }

    void loop()
    {
      unsigned long currentMillis = millis();

      if (currentMillis - prevMinMillis > minInterval)
      {
        prevMinMillis = currentMillis;
        Minute();
      }

      if (currentMillis - prevSecMillis > secInterval)
      {
        prevSecMillis = currentMillis;
        Second();
      }

    }

    void Second(){
      int First_Digit = 0;
      int Second_Digit = 0;

      for(Second_Digit; Second_Digit<10; Second_Digit++){
        if(Second_Digit==10){
          First_Digit = First_Digit + 1;
          }

        lcd.setCursor(0, 0);
        lcd.print(First_Digit);
        lcd.setCursor(1, 0);
        lcd.print(Second_Digit);
        lcd.clear();

        if(First_Digit==5 && Second_Digit==9){
          First_Digit = First_Digit - 5;
          Second_Digit = Second_Digit -10;

          }
        if(Second_Digit==9){
          First_Digit = First_Digit + 1;
          Second_Digit = Second_Digit - 10;
          }

      }
    }
    void Minute(){
      int First_Digit = 0;
      int Second_Digit = 0;
      for(Second_Digit; Second_Digit<10; Second_Digit++){
        if(Second_Digit==10){
          First_Digit = First_Digit + 1;
          lcd.print(First_Digit);
          }

        lcd.setCursor(3, 0);
        lcd.print(First_Digit);
        lcd.setCursor(4, 0);
        lcd.print(Second_Digit);
        lcd.clear();

        if(First_Digit==5 && Second_Digit==9){
          First_Digit = First_Digit - 5;
          Second_Digit = Second_Digit -10;
          lcd.print(First_Digit);

          }
        if(Second_Digit==9){
          First_Digit = First_Digit + 1;
          lcd.print(First_Digit);
          Second_Digit = Second_Digit - 10;
          }

      }
    }

body:
Use the state machine model shown in [BlinkWithoutDelay][1]

    unsigned long minInterval = 60000UL; // Interval for minutes in milliseconds
    unsigned long secInterval = 1000UL;  // Interval for seconds in milliseconds
    unsigned long prevMinMillis = 0UL;   // Holds the timestamp of the last time Minute() was called
    unsigned long prevSecMillis = 0UL;   // Holds the timestamp of the last time Second() was called

    void setup()
    {
     lcd.begin(16, 2);
    }

    void loop()
    {
      unsigned long currentMillis = millis();

      if (currentMillis - prevMinMillis > minInterval)
      {
        prevMinMillis = currentMillis;
        Minute();
      }

      if (currentMillis - prevSecMillis > secInterval)
      {
        prevSecMillis = currentMillis;
        Second();
      }

    }

With this example, `Second()` is called only when the difference between "now" and the last time it was called is greater than `secInterval`. Likewise for `Minute()`.

[Note, the code above will not run as-is, but I assume you have initialized the LiquidCrystal library and assigned the pins as per your schematic.]

**EDIT BASED ON UPDATED CODE SAMPLE**

Issue 1:

In both your `Minute()` and `Second()` functions you have a sequence like:

    lcd.setCursor(0, 0);
    lcd.print(First_Digit);
    lcd.setCursor(1, 0);
    lcd.print(Second_Digit);
    lcd.clear();

After writing the characters, you immediately clear the LCD screen. Don't do this, it erases all the output on your LCD.

Issue 2:

At the start of the `Minute()` function, you have the following:

  int First_Digit = 0;
  int Second_Digit = 0;

This means the variables `First_Digit` and `Second_Digit` are initalized to zero every time the function is called. This means you won't get an increment of the value, it will start at zero every time you try to update the LCD. You can declare those variables as `static` so that the value remains the same between calls of the function. Static variables are automatically initialized to zero. Thus:

    static int First_Digit;
    static int Second_Digit;

and similarly in the `Second()` function.

You're correct that `digitalWrite()` is not needed in your function as it is described. `digitalWrite()` is for changing a physical pin on the Arduino to a `LOW` or `HIGH` value (that is, a 0V or 5V voltage.) In the Blink without Delay example, `ledPin` and `ledState` are just variables to hold the pin identifier for the blinking LED, and the current state (`LOW` or `HIGH`) of that pin. Again, not necessary for your code, as you have described it.

**SECOND UPDATE**

Having tackled the issue of how to run multiple functions "simultaneously", now move on to fixing the overly complicated code for writing the minute and second values to the LCD... I'm not sure why you put the `for` loop in the `Minute()` and `Second()` functions, but it's unnecessary.

You also are treating each digit way too complicated. If your value for the seconds counter is 0 to 59, why not keep track of it that way, and then display each digit as necessary:

    void Second() {
      static int second;

      second++;
      if (second>59) {
        second = 0;
      }
      lcd.setCursor(0, 0);
      lcd.print(second/10);   // Prints the 10s digit
                              // Note, lcd.print automatically moves to the next column
      lcd.print(second % 10); // Prints the remainder after dividing by 10
    }

    void Minute() {
      static int minute;

      minute++;
      if (minute>59) {
        minute = 0;
        // Probably want to increment an Hour counter here?
      }
      lcd.setCursor(3, 0);
      lcd.print(minute/10);   // Prints the 10s digit
                              // Note, lcd.print automatically moves to the next column
      lcd.print(minute % 10); // Prints the remainder after dividing by 10
    }

  [1]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay


sender: user

message:
The code fails to generate the values I want, when both trigger pins 2, 3 are high or low. Why?

<!-- language: lang-cpp -->

    /*aim of the program is to generate 2 different varying frequency from the
    same output which is controlled by 2 triggers*/
    void setup()
    {
     pinMode(2,INPUT); //setting the trigger pins 2,3
     pinMode(3,INPUT);
     pinMode(6,OUTPUT); //output pin
    }

    void loop()
    {
     if(digitalRead(2)==HIGH && digitalRead(3)==LOW) { //trigger conditions
            infra();
        }
     else if(digitalRead(2)==LOW && digitalRead(3)==HIGH) {
            red();
        }
     else if((digitalRead(2)==HIGH && digitalRead(3)==HIGH) || (digitalRead(2)==LOW && digitalRead(3)==LOW)) {
      Serial.println('help');
     }
    }

    void infra() //function varies sinosoidaly (working)
    {
     float f;

     for(f=16000; f<=20525; f+=4.525) {
      tone(6,f);
     }

     for(f=20525; f>=16000; f=f-4.525) {
      tone(6,f);
     }
    }

    void red() //function varies sinosoidaly (working)
    {
     float p;

     for(p=25000; p<=32071; p+=7.071) {
      tone(6,p);
     }

     for(p=32071; p>=25000; p=p-7.071) {
      tone(6,p);
     }
    }

sender: assistant

body:
To send anything to serial you need to initialize it first with:

<!-- language: lang-cpp -->

    void setup()
    {
        Serial.begin(115200);
        //other code
    }

And you are using wrong quotes for the string.
They should be double quotes `"` not single ones `'`.

Also you could simplify your code, if you removed the third `if`, since it's just checking the already known state at that point.

You should also read the button state only once, save them into a variable and then just compare those variables.

<!-- language: lang-cpp -->

    bool button1_state = digitalRead(2);
    bool button2_state = digitalRead(3);
    if (button1_state && !button2_state) {
        infra();
    }
    else if (!button1_state && button2_state) {
        red();
    }
    else {
        Serial.println("help");
    }


message:
How can Arduino's 8 bit Microcontrollers handle C++

I have just started getting into Arduino and c++ programming!

For all the talk on the internet about c++ being incompatible with 8-bit and even 16-bit microcontrollers, how is it that Arduino Microcontrollers can safely handle c++ code, in terms of the ram usage? Is it that Arduino's library does not contain or utilize features such as constructors or objects (of C++) that (I believe) are very ram-usage-intensive?

Cheers!

body:
It's a misconception that using constructors or C++ in general requires lots of RAM. Plus, to be clear, the AVR processors like the Micro and Uno have separate RAM and PROGMEM (program memory). So, code for functions does not, in itself, use RAM.

As an example, this small program for the Micro:

<!-- language: lang-c++ -->

    int main ()
      {
      }

That uses only 206 bytes of PROGMEM and 0 bytes of RAM (according to the IDE).

<!-- language: lang-none -->

    Sketch uses 206 bytes (0%) of program storage space. Maximum is 28,672 bytes.
    Global variables use 0 bytes (0%) of dynamic memory, leaving 2,560 bytes for local variables. Maximum is 2,560 bytes.

---

Adding in a class, with a constructor, and using that class, increases the memory a bit:

<!-- language: lang-c++ -->

    class foo
      {
      public:
      int bar;  // some class variable

      foo ()  // constructor
        {
        bar = 1;
        }
      };  // end of foo

    foo nick;  // a global variable
    int main ()
      {
      PORTD = nick.bar;
      }

That uses 2 bytes of RAM, and 278 bytes of PROGMEM. Hardly a lot.

<!-- language: lang-none -->

    Sketch uses 278 bytes (0%) of program storage space. Maximum is 28,672 bytes.
    Global variables use 2 bytes (0%) of dynamic memory, leaving 2,558 bytes for local variables. Maximum is 2,560 bytes.

---

Of course, the more things you do, the more RAM and PROGMEM it takes, however the compiler generates quite efficient code, and the linker strips out things that are not needed by your code.

---

> Is it that Arduino's library does not contain or utilize features such as constructors or objects (of C++) ...

A lot of libraries use classes and constructors (for example the Serial library, the Print class, and a lot of others). There is nothing inherently RAM-intensive about a constructor. It's just a function that does something, with an implied **this** pointer to the current instance of the class.

---

> do lambdas work? (from a comment)

Yes you can use lambdas:

    // array of function pointers
    void (*doActionsArray []) () =
     {
     [] { Serial.println (0); } ,
     [] { Serial.println (1); } ,
     [] { Serial.println (2); } ,
     [] { Serial.println (3); } ,
     [] { Serial.println (4); } ,
     };

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();

      doActionsArray [3] ();
      }  // end of setup

    void loop () { }

---

>  as long as you don't (extensively) use: the standard library, exceptions, templates ... (from a comment)

Templates can certainly simplify doing things like writing to, or reading from EEPROM and similar. For example:

    #include <Arduino.h>  // for type definitions
    #include <EEPROM.h>

    template <typename T> unsigned int EEPROM_writeAnything (int ee, const T& value)
    {
        const byte* p = (const byte*)&value;
        unsigned int i;
        for (i = 0; i < sizeof(value); i++)
         EEPROM.write(ee++, *p++);
        return i;
    }

    template <typename T> unsigned int EEPROM_readAnything (int ee, T& value)
    {
        byte* p = (byte*)&value;
        unsigned int i;
        for (i = 0; i < sizeof(value); i++)
         *p++ = EEPROM.read(ee++);
        return i;
    }

---

The standard library? There are implementations for the Arduino. We have to bear in mind that RAM is limited, however if you are going to do something *anyway* that involves linked lists, etc. then the Standard Template Library will probably do what you want as efficiently as you could if you coded it "by hand".

---

The bottom line is you need to be aware of what you are coding on. I have seen examples like this:

    float foo [1000];  // hold my readings

That blows the available RAM on a Uno straight away. Nothing to do with C++ per se.

---

The other thing to be aware of is some tricks you can usefully employ. One common one is to replace:

    Serial.println ("Program starting.");

With:

    Serial.println (F("Program starting."));

The first example causes the compiler to copy the string "Program starting." from PROGMEM into RAM, using some of your valuable RAM. The second example doesn't.


body:
The talk about C++ being incompatible with small MCUs implies that developers would use features it provides. In a *good* C++ project you're expected to use vectors and iterators instead of C arrays, throw exceptions instead of returning error codes, use lambda-functions, templates etc.

As long as you don't use those features, C++ memory consumption is manageable. The reason for this is simple: such limited C++ is just a syntactic sugar around C structures and function pointers.

The problems usually start when you write a class which is complex enough that its constructor can fail. Then you have a tough choice to make: start using exceptions and drastically increase memory consumption, or write classes which *pretend* they never fail to construct (which often results in a program which *pretends* to work).


body:
To write effective code with limited resources (RAM, program space, processing), you need to know enough about the processor to avoid features which it can't do.  In this case you're limited on all three counts, so you want to get away from anything complex and slow.

A good start is to avoid any features later than C++98, or at least C++03.  These features generally come at a cost.

Beyond that, particular issues are:-

 - Polymorphism.  All classes using virtual members have a [virtual method table][2], meaning every function call from that class needs to look up against a table.  On a small processor, this does slow down your function calls.  By all means use this where it's required, but if you have performance issues then you want your polymorphic classes to live at a higher level where the function calls happen less often.  Don't do this for low-level functions which get called thousands of times in a loop.
 - Exceptions.  Already covered by other answers.
 - Inline.  This is a *good* thing.  Where you can use this, it can claw back some processing cycles: not just from the function call itself; but also from further optimisation in the calling functions.

And of course general issues for embedded firmware on low-end micros:-

 - Dynamic memory allocation (new and delete, or most STL containers).  This is ***always*** an [anti-pattern][1] in embedded development.  It requires a chunk of RAM to be set aside for heap, and you always need to consider the possibility of allocation failing.  If you really need some kind of dynamic storage, consider whether a FIFO buffer or something better bounded would be appropriate.
 - Longer integers.
 - Integer multiply and divide.
 - Anything floating-point.
 - Anything using a lot of stack, whether this is lots of local variables, lots of function parameters, or over-enthusiastic function partitioning.

  [1]: https://en.wikipedia.org/wiki/Anti-pattern
  [2]: https://en.wikipedia.org/wiki/Virtual_method_table


body:
C++ is fine with Arduinos or other AVR based Systems.
I've been use it for quite a while in a home automation project.

The avr runtime does not support exceptions nor dynamic memory allocation, as has been stated. [you can provide an implementation  though][1].

There is much of C++ left to make use of. here are some examples

**Templates**

They are very useful because, e.g. they allow to move work from runtime to compiletime. I use template for a [replacement of the Arduino HAL functions DigitalWrite and others, without the runtime and code bloat][2].

compare this

    int main(void)
    {
            DDRB |= (1<<7);
            while(  (  ( PINB & (1<<6) ) !=(1<<6) ) )
                    ;
            while(1)
            {
                    _delay_ms(100);
                    PORTB |= (1<<7);
                    _delay_ms(100);
                    PORTB &= ~(1<<7);
            }
    }

to this

    int main(void)
    {
            IOPin<13> ledpin;
            IOPin<12> testpin;
            ledpin.SetDir(out);

            while(0 == testpin.State())
                    ;
            while(1)
            {
                    _delay_ms(100);
                    ledpin.SetHigh();
                    _delay_ms(100);
                    ledpin.SetLow();
            }
    }

The template based version is much more readable, and generates exactly the same assembler code. In the abovementioned linked article i explain the template and why this works.

**more on templates**

The following code uses the "curiously recurring template pattern" CRTP.
It is used to create a job class, which i use for a primitive scheduling

This template builds a chain of registrable items.

    template<class registered>
    struct Registered {
     static registered *registry;
     registered *chain;
     Registered() : chain(registry) {registry=static_cast<registered*>(this);}
    };

The job class applies the CRTP pattern. The constructor takes the actual callback where the work is done, and how often the job is done.

    class Job : public Registered<Job>
    {
     voidFuncPtr m_p;
     uint16_t m_periodic;
     uint32_t m_lastrun;
     uint16_t m_initialdelay;
     public:
     Job(voidFuncPtr p,uint16_t periode=0,uint16_t initialdelay=0):m_p(p),m_periodic(periode),m_lastrun(0),m_initialdelay(initialdelay)
     {

     }
     void run(uint32_t t_ms)
     {
      // tbd handle wraparound !!
      if(t_ms >= m_lastrun + m_periodic + m_initialdelay)
      {
       m_p();
       m_lastrun=t_ms;
       m_initialdelay=0;
      }
     }
    };

to use the job class i just create the instances for the jobs and pass lambdas or regular function pointers

    Job jserial([](){mqttrouteradapter.handleSerialMQTT();},10);
    Job jupdate(updatemc,1);
    Job jprint(printstate,500);

initialize the beginning of the chain of jobs

    template<> Job *Registered< Job >::registry = 0;

and inside main, run an infinite loop which calls the jobs.

    while (1)
     {
      for ( auto p = Job::registry; p; p=p->chain )
      p->run(millis());
     }

**Lambdas**

Nice to avoid a callback function

instead of

    void handleserial(void)
    {
     mqttrouteradapter.handleSerialMQTT();
    }
    Job jserial(handleserial,10);

i can write something like

    Job jserial([](){mqttrouteradapter.handleSerialMQTT();},10);

**the new meaning of auto**

Allows to deduce the type automagically. This function iterates over "something" passed the second parameter. It compiles, if the passed type provides the operations/attributes used in the function.
[And yes, **this** works only since c++17][3]

 void runRx(const char* data, auto msg_registry) {
  for (auto p = msg_registry; p; p = p->chain) {
   p->rx(data);
  }
 }

**using a recent compiler**

If you want to use a recent compiler (The Arduino IDE uses gcc4.9) you can [build your own gcc avr toolchain rather easily][4]. Then you have gcc 7.2 with c++17 support !
An other very good reason to use gcc 7.2 is, that they have improved the error messages by a great deal.

My conclusion is, there is no excuse using c, except you havn't yet learned c++. And use a new compiler !

  [1]: http://www.avrfreaks.net/forum/c-new-delete-operator-confusion
  [2]: https://haarer.github.io/c++/avr/templates/i/o/2018/01/21/c++-template-based-hardware-access-vs-classic-approach.html
  [3]: http://en.cppreference.com/w/cpp/language/auto
  [4]: https://github.com/haarer/toolchain68k


message:
arduino --verify / --upload not working (command line)

I installed Arduino IDE version 2.1 on Ubuntu via apt-get. Then I typed the following command in terminal to see if the Arduino IDE compiles my sketch.

     arduino --verify xx.ino

However, this command launches the GUI IDE. Is the CLI not supported anymore, or is the cause in apt-get the package?

body:
It's quite possible that this "version 2.1" doesn't support command line processes. I've never heard of an Arduino IDE version 2.1. My understanding is the version you get from `apt-get install arduino` is something like 2:1.0.5+dfsg2 so maybe you interpreted that as 2.1. That version is based on Arduino IDE 1.0.5, though apparently it has some non-standard modifications. Command line operation was [first added](https://github.com/arduino/Arduino/blob/master/build/shared/manpage.adoc#history) in Arduino IDE 1.5.2, though some additional functionalities were added in newer versions.

You should always install the official Arduino IDE downloaded from:
https://www.arduino.cc/en/Main/Software


message:
avrdude: stk500_recv(): programmer is not responding after all tries

After months of good use, both my boards Mega 2560 and Uno became unavailable for uploading sketch or burning bootloader.

    Sketch uses 444 bytes (1%) of program storage space. Maximum is 32256 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
    C:\[...]bin/avrdude -CC:[...]avrdude\6.3.0-arduino9/etc/avrdude.conf -v -patmega328p -cstk500v1 -PCOM5 -Uflash:w:C:\Users\GREGOR~1\AppData\Local\Temp\arduino_build_242793/BareMinimum.ino.hex:i

    avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:[...]\arduino\tools\avrdude\6.3.0-arduino9/etc/avrdude.conf"

             Using Port                    : COM5
             Using Programmer              : stk500v1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03

**Facts :**

 - v1.6.20 of the boards
 - v1.8.5 of the IDE
 - Windows 8.1 64bits
 - Programmer: "AVR ISP"
 - Drivers are fine (the boards are well recognized)
 - Serial monitor works
 - I'm trying to upload the "Bare minimum" exemple sketch
 - Nothing in pin 0 and 1, nothing at all is plugged actually
 - Get Board info:
 - Uno : VID 2A03
 - Mega2560 : VID 2A03
 - From instructions [here][1], every instruction is "echoed back"

**What i tried :**

 - https://forum.arduino.cc/index.php?topic=385160.0
 - https://arduino.stackexchange.com/questions/22191/avrdude-stk500-recv-programmer-is-not-responding
 - https://zestedesavoir.com/forums/sujet/5676/probleme-televersement-arduino
 - All other programmers
 - A few old versions of boards
 - Resetting the boards a few times, during upload, before, after...

Nothing works. If you have any idea.....

Thank you all !

  [1]: https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board

body:
It eventually worked by using **upload** / ctrl+U (what I *didn't try*... smh) instead of  **upload using programmer** / ctrl+shift+U.

So i know now where it comes from, though I don't know what's wrong with AVR ISP.


message:
Arduino Burn the code programmatically

Is it possible to burn arduino code programmatically?

I was thinking of one way and that is to download hex file from my online server. Store contents of the hex file in a string, and write that string to arduino flash, restart arduino and it should run new code in flash.

Can this be done? If not than please suggest me any other way to burn the code using C++ instructions.

body:
First, the Arduino Uno has 32 KB of flash, but only 1 KB of RAM. So, to be able to store the new program in a string means your new program can only be, at most, 1kb.

Secondly, only the bootloader can write to flash. So you could write a new bootloader that downloads the new program (in parts) and writes it to the flash. You would however need quite a big bootloader, leaving less space for actual code. Also the main program still needs to access the server to see if it needs to "reboot" so the bootloader can run the update process.

An example of an OTA bootloader can be found at https://www.rotwang.co.uk/projects/bootloader.html which might be a good starting point. Similar idea https://ncrmnt.org/2014/02/27/rf24boot-a-universal-over-the-air-bootloader-for-all-those-ucs/

Another option is to write the new firmware to an external EEPROM. Then your modified bootloader only has to read the new firmware from EEPROM, making it a lot simpler and smaller. There is some useful info in the question https://arduino.stackexchange.com/questions/11694/ota-updates-for-arduino-using-nrf24l01

MySensors.org already made such a bootloader: https://www.mysensors.org/about/bootloader

I know there exists another bootloader that does just that, but I can't seem to find it.


message:
Arduino Uno R3 to Wemos D1 R2 project migration - Pinout problems

So i've chosen to purchase a Wemos D1 R2 board in order that my old Arduino Uno R3 projects can get some new IoT features. However, even if my code is working in Uno perfectly, i want to test it using D1 before adding features. My problem is that, even if i have found tables showing differences between the 2 boards' pinouts, i cannot understand the correspondence between the pinouts.

So i am giving you the table below. Let's say i want to define echo and trigger pins for a sensor in my code. For example:

    #define TRIGGER_PIN 4
    #define ECHO_PIN 3

That would be pins D3 and D4 at my Uno. But i cannot understand which those pins would be in Wemos D1 R2. Also, my two boards can be seen below for comparison

[![enter image description here][1]][1]

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

  [1]: https://i.stack.imgur.com/ELW7g.jpg
  [2]: https://i.stack.imgur.com/9Gwbj.jpg

body:
The tricky thing with the WeMos boards is the pin notation is different from other Arduino boards.

Sometimes you will see the digital pins on Arduino boards referenced with the D*n* notation. For example: "Connect the HC-SR04's Trig pin to D4 on the Uno". In fact some boards such as the Nano even use the D*n* pin notation on their silkscreen. This is just a way of further differentiating the pins from the A*n* pins. You will only refer to that pin by the number 4 in your code.

The WeMos boards are different. You actually need to use `D3` and `D4` in your code to control the pins marked D3 and D4 on the silkscreen:

<!-- language-all: lang-cpp -->

    #define TRIGGER_PIN D4
    #define ECHO_PIN D3

We can take a peek at the source code of the [ESP8266 core for Arduino](https://github.com/esp8266/Arduino/) to see why:
https://github.com/esp8266/Arduino/blob/2.4.0/variants/d1_mini/pins_arduino.h#L40-L50

    static const uint8_t D0   = 16;
    static const uint8_t D1   = 5;
    static const uint8_t D2   = 4;
    static const uint8_t D3   = 0;
    static const uint8_t D4   = 2;
    static const uint8_t D5   = 14;
    static const uint8_t D6   = 12;
    static const uint8_t D7   = 13;
    static const uint8_t D8   = 15;
    static const uint8_t RX   = 3;
    static const uint8_t TX = 1;

Now you can see that if you use your original code:

    #define TRIGGER_PIN 4
    #define ECHO_PIN 3

That would actually be referring to the pins marked D2 and RX on the WeMos D1 R2!


message:
Does the tone() generates unwanted signal?

I was trying to use the tone function for another project but I found that it also generates an undesired frequency (not the harmonics above of square wave it generates) but a lower frq square wave. Is this normal or somethings wrong with my implementation?
the code is pretty simple:

    void setup()
    {
        pinMode(7,OUTPUT); //set the pin as output
        tone(7,10000); //start a 10KHz tone
        while(true); //stay here
    }

    void loop()
    { }

hardware was an Uno also tried different pins above but same results. first I tried a 470R and an 8R speaker. then guess maybe the inductance, or something else causing it so I used a piezo buzzer as seen below:

    Pin(x)--->10KR--->piezo--->GND

however it was the same. I measured the lower frequency as 19.55Hz for a tone(10000) and 39.05Hz for tone(40000); both are pretty annoying.
what causes this and whats the workaround?

body:
Did you measure it with good equipment? How much dB is the lower frequency? Can you show a spectrum plot?

It could be the software pin toggle. The tone selects a hardware timer, which is used to generate an interrupt. The output pin is toggled in that interrupt. It is in the file [Tone.cpp][1]. That interrupt could be delayed by a timer0 interrupt (for millis).
The timer0 runs at 16MHz/(64*256). With those numbers I can not get to the interference frequency that you mentioned.
You could try to use the output of a hardware timer. For example the [toneAC library][2] generates a tone at pin 9 and 10. That is as steady as the 16 MHz crystal (very steady).

It could be the equipment that you use to test.

It could be the speaker. Some speakers generate other tones. I had a ultrasound speaker which I could hear squeeking at a much lower frequency. After a search on the internet, I found that such a speaker is known to create lower frequency whistling noises.

It could be the 5V voltage is changed somehow by the circuit.

  [1]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/Tone.cpp
  [2]: https://bitbucket.org/teckel12/arduino-toneac/wiki/Home


body:
I could reproduce the problem with the posted code. This will be caused by the fact that the tone library uses interrupts and has to manually toggle pins, which will always have a bit of jitter. You are better off setting up a hardware timer to generate the tones, this does not require interrupts.

For example:

    #include <TonePlayer.h>

    TonePlayer tone1 (TCCR1A, TCCR1B, OCR1AH, OCR1AL, TCNT1H, TCNT1L);  // pin D9 (Uno), D11 (Mega)

    void setup()
      {
      pinMode (9, OUTPUT);  // output pin is fixed (OC1A)

      tone1.tone (10000);  // 10 kHz
      }

    void loop() { }

This uses a fairly small library I wrote, which you can download from <http://www.gammon.com.au/Arduino/TonePlayer.zip>

---

# Library code

If you don't want to trust some zip file from a random web site, here is TonePlayer.h:

    /*
     Play tones with hardware timers
     Author: Nick Gammon
     Date:   1 April 2013
    */

    #include <Arduino.h>

    class TonePlayer
      {
      // addresses of output ports - NULL if not applicable
      volatile byte * const timerRegA_;
      volatile byte * const timerRegB_;
      volatile byte * const timerOCRH_;
      volatile byte * const timerOCRL_;
      volatile byte * const timerTCNTH_;
      volatile byte * const timerTCNTL_;

      public:
        // constructor
        TonePlayer (
              // ports
              volatile byte & timerRegA,
              volatile byte & timerRegB,
              volatile byte & timerOCRH,
              volatile byte & timerOCRL,
              volatile byte & timerTCNTH,
              volatile byte & timerTCNTL)
           :
             timerRegA_  (&timerRegA),
             timerRegB_  (&timerRegB),
             timerOCRH_  (&timerOCRH),
             timerOCRL_  (&timerOCRL),
             timerTCNTH_ (&timerTCNTH),
             timerTCNTL_ (&timerTCNTH)
      { }

        void tone (const unsigned int Hz);
        void noTone ();

      };  // end of TonePlayer

    /*

     PERMISSION TO DISTRIBUTE

     Permission is hereby granted, free of charge, to any person obtaining a copy of this software
     and associated documentation files (the "Software"), to deal in the Software without restriction,
     including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
     and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
     subject to the following conditions:

     The above copyright notice and this permission notice shall be included in
     all copies or substantial portions of the Software.

     LIMITATION OF LIABILITY

     The software is provided "as is", without warranty of any kind, express or implied,
     including but not limited to the warranties of merchantability, fitness for a particular
     purpose and noninfringement. In no event shall the authors or copyright holders be liable
     for any claim, damages or other liability, whether in an action of contract,
     tort or otherwise, arising from, out of or in connection with the software
     or the use or other dealings in the software.

     */

And here is TonePlayer.cpp:

    /*
     Play tones with hardware timers
     Author: Nick Gammon
     Date:   1 April 2013
     */

    #include <TonePlayer.h>

    void TonePlayer::tone (const unsigned int Hz)
    {
      // it takes two toggles for one "cycle"
      unsigned long ocr = F_CPU / Hz / 2;
      byte prescaler = _BV (CS10);  // start with prescaler of 1  (bits are the same for all timers)

      // too large? prescale it
      if (ocr > 0xFFFF)
        {
        prescaler |= _BV (CS11);    // now prescaler of 64
        ocr /= 64;
        }

      // stop timer
      *timerRegA_ = 0;
      *timerRegB_ = 0;

      // reset counter
      *timerTCNTH_ = 0;
      *timerTCNTL_ = 0;

      // what to count up to
      *timerOCRH_ = highByte (ocr);
      *timerOCRL_ = lowByte (ocr);

      *timerRegA_ = _BV (COM1A0);             // toggle output pin
      *timerRegB_ = _BV (WGM12) | prescaler;  // CTC
      }  // end of TonePlayer::tone

    void TonePlayer::noTone ()
      {
      // stop timer
      *timerRegA_ = 0;
      *timerRegB_ = 0;
      } // end of TonePlayer::noTone

    /*
     PERMISSION TO DISTRIBUTE

     Permission is hereby granted, free of charge, to any person obtaining a copy of this software
     and associated documentation files (the "Software"), to deal in the Software without restriction,
     including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
     and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
     subject to the following conditions:

     The above copyright notice and this permission notice shall be included in
     all copies or substantial portions of the Software.

     LIMITATION OF LIABILITY

     The software is provided "as is", without warranty of any kind, express or implied,
     including but not limited to the warranties of merchantability, fitness for a particular
     purpose and noninfringement. In no event shall the authors or copyright holders be liable
     for any claim, damages or other liability, whether in an action of contract,
     tort or otherwise, arising from, out of or in connection with the software
     or the use or other dealings in the software.

     Example of use:

     #include <TonePlayer.h>

     ...

     TonePlayer tone1 (TCCR1A, TCCR1B, OCR1AH, OCR1AL, TCNT1H, TCNT1L);  // pin D9 (Uno), D11 (Mega)

     or, on the Mega 2560:

     TonePlayer tone3 (TCCR3A, TCCR3B, OCR3AH, OCR3AL, TCNT3H, TCNT3L);  // pin D5
     TonePlayer tone4 (TCCR4A, TCCR4B, OCR4AH, OCR4AL, TCNT4H, TCNT4L);  // pin D6
     TonePlayer tone5 (TCCR5A, TCCR5B, OCR5AH, OCR5AL, TCNT5H, TCNT5L);  // pin D46

     ...

     pinMode (9, OUTPUT);  // D9 on Uno, D11 on Mega 2560
     tone1.tone (440);     // play 440 Hz
     delay (500);          // wait half a second
     tone1.noTone ();      // stop playing

     or, on the Mega 2560:

     pinMode (46, OUTPUT);
     tone5.tone (440);

    */

Just put those two files inside a folder "TonePlayer" inside the `libraries` folder inside your sketches folder, and it should all work.

The library is written for the **16-bit timers**, and supports Timer 1 on the Atmega328, and Timers 1, 3, 4, 5 on the Atmega2560. Comments inside the library show how to set up the other timers.


message:
Powering an Arduino Mini Pro using a CR2032 battery as a remote control

I'm looking into making my own remote control using an Arduino Mini Pro and some RF transceivers. The receiving end won't be a problem, but the remote will. I want to make it as small as possible and consume as little energy as possible.

Is it possible to turn on the Arduino Mini Pro at the push of a button, while also using that same button to trigger a piece of code? That way I can cut the power when it's not being pressed.

I will make sure to code it, so I have to hold the button down for 1-1.5 seconds, so it has time to "boot up" and send the RF signal, but should power off immediately when I let go of the button.

What kind of power should I expect from a single CR2032 battery? I have a couple of NRF24L01 RF transceivers laying around together with an Arduino Mini Pro.

If we assume this, while looking at [this sheet](http://data.energizer.com/pdfs/cr2032.pdf):

    NRF24L01: 10 mA per second (low-ball)
    ATmega328P: 5 mA per second (low-ball)
    CR2032: 0.19 mA @ 2V = 2100+ hours

Even if we just say 600 hours and it takes 2 seconds to turn something on, I should be able to run it  `600H*60M*60S = 2.160.000 seconds = 1.080.000 times`. If my calculation isn't completely wrong, it means I could literally turn it on a million times in the worst case scenario.

I hope that calculation is wrong, because that seems crazy.

EDIT: I could desolder the LED and regular as well, if that won't damage it too much. Just to consume power. I've read I can basically run it for free then.

body:
You should take a look at [ATmega328P datasheet][1]

> On page 2, it says: Six Sleep Modes: Idle, ADC Noise Reduction, Power-save, Power-down, Standby, and Extended Standby

These are the modes which can be used to put Arduino Pro Mini in stand-by. You can search for them at datasheet and choose the only that better applies to you. To learn more about sleep mode and other methods to save battery, you can take a look at this source: [Arduino Low Power - How To Run ATmega328P For a Year On Coin Cell Battery ][2]

On the datasheet of battery, you should pay attention at its charge:

> Typical Capacity: 240 mAh (to 2.0 volts)

This means that from 3 to 2 Volts, it relases 240 mAh. This is the charge you can expect to use. Using the consumptions rates you posted above

    NRF24L01: 10 mA per second (low-ball)
    ATmega328P: 5 mA per second (low-ball)
    CR2032: 240 mAh
    Time: 240mAh/(10mA + 5mA) = 16 hours

Which is not so much. To increase this autonomy, the link I posted above is quite useful because it will show you alternatives like removing the voltage regulator that will reduce drastically your consumption. Now, if you feel _really_ adventurous, you may take a look at how to underclock your board: [Arduino pro mini @ 1MHz - 1.8V][3]. This is a very efficient way to save power where clock frequency is not a must.

---------------------
**EDIT after comments:**

The 16 hours were computed using 5mA for the Arduino (which is a value for power consumption that can be expected on active mode) and 10mA for the NRF24L01. You have to estimate a sleep mode consumption for both and a percentage of time in sleep mode if you want to estimate an autonomy. At the link I sent you about sleep mode there are some tables with power consumption in different configurations.

ATmega328P can run with a minumum of 1.8 Volts, while nRF24L01+ can while with a minimum of 1.9V - see [datasheet][4]. So probably you are going to have a little bit more than 240mAh to work with. Your battery won't have 3v all the time. It is going to start with 3V (maybe a litte bit more) and gradually reduces it voltage as the charge is provided to the circuit. Once the voltage goes bellow 1.9V, nRF24L01+ won't be guaranteed to work properly.

Definitely, to sleep the Pro Mini, just waking it up when using, is the right way to design this circuit. According to [this][2] reference I posted above, power consumption for Arduino should be 0.90 mA. At the item 5.1 of [nRF24L01+ datasheet][4], it is described that it consumes 0.32mA at standby mode II. If you sleep the Pro Mini for, let's say, 90% of the time, without removing leds or voltage regulators, you can estimate that

    t = 240mAh * (0.1/(5mA+10mA) + (0.9/(0.9mA+0.32mA)) = 178.65 hours

If you use strategies to reduce Arduino power consumption, like the ones I send you above, you can increase this time. You will also save power if you change nRF24L01+ from standby mode 2 to standby mode 1. Check the database to see which one fit your needs.

  [1]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Summary.pdf
  [2]: http://www.home-automation-community.com/arduino-low-power-how-to-run-atmega328p-for-a-year-on-coin-cell-battery/
  [3]: https://www.iot-experiments.com/arduino-pro-mini-1mhz-1-8v/
  [4]: https://www.sparkfun.com/datasheets/Components/SMD/nRF24L01Pluss_Preliminary_Product_Specification_v1_0.pdf


body:
If you have a single button, it is useless to use the button to trigger the piece of code. The fact that you are powered on means that the button is pressed.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/m09ZP.png)

<!-- End schematic -->

Of course you need a 3.3V Arduino PRO Mini...

If you have multiple buttons, you can have different circuits to detect this.

**Solution 1**

Use a set of diodes to power the board, then another to detect the digital pins.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/y5b5m.png)

<!-- End schematic -->

The second set of diodes is needed because you should not show to the atmega pins a voltage greater than Vcc+0.5V. Since a pull-down resistor is needed, if you want you can replace the second set of diodes with 2k2 resistors.

**Solution 2**

Again use a set of diodes to power the board, but then decode the value through an analog reading

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/aqSOO.png)

<!-- End schematic -->

You will need to experiment a bit to figure out the thresholds. For instance, with the values I wrote, you can expect to read from the ADC a value around 1000 for the button 1, a value around 600 for the button 2, and 300 for the button 3; for this reason, you write

    int buttonRawValue = analogRead(A1);
    if (buttonRawValue > 800) {
        // Button 1 was pressed
    }
    else if (buttonRawValue > 450) {
        // Button 2 was pressed
    }
    else {
        // Button 3 was pressed
    }

This will require some tuning, but I think it can work.

**Solution 3**

You can power the board through a transistor (I usually prefer small MOSFETs)

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/oC3Gj.png)

<!-- End schematic -->

You will need to find a MOS with a very low Vgs-th, sinceit should fully turn on with 1.5V. This solution has the advantage of not wasting the small voltage you have (while the other ones waste around 0.3V for Schottky diodes and 0.6V for PN diodes).

Personally I'd go with solution 3, since it is also easy to let the atmega control the power (simply attach one of the digital outputs to the cathodes of the diodes, and the ATMEGA will be able to force power on until it has finished the operations).

As a side note, I would recommend you not to use a pre-made board, but use a bare ATMEGA328P in this project. You can experiment with another arduino board, but then use the arduino board to flash a bare ATMEGA; you will get rid of all the useless things. You can avoid using a crystal and a voltage regulator, so your circuit will consist only of the components I used in the schematics and a 100nF capacitor between the VCC and GND pins of the microcontroller.

And... Don't flash a bootloader. Use another arduino board to flash the microcontroller, not a serial peripheral. This is because the bootloader is useful, but at boot it wastes some seconds (and you need to be as quick as possible)


message:
LCD Clock Millis Code Issue

I am trying to create a clock on an LCD when I upload the code below, all it displays is a very rapidly flashing 0:00 PM. Please help. This is my first time using Millis.

    #include <LiquidCrystal.h>   //includes LCD display library in sketch
    LiquidCrystal lcd(27,26,25,24,23,22);   //determines pins of the LCD display
    int seconds = 0;    //generates integer storing seconds
    int minutes = 0;    //generates integer storing and showing minutes
    int hours = 12;      //generates integer storing hours in 24 hour mode
    int displayHours;      //generates integer displaying hours in 12 hour mode
    unsigned long previousMillis = 0;   //creates a variable to store the amount of milliseconds since last update
    const long interval = 1000;    //generates integer to find 1 second interval

    void setup()
    {
      lcd.begin(16,2);  //determines size of the LCD display
    }

    void loop()   //runs code repeatedly
    {
      updateSeconds();   //runs the updateSeconds function
      clockShown();   //runs the clockShown function
      clockConversion();    //runs the clockConversion function
    }

    void updateSeconds()   //check to see if it's time to update the seconds integer
    {
      unsigned long currentMillis = millis();  //generates the number of milliseconds program has been running
      if (currentMillis - previousMillis >= interval)
        {
          previousMillis = currentMillis; //updates the last time seconds was updated
          seconds = seconds ++;   //adds a second to the counter
       }
    }

    void clockShown()   //displays the time on an LCD display
    {
      lcd.clear();   //resets screen on LCD
      lcd.setCursor(0,0);    //sets the place to start writing at the top left corner of the LCD
      lcd.print(displayHours);  //displays hours
      lcd.print(":");   //displays colon
      if(minutes <= 9)  //if the minute is 1 digit
      {
        lcd.print("0"); //displays 0
      }
      lcd.print(minutes);  //displays minutes
      if(hours < 12)lcd.print(" AM");  //displays AM in the morning
      if(hours >= 12)lcd.print(" PM");   //displays PM at night
    }

    void clockConversion()  //runs math to convert seconds minutes and hours
    {
      if(seconds == 60) //when seconds is 60
      {
        seconds = 0;  //set seconds back to 0
        minutes = minutes ++;  //and add a minute
      }
      if(minutes == 60) //when minutes is 60
      {
        minutes = 0; //set minutes back to 0
        displayHours = displayHours ++; //and add an hour
        hours = hours ++; //and keep track of AM PM
      }
      if(displayHours == 13)  //if the hour being displayed is 13
      {
        displayHours = 1; //make it 1 instead
      }
    }

body:
**Problem 1**

    seconds = seconds ++;   //adds a second to the counter

This command grabs the value of `seconds`, increments the value of `seconds`, and then assigns the previously grabbed value to `seconds`. Or rather, it does nothing to change the value of `seconds`.

This mistake is repeated for `minutes`, `hours`, and `displayHours` in the `clockConversion()` function.

*Instead*

    seconds++;

That was the main problem. The other problems described below are just for efficiency.

**Problem 2**

    void loop()   //runs code repeatedly
    {
      updateSeconds();   //runs the updateSeconds function
      clockShown();   //runs the clockShown function
      clockConversion();    //runs the clockConversion function
    }

Why would you display the clock with `clockShown()` *before* you run `clockConversion()` to nice-up the minute and hour carry-over? Since you are running both `clockShown()` and `clockConversion()` at a high frequency, it doesn't matter much, but from a program flow point of view, I think it makes more sense to do the conversion before you display the values.

**Problem 3**

You are only updating `seconds` every 1000 milliseconds, using the `millis()` function. This is good.

However, nothing at all changes during the 1000 milliseconds between the incrementing of `seconds`. Why not pull the `millis()` parts into `loop()` and call all 3 functions only once per second?

    void loop()   //runs code repeatedly
    {
      unsigned long currentMillis = millis();  //generates the number of milliseconds program has been running
      if (currentMillis - previousMillis >= waittime)
      {
        previousMillis = currentMillis; //updates the last time seconds was updated

        updateSeconds();   //runs the updateSeconds function
        clockConversion();    //runs the clockConversion function
        clockShown();   //runs the clockShown function
      }
    }


message:
Trying to compile code on UNO using ccs811 and LCD

Complete newbie here. I'm really hoping to get something like this to work, and then learn from it. I have a generic UNO board and an LCD/CCS811 on order. I'm trying to do exactly this: (https://create.arduino.cc/projecthub/partsoven/air-quality-monitor-live-display-ad028a) but I'm receiving the following error upon compiling the code. I believe I have all the libraries installed, etc.. but for some reason, I can't get this sketch to upload.. sorry for the crap formatting on this, the {} never works for me and I can't space or indent past a certain point for some reason.... sorry for the long post.

    Arduino: 1.8.1 (Windows 7), Board: "Arduino/Genuino Uno"

    C:\Users\Guy\Documents\Arduino\sketch_jan25a\sketch_jan25a.ino:9:32:
    warning: invalid conversion from 'int' to 't_backlighPol' [-fpermissive]

    LiquidCrystal_I2C lcd(0x3F,16,2);  // set the LCD address to 0x3F for a 16 chars and 2 line display

                                    ^

     In file included from
     C:\Users\Guy\Documents\Arduino\sketch_jan25a\sketch_jan25a.ino:5:0:
     C:\Users\Guy\Documents\Arduino\libraries\jm_LiquidCrystal_I2C/LiquidCrystal_I2C.h:55:2: note: initializing argument 3 of 'LiquidCrystal_I2C::LiquidCrystal_I2C(uint8_t, uint8_t, t_backlighPol)'

      LiquidCrystal_I2C (uint8_t lcd_Addr, uint8_t backlighPin, t_backlighPol pol);

      ^

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::available()'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::rxBufferLength'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::rxBufferIndex'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::read()'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::rxBuffer'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::peek()'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::flush()'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::onReceiveService(unsigned char*, int)'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::user_onReceive'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::onRequestService()'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::user_onRequest'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::txBufferIndex'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::txBufferLength'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::write(unsigned char const*, unsigned int)'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::transmitting'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::write(unsigned char)'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::txBuffer'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::TwoWire()'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::TwoWire()'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `Wire'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::begin()'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::begin(unsigned char)'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::begin(int)'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::end()'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::setClock(unsigned long)'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::beginTransmission(unsigned char)'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::txAddress'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::beginTransmission(int)'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::endTransmission(unsigned char)'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::requestFrom(unsigned char, unsigned char, unsigned long, unsigned char, unsigned char)'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::requestFrom(unsigned char, unsigned char, unsigned char)'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::requestFrom(unsigned char, unsigned char)'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::requestFrom(int, int)'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::requestFrom(int, int, int)'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::endTransmission()'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::onReceive(void (*)(int))'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\jm_Wire.cpp.o (symbol from plugin): In function `TwoWire::available()':

    (.text+0x0): multiple definition of `TwoWire::onRequest(void (*)())'

    libraries\Wire\Wire.cpp.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\utility\jm_twi.c.o (symbol from plugin): In function `twi_readFrom':

    (.text+0x0): multiple definition of `twi_readFrom'

    libraries\Wire\utility\twi.c.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\utility\jm_twi.c.o (symbol from plugin): In function `twi_readFrom':

    (.text+0x0): multiple definition of `twi_writeTo'

    libraries\Wire\utility\twi.c.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\utility\jm_twi.c.o (symbol from plugin): In function `twi_readFrom':

    (.text+0x0): multiple definition of `twi_transmit'

    libraries\Wire\utility\twi.c.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\utility\jm_twi.c.o (symbol from plugin): In function `twi_readFrom':

    (.text+0x0): multiple definition of `twi_init'

    libraries\Wire\utility\twi.c.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\utility\jm_twi.c.o (symbol from plugin): In function `twi_readFrom':

    (.text+0x0): multiple definition of `twi_disable'

    libraries\Wire\utility\twi.c.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\utility\jm_twi.c.o (symbol from plugin): In function `twi_readFrom':

    (.text+0x0): multiple definition of `twi_setAddress'

    libraries\Wire\utility\twi.c.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\utility\jm_twi.c.o (symbol from plugin): In function `twi_readFrom':

    (.text+0x0): multiple definition of `twi_setFrequency'

    libraries\Wire\utility\twi.c.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\utility\jm_twi.c.o (symbol from plugin): In function `twi_readFrom':

    (.text+0x0): multiple definition of `twi_attachSlaveRxEvent'

    libraries\Wire\utility\twi.c.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\utility\jm_twi.c.o (symbol from plugin): In function `twi_readFrom':

    (.text+0x0): multiple definition of `twi_attachSlaveTxEvent'

    libraries\Wire\utility\twi.c.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\utility\jm_twi.c.o (symbol from plugin): In function `twi_readFrom':

    (.text+0x0): multiple definition of `twi_reply'

    libraries\Wire\utility\twi.c.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\utility\jm_twi.c.o (symbol from plugin): In function `twi_readFrom':

    (.text+0x0): multiple definition of `twi_stop'

    libraries\Wire\utility\twi.c.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\utility\jm_twi.c.o (symbol from plugin): In function `twi_readFrom':

    (.text+0x0): multiple definition of `twi_releaseBus'

    libraries\Wire\utility\twi.c.o (symbol from plugin):(.text+0x0): first defined here

    libraries\jm_Wire\utility\jm_twi.c.o (symbol from plugin): In function `twi_readFrom':

    (.text+0x0): multiple definition of `__vector_24'

    libraries\Wire\utility\twi.c.o (symbol from plugin):(.text+0x0): first defined here

    collect2.exe: error: ld returned 1 exit status

    exit status 1
    Error compiling for board Arduino/Genuino Uno.

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

Below is the sketch I'm attempting to upload:

    /*
     * Displays Sparkfun CCS811 data on a Serial enabled LCD sent over I2C.
     */
    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>

    #define I2C_ADDR 0x3F
    LiquidCrystal_I2C lcd(0x3F,16,2);  // set the LCD address to 0x3F for a 16 chars and 2 line display

    #include "SparkFunCCS811.h"

    #define CCS811_ADDR 0x5B // CCS811 Default I2C Address
    //#define CCS811_ADDR 0x5A //Alternate I2C Address

    CCS811 mySensor(CCS811_ADDR);

    void setup()
    {
      lcd.init();                      // initialize the lcd
      lcd.backlight();                //turn on backlight
      Serial.begin(9600);

    }

    void loop()
    {
      //Check to see if data is ready with .dataAvailable()
      if (mySensor.dataAvailable())
      {
        //If so, have the sensor read and calculate the results.
        //Get them later
        mySensor.readAlgorithmResults();

      }

      delay(100); //Don't spam the I2C bus

        // clear the screen
        lcd.clear();
        // go to first row and send CO2 data to the display
        lcd.setCursor(0,0);
        lcd.print("CO2 [");
        lcd.print(mySensor.getCO2());
        lcd.print("] ppb");
          // go to second row and send tVOC data to the display
        lcd.setCursor(0,1);
        lcd.print("tVOC [");
        lcd.print(mySensor.getTVOC());
        lcd.print("] ppm");

    }

body:
I am assuming you are using [this library](https://bitbucket.org/fmalpartida/new-liquidcrystal/overview), which is the only one I can find using that `t_backlighPol` datatype

You need to set the I2C address when you instantiate the object:

    LiquidCrystal_I2C lcd(0x38);  // Set the LCD I2C address

And define the LCD size when you call the `begin()` function. Note that `init()` is a private function of the object:

    lcd.begin(16,2);               // initialize the lcd


message:
bit_is_clear(ACSR, ACO) Instead of digital_read(1)==LOW

I am attempting to create a program for the atmega328P which will enable the aux input of a Toyota Corolla stereo. In order to do this, I'm bitbanging AVC LAN. Nearly all of my research comes from this site:
https://github.com/halleysfifthinc/Toyota-AVC-LAN

In this example, Frigon has wired his Atmega8 in a peculiar way. Instead of connecting the + terminal directly to a single pin of his Atmega8, he's connected it to a pulldown resistor, resisted it to the - terminal (presumably for bus termination) and a digital pin as well as an analog pin. The - terminal has been given similar strange treatment.

In his function ReadBits(), he waits for a physical 1, then sets a timer and waits for a physical 0 to measure the length of the pulse. But when he does this, he uses the equivalent of

    while ( bit_is_clear( ACSR, ACO ) );

That's completely Greek to me. Does this have something to do with something called in Internal Analog Comparator?

I attempted to create something similar using

    while( digitalRead( 2 ) );

but I'm reading static as well as honest-to-goodness pulses. I assume that, anyways, because I'm getting pulses of length 2-7 ticks when many are closer to 20-40 ticks (measured using TCNT0 with no custom prescaler).

So... what exactly is he doing with ACSR and ACO? Why is his + and - terminals connected to more than one pin? Why are his diodes there?

=========================EDIT=======================

Following Edgar's advice, I've reworked my schematic and code to closely match Frigon's work. Below is my code:

    #include <avr/wdt.h>

    #define fwVer       "v0.1"
    #define fwDt        __DATE__
    #define DATAPIN     2

    //====================================================================================COPYPASTED
    #define DATAIN_PIN              ACSR
    #define DATAIN                  ACO

    #define INPUT_IS_SET            ( bit_is_set( DATAIN_PIN, DATAIN ) )
    #define INPUT_IS_CLEAR          ( bit_is_clear( DATAIN_PIN, DATAIN ) )
    //===================================================================================WHAT DOES THIS MEAN

    byte data[255];

    void setup() {
      LedOff();

      Serial.begin(9600);

      pinMode(3,OUTPUT);
      pinMode(2,OUTPUT);
      digitalWrite(3,HIGH); //"leave the pins tri-stated" according to Frigon
      digitalWrite(2,LOW);
      pinMode(LED_BUILTIN,OUTPUT);

      //two second watchdog
      wdt_enable( WDTO_2S );

      Serial.println("Firmware "+String(fwVer)+", compiled on "+fwDt);
      LedOff();
    }

    void LedOff() {
      digitalWrite(LED_BUILTIN, LOW);
    }
    void LedOn() {
      digitalWrite(LED_BUILTIN, HIGH);
    }

    void loop() {
      wdt_reset();
      if (INPUT_IS_CLEAR) LedOff();
      else LedOn();
    }
Schematic: https://i.stack.imgur.com/0UNzF.jpg
(mistake on the schematic - I connected 5v to vcc and ground to ground)
If it matters, I'm powering the head unit and the arduino from the 12v and 5v rails of an ATX power supply. They both take the same ground.

My code should theoretically only turn on my led whenever the head unit broadcasts bits, but it's just sort of erratically blipping on and off or fading gently at random. I've triple checked my wiring (breadboard if that matters). Why is this happening? Is there something about bit_is_clear(ACSR,ACO) that I don't understand?

body:
> Does [`bit_is_clear(ACSR, ACO)`] have something to do with something
> called in Internal Analog Comparator?

Exactly. `ACSR` is the “Analog Comparator Control and Status Register”.
`ACO`, the “Analog Comparator Output” is one bit of this register. The
ATmega328P has the same comparator, with the same register and bit names
as the ATmega8. C.f. the [datasheet][]. You should be able to use this
part of the code as is.

> Frigon has wired his Atmega8 in a peculiar way. [...]

It seems to me that is termination is intended to ensure that, in the
“floating level”, the line AVC− is at a potential higher than AVC+. In
the “driving level”, the opposite should be true, with a difference of
at least 120 mV.

> I attempted to create something similar using `while(digitalRead(2)) ;`

It's not surprising that it doesn't work. This is a differential bus.
The information is carried by the potential difference between AVC+ and
AVC−, not by the potential of a single wire. A difference higher than
120 mV should be interpreted and a high state. Your digital input
instead reads a single wire and compares its potential to ground. The
thresholds to switch between `LOW` and `HIGH` are typically around 2.1
and 2.6 V, with some hysteresis. This is far from being compatible
with the signaling of the bus.

I recommend you follow Frigon's steps and use the analog comparator just
as he does. The comparator will tell you which of AVC+ or AVC− has a
higher potential, and it will not be bothered by the low level of the
differential signaling.

[datasheet]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf#page=299


message:
MPU9250+arduino pro micro strange behaviour after reset

I have an arduino pro micro + mpu9250. For test sketch I'm using https://github.com/sparkfun/SparkFun_MPU-9250-DMP_Arduino_Library

It works as intended after the first sketch upload. After that if I unplug usb cable thus cutting the both devices power and plug back - the fun starts here) My sketch is working, but this time the response from mpu9250 is like 10 times slower. Here is the weird part - it still works, but just shows the data slower in Serial Monitor and the led blinks are slower. What am I doing wrong?

Here is the example I'm using(from the library mentioned above):

        /* MPU9250 Basic Example Code
     by: Kris Winer
     date: April 1, 2014
     license: Beerware - Use this code however you'd like. If you
     find it useful you can buy me a beer some time.
     Modified by Brent Wilkins July 19, 2016

     Demonstrate basic MPU-9250 functionality including parameterizing the register
     addresses, initializing the sensor, getting properly scaled accelerometer,
     gyroscope, and magnetometer data out. Added display functions to allow display
     to on breadboard monitor. Addition of 9 DoF sensor fusion using open source
     Madgwick and Mahony filter algorithms. Sketch runs on the 3.3 V 8 MHz Pro Mini
     and the Teensy 3.1.

     SDA and SCL should have external pull-up resistors (to 3.3V).
     10k resistors are on the EMSENSR-9250 breakout board.

     Hardware setup:
     MPU9250 Breakout --------- Arduino
     VDD ---------------------- 3.3V
     VDDI --------------------- 3.3V
     SDA ----------------------- A4
     SCL ----------------------- A5
     GND ---------------------- GND
     */

    #include "quaternionFilters.h"
    #include "MPU9250.h"

    #ifdef LCD
    #include <Adafruit_GFX.h>
    #include <Adafruit_PCD8544.h>

    // Using NOKIA 5110 monochrome 84 x 48 pixel display
    // pin 9 - Serial clock out (SCLK)
    // pin 8 - Serial data out (DIN)
    // pin 7 - Data/Command select (D/C)
    // pin 5 - LCD chip select (CS)
    // pin 6 - LCD reset (RST)
    Adafruit_PCD8544 display = Adafruit_PCD8544(9, 8, 7, 5, 6);
    #endif // LCD

    #define AHRS true         // Set to false for basic data read
    #define SerialDebug true  // Set to true to get Serial output for debugging

    // Pin definitions
    int intPin = 12;  // These can be changed, 2 and 3 are the Arduinos ext int pins
    int myLed  = 17;  // Set up pin 13 led for toggling

    MPU9250 myIMU;

    void setup()
    {
      Wire.begin();
       TWBR = 12;  // 400 kbit/sec I2C speed
      Serial.begin(115200);

      // Set up the interrupt pin, its set as active high, push-pull
      pinMode(intPin, INPUT);
      digitalWrite(intPin, LOW);
      pinMode(myLed, OUTPUT);
      digitalWrite(myLed, HIGH);

    #ifdef LCD
      display.begin(); // Ini8ialize the display
      display.setContrast(58); // Set the contrast

      // Start device display with ID of sensor
      display.clearDisplay();
      display.setTextSize(2);
      display.setCursor(0,0); display.print("MPU9250");
      display.setTextSize(1);
      display.setCursor(0, 20); display.print("9-DOF 16-bit");
      display.setCursor(0, 30); display.print("motion sensor");
      display.setCursor(20,40); display.print("60 ug LSB");
      display.display();
      delay(1000);

      // Set up for data display
      display.setTextSize(1); // Set text size to normal, 2 is twice normal etc.
      display.setTextColor(BLACK); // Set pixel color; 1 on the monochrome screen
      display.clearDisplay();   // clears the screen and buffer
    #endif // LCD

      // Read the WHO_AM_I register, this is a good test of communication
      byte c = myIMU.readByte(MPU9250_ADDRESS, WHO_AM_I_MPU9250);
      Serial.print("MPU9250 "); Serial.print("I AM "); Serial.print(c, HEX);
      Serial.print(" I should be "); Serial.println(0x71, HEX);

    #ifdef LCD
      display.setCursor(20,0); display.print("MPU9250");
      display.setCursor(0,10); display.print("I AM");
      display.setCursor(0,20); display.print(c, HEX);
      display.setCursor(0,30); display.print("I Should Be");
      display.setCursor(0,40); display.print(0x71, HEX);
      display.display();
      delay(1000);
    #endif // LCD

      if (c == 0x71) // WHO_AM_I should always be 0x68
      {
        Serial.println("MPU9250 is online...");

        // Start by performing self test and reporting values
        myIMU.MPU9250SelfTest(myIMU.SelfTest);
        Serial.print("x-axis self test: acceleration trim within : ");
        Serial.print(myIMU.SelfTest[0],1); Serial.println("% of factory value");
        Serial.print("y-axis self test: acceleration trim within : ");
        Serial.print(myIMU.SelfTest[1],1); Serial.println("% of factory value");
        Serial.print("z-axis self test: acceleration trim within : ");
        Serial.print(myIMU.SelfTest[2],1); Serial.println("% of factory value");
        Serial.print("x-axis self test: gyration trim within : ");
        Serial.print(myIMU.SelfTest[3],1); Serial.println("% of factory value");
        Serial.print("y-axis self test: gyration trim within : ");
        Serial.print(myIMU.SelfTest[4],1); Serial.println("% of factory value");
        Serial.print("z-axis self test: gyration trim within : ");
        Serial.print(myIMU.SelfTest[5],1); Serial.println("% of factory value");

        // Calibrate gyro and accelerometers, load biases in bias registers
        myIMU.calibrateMPU9250(myIMU.gyroBias, myIMU.accelBias);

    #ifdef LCD
        display.clearDisplay();

        display.setCursor(0, 0); display.print("MPU9250 bias");
        display.setCursor(0, 8); display.print(" x   y   z  ");

        display.setCursor(0,  16); display.print((int)(1000*accelBias[0]));
        display.setCursor(24, 16); display.print((int)(1000*accelBias[1]));
        display.setCursor(48, 16); display.print((int)(1000*accelBias[2]));
        display.setCursor(72, 16); display.print("mg");

        display.setCursor(0,  24); display.print(myIMU.gyroBias[0], 1);
        display.setCursor(24, 24); display.print(myIMU.gyroBias[1], 1);
        display.setCursor(48, 24); display.print(myIMU.gyroBias[2], 1);
        display.setCursor(66, 24); display.print("o/s");

        display.display();
        delay(1000);
    #endif // LCD

        myIMU.initMPU9250();
        // Initialize device for active mode read of acclerometer, gyroscope, and
        // temperature
        Serial.println("MPU9250 initialized for active data mode....");

        // Read the WHO_AM_I register of the magnetometer, this is a good test of
        // communication
        byte d = myIMU.readByte(AK8963_ADDRESS, WHO_AM_I_AK8963);
        Serial.print("AK8963 "); Serial.print("I AM "); Serial.print(d, HEX);
        Serial.print(" I should be "); Serial.println(0x48, HEX);

    #ifdef LCD
        display.clearDisplay();
        display.setCursor(20,0); display.print("AK8963");
        display.setCursor(0,10); display.print("I AM");
        display.setCursor(0,20); display.print(d, HEX);
        display.setCursor(0,30); display.print("I Should Be");
        display.setCursor(0,40); display.print(0x48, HEX);
        display.display();
        delay(1000);
    #endif // LCD

        // Get magnetometer calibration from AK8963 ROM
        myIMU.initAK8963(myIMU.magCalibration);
        // Initialize device for active mode read of magnetometer
        Serial.println("AK8963 initialized for active data mode....");
        if (SerialDebug)
        {
          //  Serial.println("Calibration values: ");
          Serial.print("X-Axis sensitivity adjustment value ");
          Serial.println(myIMU.magCalibration[0], 2);
          Serial.print("Y-Axis sensitivity adjustment value ");
          Serial.println(myIMU.magCalibration[1], 2);
          Serial.print("Z-Axis sensitivity adjustment value ");
          Serial.println(myIMU.magCalibration[2], 2);
        }

    #ifdef LCD
        display.clearDisplay();
        display.setCursor(20,0); display.print("AK8963");
        display.setCursor(0,10); display.print("ASAX "); display.setCursor(50,10);
        display.print(myIMU.magCalibration[0], 2);
        display.setCursor(0,20); display.print("ASAY "); display.setCursor(50,20);
        display.print(myIMU.magCalibration[1], 2);
        display.setCursor(0,30); display.print("ASAZ "); display.setCursor(50,30);
        display.print(myIMU.magCalibration[2], 2);
        display.display();
        delay(1000);
    #endif // LCD
      } // if (c == 0x71)
      else
      {
        Serial.print("Could not connect to MPU9250: 0x");
        Serial.println(c, HEX);
        while(1) ; // Loop forever if communication doesn't happen
      }
    }

    void loop()
    {
      // If intPin goes high, all data registers have new data
      // On interrupt, check if data ready interrupt
      if (myIMU.readByte(MPU9250_ADDRESS, INT_STATUS) & 0x01)
      {
        myIMU.readAccelData(myIMU.accelCount);  // Read the x/y/z adc values
        myIMU.getAres();

        // Now we'll calculate the accleration value into actual g's
        // This depends on scale being set
        myIMU.ax = (float)myIMU.accelCount[0]*myIMU.aRes; // - accelBias[0];
        myIMU.ay = (float)myIMU.accelCount[1]*myIMU.aRes; // - accelBias[1];
        myIMU.az = (float)myIMU.accelCount[2]*myIMU.aRes; // - accelBias[2];

        myIMU.readGyroData(myIMU.gyroCount);  // Read the x/y/z adc values
        myIMU.getGres();

        // Calculate the gyro value into actual degrees per second
        // This depends on scale being set
        myIMU.gx = (float)myIMU.gyroCount[0]*myIMU.gRes;
        myIMU.gy = (float)myIMU.gyroCount[1]*myIMU.gRes;
        myIMU.gz = (float)myIMU.gyroCount[2]*myIMU.gRes;

        myIMU.readMagData(myIMU.magCount);  // Read the x/y/z adc values
        myIMU.getMres();
        // User environmental x-axis correction in milliGauss, should be
        // automatically calculated
        myIMU.magbias[0] = +470.;
        // User environmental x-axis correction in milliGauss TODO axis??
        myIMU.magbias[1] = +120.;
        // User environmental x-axis correction in milliGauss
        myIMU.magbias[2] = +125.;

        // Calculate the magnetometer values in milliGauss
        // Include factory calibration per data sheet and user environmental
        // corrections
        // Get actual magnetometer value, this depends on scale being set
        myIMU.mx = (float)myIMU.magCount[0]*myIMU.mRes*myIMU.magCalibration[0] -
                   myIMU.magbias[0];
        myIMU.my = (float)myIMU.magCount[1]*myIMU.mRes*myIMU.magCalibration[1] -
                   myIMU.magbias[1];
        myIMU.mz = (float)myIMU.magCount[2]*myIMU.mRes*myIMU.magCalibration[2] -
                   myIMU.magbias[2];
      } // if (readByte(MPU9250_ADDRESS, INT_STATUS) & 0x01)

      // Must be called before updating quaternions!
      myIMU.updateTime();

      // Sensors x (y)-axis of the accelerometer is aligned with the y (x)-axis of
      // the magnetometer; the magnetometer z-axis (+ down) is opposite to z-axis
      // (+ up) of accelerometer and gyro! We have to make some allowance for this
      // orientationmismatch in feeding the output to the quaternion filter. For the
      // MPU-9250, we have chosen a magnetic rotation that keeps the sensor forward
      // along the x-axis just like in the LSM9DS0 sensor. This rotation can be
      // modified to allow any convenient orientation convention. This is ok by
      // aircraft orientation standards! Pass gyro rate as rad/s
    //  MadgwickQuaternionUpdate(ax, ay, az, gx*PI/180.0f, gy*PI/180.0f, gz*PI/180.0f,  my,  mx, mz);
      MahonyQuaternionUpdate(myIMU.ax, myIMU.ay, myIMU.az, myIMU.gx*DEG_TO_RAD,
                             myIMU.gy*DEG_TO_RAD, myIMU.gz*DEG_TO_RAD, myIMU.my,
                             myIMU.mx, myIMU.mz, myIMU.deltat);

      if (!AHRS)
      {
        myIMU.delt_t = millis() - myIMU.count;
        if (myIMU.delt_t > 500)
        {
          if(SerialDebug)
          {
            // Print acceleration values in milligs!
            Serial.print("X-acceleration: "); Serial.print(1000*myIMU.ax);
            Serial.print(" mg ");
            Serial.print("Y-acceleration: "); Serial.print(1000*myIMU.ay);
            Serial.print(" mg ");
            Serial.print("Z-acceleration: "); Serial.print(1000*myIMU.az);
            Serial.println(" mg ");

            // Print gyro values in degree/sec
            Serial.print("X-gyro rate: "); Serial.print(myIMU.gx, 3);
            Serial.print(" degrees/sec ");
            Serial.print("Y-gyro rate: "); Serial.print(myIMU.gy, 3);
            Serial.print(" degrees/sec ");
            Serial.print("Z-gyro rate: "); Serial.print(myIMU.gz, 3);
            Serial.println(" degrees/sec");

            // Print mag values in degree/sec
            Serial.print("X-mag field: "); Serial.print(myIMU.mx);
            Serial.print(" mG ");
            Serial.print("Y-mag field: "); Serial.print(myIMU.my);
            Serial.print(" mG ");
            Serial.print("Z-mag field: "); Serial.print(myIMU.mz);
            Serial.println(" mG");

            myIMU.tempCount = myIMU.readTempData();  // Read the adc values
            // Temperature in degrees Centigrade
            myIMU.temperature = ((float) myIMU.tempCount) / 333.87 + 21.0;
            // Print temperature in degrees Centigrade
            Serial.print("Temperature is ");  Serial.print(myIMU.temperature, 1);
            Serial.println(" degrees C");
          }

    #ifdef LCD
          display.clearDisplay();
          display.setCursor(0, 0); display.print("MPU9250/AK8963");
          display.setCursor(0, 8); display.print(" x   y   z  ");

          display.setCursor(0,  16); display.print((int)(1000*myIMU.ax));
          display.setCursor(24, 16); display.print((int)(1000*myIMU.ay));
          display.setCursor(48, 16); display.print((int)(1000*myIMU.az));
          display.setCursor(72, 16); display.print("mg");

          display.setCursor(0,  24); display.print((int)(myIMU.gx));
          display.setCursor(24, 24); display.print((int)(myIMU.gy));
          display.setCursor(48, 24); display.print((int)(myIMU.gz));
          display.setCursor(66, 24); display.print("o/s");

          display.setCursor(0,  32); display.print((int)(myIMU.mx));
          display.setCursor(24, 32); display.print((int)(myIMU.my));
          display.setCursor(48, 32); display.print((int)(myIMU.mz));
          display.setCursor(72, 32); display.print("mG");

          display.setCursor(0,  40); display.print("Gyro T ");
          display.setCursor(50,  40); display.print(myIMU.temperature, 1);
          display.print(" C");
          display.display();
    #endif // LCD

          myIMU.count = millis();
          digitalWrite(myLed, !digitalRead(myLed));  // toggle led
        } // if (myIMU.delt_t > 500)
      } // if (!AHRS)
      else
      {
        // Serial print and/or display at 0.5 s rate independent of data rates
        myIMU.delt_t = millis() - myIMU.count;

        // update LCD once per half-second independent of read rate
        if (myIMU.delt_t > 500)
        {
          if(SerialDebug)
          {
            Serial.print("ax = "); Serial.print((int)1000*myIMU.ax);
            Serial.print(" ay = "); Serial.print((int)1000*myIMU.ay);
            Serial.print(" az = "); Serial.print((int)1000*myIMU.az);
            Serial.println(" mg");

            Serial.print("gx = "); Serial.print( myIMU.gx, 2);
            Serial.print(" gy = "); Serial.print( myIMU.gy, 2);
            Serial.print(" gz = "); Serial.print( myIMU.gz, 2);
            Serial.println(" deg/s");

            Serial.print("mx = "); Serial.print( (int)myIMU.mx );
            Serial.print(" my = "); Serial.print( (int)myIMU.my );
            Serial.print(" mz = "); Serial.print( (int)myIMU.mz );
            Serial.println(" mG");

            Serial.print("q0 = "); Serial.print(*getQ());
            Serial.print(" qx = "); Serial.print(*(getQ() + 1));
            Serial.print(" qy = "); Serial.print(*(getQ() + 2));
            Serial.print(" qz = "); Serial.println(*(getQ() + 3));
          }

    // Define output variables from updated quaternion---these are Tait-Bryan
    // angles, commonly used in aircraft orientation. In this coordinate system,
    // the positive z-axis is down toward Earth. Yaw is the angle between Sensor
    // x-axis and Earth magnetic North (or true North if corrected for local
    // declination, looking down on the sensor positive yaw is counterclockwise.
    // Pitch is angle between sensor x-axis and Earth ground plane, toward the
    // Earth is positive, up toward the sky is negative. Roll is angle between
    // sensor y-axis and Earth ground plane, y-axis up is positive roll. These
    // arise from the definition of the homogeneous rotation matrix constructed
    // from quaternions. Tait-Bryan angles as well as Euler angles are
    // non-commutative; that is, the get the correct orientation the rotations
    // must be applied in the correct order which for this configuration is yaw,
    // pitch, and then roll.
    // For more see
    // http://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles
    // which has additional links.
          myIMU.yaw   = atan2(2.0f * (*(getQ()+1) * *(getQ()+2) + *getQ() *
                        *(getQ()+3)), *getQ() * *getQ() + *(getQ()+1) * *(getQ()+1)
                        - *(getQ()+2) * *(getQ()+2) - *(getQ()+3) * *(getQ()+3));
          myIMU.pitch = -asin(2.0f * (*(getQ()+1) * *(getQ()+3) - *getQ() *
                        *(getQ()+2)));
          myIMU.roll  = atan2(2.0f * (*getQ() * *(getQ()+1) + *(getQ()+2) *
                        *(getQ()+3)), *getQ() * *getQ() - *(getQ()+1) * *(getQ()+1)
                        - *(getQ()+2) * *(getQ()+2) + *(getQ()+3) * *(getQ()+3));
          myIMU.pitch *= RAD_TO_DEG;
          myIMU.yaw   *= RAD_TO_DEG;
          // Declination of SparkFun Electronics (40°05'26.6"N 105°11'05.9"W) is
          //  8° 30' E  ± 0° 21' (or 8.5°) on 2016-07-19
          // - http://www.ngdc.noaa.gov/geomag-web/#declination
          myIMU.yaw   -= 8.5;
          myIMU.roll  *= RAD_TO_DEG;

          if(SerialDebug)
          {
            Serial.print("Yaw, Pitch, Roll: ");
            Serial.print(myIMU.yaw, 2);
            Serial.print(", ");
            Serial.print(myIMU.pitch, 2);
            Serial.print(", ");
            Serial.println(myIMU.roll, 2);

            Serial.print("rate = ");
            Serial.print((float)myIMU.sumCount/myIMU.sum, 2);
            Serial.println(" Hz");
          }

    #ifdef LCD
          display.clearDisplay();

          display.setCursor(0, 0); display.print(" x   y   z  ");

          display.setCursor(0,  8); display.print((int)(1000*myIMU.ax));
          display.setCursor(24, 8); display.print((int)(1000*myIMU.ay));
          display.setCursor(48, 8); display.print((int)(1000*myIMU.az));
          display.setCursor(72, 8); display.print("mg");

          display.setCursor(0,  16); display.print((int)(myIMU.gx));
          display.setCursor(24, 16); display.print((int)(myIMU.gy));
          display.setCursor(48, 16); display.print((int)(myIMU.gz));
          display.setCursor(66, 16); display.print("o/s");

          display.setCursor(0,  24); display.print((int)(myIMU.mx));
          display.setCursor(24, 24); display.print((int)(myIMU.my));
          display.setCursor(48, 24); display.print((int)(myIMU.mz));
          display.setCursor(72, 24); display.print("mG");

          display.setCursor(0,  32); display.print((int)(myIMU.yaw));
          display.setCursor(24, 32); display.print((int)(myIMU.pitch));
          display.setCursor(48, 32); display.print((int)(myIMU.roll));
          display.setCursor(66, 32); display.print("ypr");

        // With these settings the filter is updating at a ~145 Hz rate using the
        // Madgwick scheme and >200 Hz using the Mahony scheme even though the
        // display refreshes at only 2 Hz. The filter update rate is determined
        // mostly by the mathematical steps in the respective algorithms, the
        // processor speed (8 MHz for the 3.3V Pro Mini), and the magnetometer ODR:
        // an ODR of 10 Hz for the magnetometer produce the above rates, maximum
        // magnetometer ODR of 100 Hz produces filter update rates of 36 - 145 and
        // ~38 Hz for the Madgwick and Mahony schemes, respectively. This is
        // presumably because the magnetometer read takes longer than the gyro or
        // accelerometer reads. This filter update rate should be fast enough to
        // maintain accurate platform orientation for stabilization control of a
        // fast-moving robot or quadcopter. Compare to the update rate of 200 Hz
        // produced by the on-board Digital Motion Processor of Invensense's MPU6050
        // 6 DoF and MPU9150 9DoF sensors. The 3.3 V 8 MHz Pro Mini is doing pretty
        // well!
          display.setCursor(0, 40); display.print("rt: ");
          display.print((float) myIMU.sumCount / myIMU.sum, 2);
          display.print(" Hz");
          display.display();
    #endif // LCD

          myIMU.count = millis();
          myIMU.sumCount = 0;
          myIMU.sum = 0;
        } // if (myIMU.delt_t > 500)
      } // if (AHRS)
    }

body: The fix found - wrong bootloader was flashed in the Arduino Pro Micro chip. Had to reflash it using AVR ISP mk2 and Arduino IDE. So if you got something like and your board is not genuine SparkFun Pro Micro - then reflash the bootloader.


message:
Why Commenting Serial.print() gives me a different value?

I am working on with `Cypress` and `Arduino`.I am trying to transfer the data from `cypress` and printing it to the `Serial Monitor` or Arduino. but the thing is when I am using `Serial.print(j)` it is showing the right value of i (See in the code about what is `i and j`), but when I comment or remove `Serial.print(j)` it is showing the wrong value of `i`
For example, suppose cypress is sending data `00001934a`
and then I am reading this value using

    int j = mySerial.read()-'0';
    // -'0' is for chaging ascii data to normal integer
    //for example ascii value of `0` is 48
    //so mySerial will read 48
    // and exprerssion value will become `48-48 = 0`

My code

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(10, 11); // RX, TX
    void setup() {
    Serial.begin(57600);
     while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
    }

    mySerial.begin(4800);
    }

    int  i = 0;
    int j = 0;
    void loop() {
    if (mySerial.available()) {

            while(j!=49){
            i = i*10 + j;
            j = mySerial.read()-'0';
             //49 is the ascii value of a, I am using this for acting like
             //a flag, so that i can see the break in data

            Serial.println(j);//commeting this line is causing the problem
          }
       Serial.print(i);
       }
    }

when the line is not commented the output was

    0
    0
    0
    0
    1
    9
    3
    4
    49
    193 //this is the value of i which is correct one
but when I comment the line `Serial.println(j)` the output was

       14569 // I don't know what the hack is this.

Hopefully the problem is understandable, but still, you can comment for more detail.
BTW I am using SoftwareSerial.

body:
Please, explain this to me

       while(j!=49){
            i = i*10 + j;

            Serial.println(j);//commeting this line is causing the problem
          }
       Serial.print(i);

The variable `j` never change inside the `while`.

You print the same `j` time and time again inside the `while`.

The variable `i` keep incrementing inside the `while`. It never stop.

I don't think you posted your real code.


body:
Your serial reading is completely flawed:

    if (mySerial.available()) {

        while(j!=49){
        i = i*10 + j;
        j = mySerial.read()-'0';

What you are saying there is:

* If there is *at least one* character available:
* Read as many characters as can until I get 49.

The main thing wrong with that is that you try and read characters that just don't exist. Serial comes in a byte a time and you *must* wait for those characters to arrive before attempting to read them.  By adding the serial print into your loop you are slowing it down and, by chance, giving the characters time to arrive.

* [Read this to better understand how serial works](https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/).


body:
Majenko has correctly diagnosed your problem, and the blog post he
linked to is definitely a must-read. The suggested solution, namely
buffering the input until you can read a complete message, is presumably
the most standard way of dealing with an input stream.

It is, however, not the only option. Your idea of building the number
digit by digit can work, if implemented properly, and it can save you
the memory cost of the buffer. The key is to only read bytes when they
are available.

Below is a _non-blocking_ implementation of a number reader that works
along the lines of your own code. This function only reads positive
numbers. It returns the number it just parsed upon reading a non-digit
character. In every other case it returns `-1` to tell you there is no
input number available:

    // Read an positive integer from a stream.
    // Returns -1 if a complete integer is not available.
    int readInt(Stream &link)
    {
        static bool got_a_digit = false;  // did we get a digit so far?
        static int i = 0;                 // the integer we are building
        if (link.available()) {
            char c = link.read();
            if (isdigit(c)) {
                i = 10 * i + (c - '0');
                got_a_digit = true;
            } else if (got_a_digit) {  // non-digit: return the number
                int i_copy = i;
                got_a_digit = false;   // reset for next reading
                i = 0;                 // ditto
                return i_copy;
            }
        }
        return -1;
    }

And here is how you would use it:

    void loop() {
        int i = readInt(mySerial);
        if (i != -1)
            Serial.println(i);
    }


message:
How can I record a push button sequence and store it in an array

I have 3 push buttons and I want to record the sequence in which they are pressed in array of size 10,i.e, I want to record 10 values for example {1,1,2,2,3,3,1,1,1,3}. I want to blink an array of 3 LED in the same pattern in which the buttons were pressed. I have two extra push buttons for putting the arduino in record and play modes respectively. If any one can suggest how I can store the values in the array I will really be very thankful. I am also facing the problem because it's very difficult to manage the bouncing of the buttons simultaneously.

body:
You can create an array like this, make it global to easy access it:

    int states[10];

And the current index:

    int index_state = 0;

And initialize the array (in setup):

    for (int n = 0; n < 10; n++)
    {
        states[n] = 0; // Unpressed
    }

When a new button press should be stored:

    states[index_state] = state;

And add one to the index state, if 10 is reached, start over (this means the last 10 are stored).

    index_state = (index_state + 1) % 10;

And to check the states you just iterate from index_state.

Hope this helps you get going.

Note this is called a ring buffer.