body:
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?

title: Does the tone() generates unwanted signal?

Answers: 2

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.


body:
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.

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

Answers: 2

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)


body:
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
      }
    }

title: LCD Clock Millis Code Issue

Answers: 1

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
      }
    }


body:
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");

    }

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

Answers: 1

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


body:
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?

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

Answers: 1

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


body:
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)
    }

title: MPU9250+arduino pro micro strange behaviour after reset

Answers: 1

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.


body:
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.

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

Answers: 3

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);
    }


body: 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.

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

Answers: 2

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.

body:
this is my code that stores the button sequence but it will be great if someone can help me blink the LED sequence an put the micro-controller in play or record mode when desired. Also this code faces some issue as some times it fails to take inputs or takes two inputs at a time:

    int arr[10];
    boolean previous = LOW;
    unsigned long time1 = 0;
    int debounce = 200;
    unsigned long time2 = 0;
    int index_state = 0;
    void setup()
    {
     for(int i = 3;i<6 ;i++)
      pinMode(i,INPUT);
     for(int n=0;n<10;n++) arr[n] = 0;//initialisition
     Serial.begin(9600);
    }

    void loop(){
     boolean mode = digitalRead(3) || digitalRead(4) || digitalRead(5);
     while(mode == LOW) mode = digitalRead(3) || digitalRead(4) || digitalRead(5);//wait here till one of the pushbutton goes high;
     //Serial.println("value");
     if( mode == HIGH && previous == LOW && millis() - time1 > debounce){
     //find out which one is high and store that value in array;
     if(digitalRead(3)) arr[index_state] = 3;
     else if(digitalRead(4)) arr[index_state] = 4;
     else if(digitalRead(5)) arr[index_state] = 5;
     else ;
     //print the value and the index;
     Serial.print(arr[index_state]);
     Serial.print(" Stored in index: ");
     Serial.println(index_state);
     index_state = (index_state + 1) % 10;
     //update value of time1 for button debouncing
     time1 =  millis();
    }

      //update the value of previous button state
      previous = digitalRead(3) || digitalRead(4) || digitalRead(5);

      }


body:
I've bought a BSFrance LoRA32u4 from DIYmall on eBay UK.

https://bsfrance.fr/lora-long-range/1311-BSFrance-LoRa32u4-1KM-Long-Range-Board-Based-Atmega32u4-433MHz-LoRA-RA02-Module.html

I've copied the "bsfrance" directory (from the ZIP) into Arduino/hardware (on 64-bit Ubuntu 16.04).

Staring the Arduino IDE, I've selected the correct board (Tools>>Board>>BSFrance>>LoRA32u4).

I've selected the correct port Tools>>Port>>/dev/ttyACM1 (LoRA32u4).

Verifying a trivial sketch looks fine:

    void setup() {
      pinMode(LED_BUILTIN, OUTPUT);
    }

    void loop() {
      digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);                       // wait for a second
      digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);                       // wait for a second
    }

Result:

    Sketch uses 4104 bytes (14%) of program storage space. Maximum is 28672 bytes.
    Global variables use 149 bytes of dynamic memory.

The USB device appears in `lsusb` as: `Bus 002 Device 077: ID 239a:800c`.

Clicking install causes a white LED to flicker for around ten seconds, but results in:

    avrdude: error: buffered memory access not supported. Maybe it isn't
    a butterfly/AVR109 but a AVR910 device?
    avrdude: initialization failed, rc=-1
             Double check connections and try again, or use -F to override
             this check.

or:

    Couldn't find a Board on the selected port. Check that you have the
    correct port selected.  If it is correct, try pressing the board's reset
    button after initiating the upload.

or:

    Found programmer: Id = "CATERIN"; type =

or:

    Device code: 0x0d

or:

    .   Software Version = 1.0; Hardware Version =

or:

    An error occurred while uploading the sketch

How do I transfer code onto this board?

(I am new to Arduino, so I may be missing something obvious.  I do have lots of experience programming vanilla ATMEGAs in C without the Arduino IDE.)

--

I have an AVRISP mkII - would burning a new boot-loader help, or just wreck the USB-serial on the device?

title: How to program a BSFrance LoRA32u4 from Arduine IDE 8.5?

Answers: 2

body:
I emailed BSFrance and they were very helpful, coming back with a few suggestions which I could not get to work.

I then tried the Sketch>>Upload Using Programmer with my AVRISPmkII and it worked.  I'm guessing there is a bootloader/Linux issue with the board I bought, and bypassing it let me program the board.

It also works flawlessly with my Mac Mini.

body:
I've had the same problem, but couldn't fix it with the "Upload using programmer".
Instead i sound that the problem was that the serial connection kept dropping after a couple of seconds. My colleague, also on Ubuntu, had the same issue.

This fixed it for me: https://learn.adafruit.com/adafruit-arduino-ide-setup/linux-setup#udev-rules

The board registers as an Adafruit board on my system, and apparently the ModemManager is not too keen on that.

After running first command in the link and restarting, i could upload to the board from Arduino IDE with no errors.


body:
For a bitbanging project I'm working on, I need to measure microseconds as accurately as possible. The function micros() won't work for me here because of the unpredictable times at which it might roll over. I have been using this project by Louis Frigon as an example:

https://web.archive.org/web/20140627135927/http://www.sigmaobjects.com/toyota/

In this document he sets his Atmega8's prescaler value:

    // Timer 0 prescaler = 8 ( 1 count / us )
    TCCR0 = _BV(CS01);
Do I understand that after these instructions, TCNT0 counts up by nearly precise microseconds?
If so, what math could I use to set my prescaler for measuring microseconds? The 328P has a higher clock speed, does that mean I won't be able to do this?

title: Atmega328P Prescaler to Microseconds

Answers: 1

body:
> The 328P has a higher clock speed

The 328P will run at whatever speed you clock it, up to a maximum that
depends on the supply voltage. Most 328P-based Arduinos are clocked at
16 MHz though.

> what math could I use to set my prescaler for measuring microseconds?

You can't. You would have to set the prescaler to 16 if you want the
timer to count microseconds. You can set it to 8 or to 64, but there is
no intermediate setting in between.

Maybe you could leave the prescaler at 8 and count half-microseconds
instead?

------------------------------------------------------------------------

**Edit**: On the 328P, Timer 0 has _two_ control registers, named
`TCCR0A` and `TCCR0B`. To set it to normal counting mode at `F_CPU`/8,
you have to:

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

    TCCR0A = 0;
    TCCR0B = _BV(CS01);

If you are programming in plain C, the first line is not needed (but it
won't hurt either), as the initial value of `TCCR0A` is zero on reset.
If you are using the Arduino core library (and you write `setup()` and
`loop()` instead of `main()`), then you do need this first line, as the
Arduino core configures Timer 0 for PWM at 977 Hz. But note
that the Arduino core also uses Timer 0 for timekeeping
(`millis()`, `micros()` and `delay()`). Thus you may want to use another
timer.

You could switch to Timer 2 by replacing every “0” with a “2” on
the register and bit names of the two lines above. Then you would also
replace every occurrence of `TCNT0` in the code with `TCNT2`.


body:
I’m using WeMos D1 R2 and latest Blynk library and app. I am also using Arduino IDE 1.6.13. I am trying to read a button from the app, which works fine, but i want to read it continuously. Through the Serial Monitor I can see that the board changes modes as it should. However, even if sensors read values when we get through the first “if” states, the values do not continue to show up in Serial Monitor. I believe that’s happening because it is not working as a loop. Also, the relays are not working(they start as open as they should, but their state never changes), as I believe program freezes at some point.

Here is the code:

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

    //Start of program
    #include <dht11.h>
    #define BLYNK_PRINT Serial//
    #include <ESP8266WiFi.h>
    #include <Blynk.h>
    #include <BlynkSimpleEsp8266.h>
    #include <NewPing.h>
    #include <SimpleTimer.h>

    #define TRIGGER_PIN2 D4 // Arduino pin tied to trigger pin on the ultrasonic sensor 2.
    #define ECHO_PIN2 D5     // Arduino pin tied to echo pin on the ultrasonic sensor 2.
    #define MAX_DISTANCE2  23// Height of the Water Tank 2 (in centimeters).
    #define DHT11_PIN D6

    char auth[] = "****";
    char ssid[] = "8888";
    char pass[] = "psw";

    int Relay1 = D1;
    int Relay2 = D2;
    int val2 = 0;
    int tankwater1 = 0; //water in tank 1 in liters
    int tankwater2 = 0; //water in tank 2 in liters
    int fieldsize1 = 0; //size of field1 in m^2
    int fieldsize2 = 0; //size of field2 in m^2
    int sensor_pin = D7;
    SimpleTimer timer;
    //NewPing sonar1(TRIGGER_PIN1, ECHO_PIN1, MAX_DISTANCE1); // NewPing setup
    of pins and maximum distance.
    NewPing sonar2(TRIGGER_PIN2, ECHO_PIN2, MAX_DISTANCE2); // NewPing setup of
    pins and maximum distance.

    void setup()
    {
      Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
      Blynk.begin(auth, ssid, pass);
      pinMode(Relay1, OUTPUT); //Setup Relay pin as output pin
      pinMode(Relay2, OUTPUT); //Setup Relay pin as output pin
      //pinMode(led_pin, OUTPUT);
      pinMode(sensor_pin, INPUT);
      digitalWrite(Relay1, LOW);
      digitalWrite(Relay2, LOW);
    }

    void loop()
    {
      Blynk.run();
      timer.run();
    }

    BLYNK_READ(V8)
    {
      Blynk.virtualWrite(8, 23 - val2); // virtualpin 8 distance
    }

    BLYNK_WRITE(V1) {
      int pinValue = param.asInt();

      if (pinValue == 0)
      {
        val2 = sonar2.convert_cm(sonar2.ping_median());
        Serial.println("Irrigation mode is active");
        Serial.println("Water level is at:");
        Serial.println(23 - val2);

        if (digitalRead(sensor_pin) == HIGH)
        {
          if (val2 <= 15) //Water level reaches the Top of the Tank2
          {
            digitalWrite(Relay2, HIGH); //Pump2 off
            delay(500);
          }
          else if (val2 > 15) // Water is empty on the Tank2
          {
            digitalWrite(Relay2, LOW); // Pump2 ON
            delay(500);
            //delay(86400000); one day delay. not suitable for experiment
          }
          else if (digitalRead(sensor_pin) == LOW)
          {
            digitalWrite(Relay1, LOW);
          }
        }
      }
      else {
        Serial.println("Fertilize mode is active. This does nothing now");
        //val3 = sonar2.convert_cm(sonar2.ping_median());
        //tankwater2 = (10-val3)*fieldsize2; //calculation of water in tank2
      }
    }
    //End of program

title: Problem with action that should happen in loop(continuously)

Answers: 1

body:
The `BLYNK_WRITE(V1)` function is only called when a Blynk app widget sends data to your hardware. It does not run in a loop. If you want something to run in a loop, put it in `loop()`.

The `WRITE` aspect is from the point of view of the App, not of your hardware, so your hardware uses `BLYNK_WRITE()` to **receive** information from the app. And it's only called when the app chooses to send that information. For example, when a button in the Blynk smartphone app is pushed.


body:
This is the first time that I realized that extra SMD IC near the USB port of the Arduino UNO is actually a fully fledged microcontroller, I thought that it was just a USB to Serial converter. Further research into this chip left me with more questions than answers.

First of all, why did Arduino decide to use the Atmega16U2 as a USB to Serial converter? Couldn't they have gone with an FTDI chip instead? I came across this phrase on Quora "The best part is that you can also program and create your own applications on the 16u2 if you have an In-circuit Serial Programmer". How exactly does this work?

What about the two other set of connectors on the board? (other than the two main rows of headers) The ones labeled ICSP and JP2? Is the JP2 for the 16U2? I read that these could be used for burning the code onto the Atmega328P so that it can be modified, but not overwritten. What are any other uses for the 16U2 on the Arduino UNO?

title: Why was the Atmega16U2 used on the Arduino UNO as a USB to Serial converter?

Answers: 1

body:
First reason I'd guess is price:

 - [FT232 on octopart][1]: USD2.65 ~ 3
 - [Atmega16U2 on octopart][2]: USD2.12 ~ 2.2

They can probably get much better deals considering that the Atmega328 is also from Atmel (now Microchip).

About the programming:

There are some projects which make the Atmega16U2 into a MIDI device over USB or HID, for example some repos: [1][3], [2][4], [3][5]. I've used the second one I think, and it works fine.

You can program it with an ISP/ICSP programmer such as Atmel ICE(below) or [Arduino ISP][6].

[![enter image description here][7]][7]

Use the ISP pins by the Atmega16U2:

[![enter image description here][8]][8]

  [1]: https://octopart.com/search?q=FT232&start=0
  [2]: https://octopart.com/search?q=atmega16u2&start=0
  [3]: https://github.com/harlequin-tech/arduino-usb
  [4]: https://github.com/ddiakopoulos/hiduino
  [5]: https://github.com/kuwatay/mocolufa
  [6]: https://www.arduino.cc/en/Tutorial/ArduinoISP
  [7]: https://i.stack.imgur.com/rpxZF.jpg
  [8]: https://i.stack.imgur.com/DAqSF.png


body: Can I measure lithium ion cell voltage with Arduino ADC which is used to power the same Arduino through a boost module (XL6009)? The output voltage of boost module is 9 volts.

title: Measuring Lithium ion cell voltage used to power Arduino via a boost module

Answers: 1

body:
I'm the author of a library called [BatterySense][1] and you can use it to achieve your goal. In the repository Readme you can also find wiring diagrams and usage examples, but to give you a rough idea...

 1. Verify the negative side of your battery has continuity to the GND pin of your Arduino: you need to identify if the boost module is messing the common ground, but if you have continuity then you are fine
 2. Add a connection from the battery positive terminal going into one of the Arduino analog pins
 3. Use the BatterySense library to get the battery voltage and percentage level

  [1]: https://github.com/rlogiacco/BatterySense


body:
My project is automatic room light controller with visitor counter using Arduino.

My project was running correct upto this, but the problem started when we connected GSM module to our project because we have given a limit to the room, so when after limit exceeded using GSM a msg must be sent to the admin.

Actual problem is when a limit exceeds,code is not coming out of loop and when we are trying to increment or decrement no. of persons using IR sensor but its not happening.

Help me which loop i sholud use to send msg automatically

    #include<LiquidCrystal.h>
    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(3, 5);
    char msg;
    LiquidCrystal lcd(13, 12, 11, 10, 9, 8);
    #define in 14
    #define out 19
    #define relay 2
    int count = 0;
    void IN()
    {
      count++;
      lcd.clear();
      lcd.print("Person In Room:");
      lcd.setCursor(0, 1);
      lcd.print(count);
      delay(1000);
    }
    void OUT()
    {
      count--;
      lcd.clear();
      lcd.print("Person In Room:");
      lcd.setCursor(0, 1);
      lcd.print(count);
      delay(1000);
    }
    void setup()
    {
      lcd.begin(16, 2);
      lcd.print("Visitor Counter");
      delay(2000);
      pinMode(in, INPUT);
      pinMode(out, INPUT);
      pinMode(relay, OUTPUT);
      lcd.clear();
      lcd.print("Person In Room:");
      lcd.setCursor(0, 1);
      lcd.print(count);

      mySerial.begin(9600);   // Setting the baud rate of GSM Module
      Serial.begin(9600);    // Setting the baud rate of Serial Monitor (Arduino)
      Serial.println("GSM SIM900A BEGIN");
      Serial.println("Enter character for control option:");
      Serial.println("s : to send message");
      Serial.println();
      delay(100);
    }

    void loop()
    {
      if (digitalRead(in))
        IN();
      if (digitalRead(out))
        OUT();

      if (count <= 0)
      {
        lcd.clear();
        digitalWrite(relay, LOW);
        lcd.clear();
        lcd.print("Nobody In Room");
        lcd.setCursor(0, 1);
        lcd.print("Light Is Off");
        delay(200);
      }
      else
        digitalWrite(relay, HIGH);

      if (count >= 3)
      {
        SendMessage();

        digitalWrite(relay, HIGH);
        delay(100);
        lcd.clear();
        lcd.print("Limit exceeded");
        lcd.setCursor(0, 1);
        lcd.print(count);
        return;
      }
      //else
      //  digitalWrite(relay, LOW);

      if (Serial.available() > 0)
        switch (Serial.read())
        {
          case 's':
            SendMessage();
            break;
          case 'r':
            ReceiveMessage();
            break;
        }
      if (mySerial.available() > 0)
        Serial.write(mySerial.read());
    }

    void SendMessage()
    {
      mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
      delay(1000);  // Delay of 1000 milli seconds or 1 second
      mySerial.println("AT+CMGS=\"+918419906897\"\r"); // Replace x with mobile number
      delay(1000);
      mySerial.println("GSM TEST:Limit of the room exceeded");// The SMS text you want to send
      delay(100);
      mySerial.println((char)26);// ASCII code of CTRL+Z
      delay(1000);
      //Serial.end();
    }

    void ReceiveMessage()
    {
      mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to recieve a live SMS
      delay(1000);
      if (mySerial.available() > 0)
      {
        msg = mySerial.read();
        Serial.print(msg);
      }
    }

    void Response()
    {
      int count = 0;
      Serial.println();
      while (1)
      {
        if (Serial.available())
        {
          char data = Serial.read();
          if (data == 'K') {
            Serial.println("OK");
            break;
          }
          if (data == 'R') {
            Serial.println("GSM Not Working");
            break;
          }
        }
        count++;
        delay(10);
        if (count == 1000) {
          Serial.println("GSM not Found");
          break;
        }
      }
    }

title: IR sensor not incrementing or decrementing inside the loop

Answers: 1

body:
Check that the GSM module is wired correctly, is setup correctly and that you get a ringing tone when you call that number from a different number.
If that is all okay, write / copy a sketch from one of the many online tutorials that sends an SMS taking all input from the serial monitor of the Arduino IDE. When that is working, transfer that code into the sketch above.
The *return* statement in your code will exit the loop() function within the sketch, but the C code running your sketch will just invoke your sketch again. Also, good practise says it's best not to include a function that is not actually used in the sketch - examples being the ReceiveMessage() and Response() functions.


body:
I am a newby to the world of electronics and IC chips, and am looking to make an ATMEGA328 based board to monitor 12v batteries. The board will be powered from the batteries being monitored, with a regulated power supply taking 12v input and outputting 5v to the board.
The data sheet for the ATMEGA328 chip says that AVcc should be connected externally to Vcc via a low-pass filter. A bit of internetting tells me the low-pass filter will filter out noise above a specific frequency, and provides links to calculators that show the affect of different resistor / capacitor pairs.

My problem is that, I have no idea what frequencies I need to filter! All / any advice much appreciated.

Further info: voltage measurements will be via voltage divider circuits, amp hour consumption will be via sensors, all of which will be connected to analog pins for ADC conversion.

title: ATMEGA AVcc pin - low pass filter

Answers: 1

body:
The filter is only needed if low noise is important to your application.
For monitoring batteries, you probably don't need the accuracy level at
which you would want the filter. For what it's worth, the Arduino Uno
doesn't have such filter: it's AVCC is connected straight to VCC.

If you really want the filter, the exact characteristics are not
critical. The datasheet suggests 10 µH + 100 nF, so this
should be a safe choice.

------------------------------------------------------------------------

**Edit**: To answer the question in the comment, yes, it is generally
advised to use decoupling capacitors, usually something like
100 nF, even when powered from a voltage regulator.

Notice that both the VCC and the AVCC pins are very close to a ground
pin. Best practice is to use one decoupling cap for each (A)VCC/GND
pair, and to place that cap as close as possible to the pins.


body:
I am new to electronics. I am going to play a sound truck from SD card when user push a button, Well This is very easy and there are lots of methods and codes to play it. the problem is with sound quality. I want to output sound into an speaker using 2.5 mm jack. here the problem appears. Is there any module which outputs Arduinos to speakers?

To me more clear in this tutorial https://www.instructables.com/id/Audio-Player-Using-Arduino-With-Micro-SD-Card/ we can play sound using simple speakers, is it possible to connect it to a higher quality speaker? like those pc speakers using 2.5 mm jack?
In fact I want to get better sound quality than the above tutorial using adrino.
thanks

title: Arduino uno audio output quality improvement

Answers: 1

body:
If a beginner, it is always better to copy then invent.  That said, I would recommend using [this arduino.cc Simple Audio Player tutorial][1].  There are [many different types of Arduino boards][2].  The Arduino Due uses a [Microchip/Atmel SAM3X8E ARM Cortex-M3 CPU][3] which contains at least one [DAC][4].  It is assumed this will produce better sound than the [PWM][5] output of the slower [ATmega328P][6] processor found on an Arduino Uno.

  [1]: https://www.arduino.cc/en/Tutorial/SimpleAudioPlayer
  [2]: https://www.arduino.cc/en/Products/Compare
  [3]: http://ww1.microchip.com/downloads/en/devicedoc/atmel-11057-32-bit-cortex-m3-microcontroller-sam3x-sam3a_datasheet.pdf
  [4]: https://en.wikipedia.org/wiki/Digital-to-analog_converter
  [5]: https://en.wikipedia.org/wiki/Pulse-width_modulation
  [6]: http://www.microchip.com/wwwproducts/en/atmega328p


body:
I am trying to use Process.h library to run a shell command. Here is my code. I am using Arduino Uno.

    #include <Process.h>
    #include <Bridge.h>

    void setup() {
      // Initialize Bridge
      //Bridge.begin(115200);

      // Initialize Serial
      Serial.begin(115200);

      // Wait until a Serial Monitor is connected.
      while (!Serial);

      // run various example processes
      runPythonFunction();
    }

    void loop() {
      // Do nothing here.
    }

    void runPythonFunction() {

      Process p;        // Create a process and call it "p"
      //p.begin("/usr/bin/python /home/kairos/Arduino/codes/sketch_jan26a/tweet.py");
      p.runShellCommandAsynchronously("/usr/bin/python -U /path/to/tweet.py");      // Run the process and wait for its termination
      //p.run();
      // Print command output on the SerialUSB.
      // A process output can be read with the stream methods
      while(p.available() > 0) {
         char c = p.read();
        Serial.print(c);
      }
      // Ensure the last bit of data is sent.
      Serial.flush();
      delay(300000);
    }

If I do not comment the `Bridge.begin()` line, then in monitor display reverse question marks are displayed. And after commenting that, I am getting some garbage on the serial monitor. Also, my python script makes a new file in the same directory, which runs fine if I run it using a terminal. But if I run it using Arduino code, I am not able to see that new file being generated.

Even using `p.begin()` and `p.run()`it does not run. Nor using `p.runShellCommandAsynchronously()`.

So how can I run that python script?

title: Running python script using Arduino

Answers: 1

body:
The Uno cannot run python.

The Bridge library is intended for communication either between the two MCUs of the Yun, or between an Arduino board and the MCU on a Yun shield.

It is literally a Bridge between the two systems - Arduino and the Linux system in the Yun.