text:
Powering an Arduino Mini Pro using a CR2032 battery as a remote control
I'm looking into making my own remote control using an Arduino Mini Pro and some RF transceivers. The receiving end won't be a problem, but the remote will. I want to make it as small as possible and consume as little energy as possible.
Is it possible to turn on the Arduino Mini Pro at the push of a button, while also using that same button to trigger a piece of code? That way I can cut the power when it's not being pressed.
I will make sure to code it, so I have to hold the button down for 1-1.5 seconds, so it has time to "boot up" and send the RF signal, but should power off immediately when I let go of the button.
What kind of power should I expect from a single CR2032 battery? I have a couple of NRF24L01 RF transceivers laying around together with an Arduino Mini Pro.
If we assume this, while looking at this sheet:
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.

You should take a look at ATmega328P datasheet

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
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. 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. 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 reference I posted above, power consumption for Arduino should be 0.90 mA. At the item 5.1 of nRF24L01+ datasheet, 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.

Thanks for your reply! The 16 hours would mean when it's actually bursting RF signals out into the air, right? So I could power the ATmega328P Arduino Mini Pro and the RF signal for 16 hours before the battery is completely drained (if we assume it stays at 3v all the time)? Would it be efficient enough to simply sleep the ATmega328P, then wake up with the push of a button? Would that keep the CR2032 battery running long enough, so I can use this for months?

I uptated the answer.

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.

simulate this circuit – Schematic created using CircuitLab
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.

simulate this circuit
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

simulate this circuit
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)

simulate this circuit
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)


text:
LCD Clock Millis Code Issue
I am trying to create a clock on an LCD when I upload the code below, all it displays is a very rapidly flashing 0:00 PM. Please help. This is my first time using Millis.
#include <LiquidCrystal.h>   //includes LCD display library in sketch
LiquidCrystal lcd(27,26,25,24,23,22);   //determines pins of the LCD display
int seconds = 0;    //generates integer storing seconds
int minutes = 0;    //generates integer storing and showing minutes
int hours = 12;      //generates integer storing hours in 24 hour mode
int displayHours;      //generates integer displaying hours in 12 hour mode
unsigned long previousMillis = 0;   //creates a variable to store the amount of milliseconds since last update
const long interval = 1000;    //generates integer to find 1 second interval

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

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

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

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

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

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

source: Stack Exchange

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

sort: votes


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

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

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

                                ^

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

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

  ^

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

collect2.exe: error: ld returned 1 exit status

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

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

Below is the sketch I'm attempting to upload:
/*
 * Displays Sparkfun CCS811 data on a Serial enabled LCD sent over I2C.
 */
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

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

#include "SparkFunCCS811.h"

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

CCS811 mySensor(CCS811_ADDR);

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

}

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

  }

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

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

}

The first error seems, as if the library wants another parameter type for it's constructor. For more help you should provide your code and the library you used for this (when not buildin of the Arduino IDE please provide a link)

Your code compile OK with Arduino 1.8.5.

This worked for you? I'll have to see what version of Arduino I'm running.

I am assuming you are using this library, 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

Thank you, Jose. I will change these two lines when I get home and see what happens!

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


text:
bit_is_clear(ACSR, ACO) Instead of digital_read(1)==LOW
I am attempting to create a program for the atmega328P which will enable the aux input of a Toyota Corolla stereo. In order to do this, I'm bitbanging AVC LAN. Nearly all of my research comes from this site:
https://github.com/halleysfifthinc/Toyota-AVC-LAN
In this example, Frigon has wired his Atmega8 in a peculiar way. Instead of connecting the + terminal directly to a single pin of his Atmega8, he's connected it to a pulldown resistor, resisted it to the - terminal (presumably for bus termination) and a digital pin as well as an analog pin. The - terminal has been given similar strange treatment.
In his function ReadBits(), he waits for a physical 1, then sets a timer and waits for a physical 0 to measure the length of the pulse. But when he does this, he uses the equivalent of
while ( bit_is_clear( ACSR, ACO ) );

That's completely Greek to me. Does this have something to do with something called in Internal Analog Comparator?
I attempted to create something similar using
while( digitalRead( 2 ) );

but I'm reading static as well as honest-to-goodness pulses. I assume that, anyways, because I'm getting pulses of length 2-7 ticks when many are closer to 20-40 ticks (measured using TCNT0 with no custom prescaler).
So... what exactly is he doing with ACSR and ACO? Why is his + and - terminals connected to more than one pin? Why are his diodes there?
=========================EDIT=======================
Following Edgar's advice, I've reworked my schematic and code to closely match Frigon's work. Below is my code:
#include <avr/wdt.h>

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

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

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

byte data[255];

void setup() {
  LedOff();

  Serial.begin(9600);

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

  //two second watchdog
  wdt_enable( WDTO_2S );

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

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

void loop() {
  wdt_reset();
  if (INPUT_IS_CLEAR) LedOff();
  else LedOn();
}

Schematic: https://i.stack.imgur.com/0UNzF.jpg
(mistake on the schematic - I connected 5v to vcc and ground to ground)
If it matters, I'm powering the head unit and the arduino from the 12v and 5v rails of an ATX power supply. They both take the same ground.
My code should theoretically only turn on my led whenever the head unit broadcasts bits, but it's just sort of erratically blipping on and off or fading gently at random. I've triple checked my wiring (breadboard if that matters). Why is this happening? Is there something about bit_is_clear(ACSR,ACO) that I don't understand?

Oh dear, the Wayback Machine. Sympathetic to your problem as I am, your question already refers to a link-dead site which is why you are using the Wayback Machine. Who knows how long that will last? Please post (edit your question) to include the schematics you are talking about, and the code. As it is you are saying "some link-dead site has a schematic and some code, how does it work?". Even if we answer, how useful will the answer be if the Wayback Machine goes down?

Done. Didn't think about the wayback machine dying out.

No, you haven't included the schematic nor the code in the question. If you dump it to your disk, then edit the question and include it, then the question will stand whether or not the Wayback Machine goes down, or any other site (excepting this one, of course, but then the question won't exist either).

The code is large and separated into multiple files. I'm not trying to make this post impossibly large.

About your recent edit: 1. “leave the pins tri-stated” means they should be set as inputs. 2. The analog comparator compares the potentials of the pins AIN0 (digital 6 on the Uno, not A0) and AIN1 (digital 7). Frigon has these pins connected to the AVC bus, whereas on your schematic they are left floating, so they only pick up noise.

Changing the pins is all I needed. I misinterpreted the pinout. I'm capturing messages like a champ now. Thank you so much.

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.

Thank you. I'll revise my approach and give that a shot. I deviated from the original work because I didn't understand it (and I really hate doing something without understanding it). To that end, is there anywhere I can read about the ACSR and ACO registers (and the comparator) in greater detail? Besides the 328P datasheet of course... That's a little too dense for me to work with...

If you narrow down your view of the datasheet to the page that mentions that register it isn't too bad. However I do find the explanation there rather obscure: "Bit 5 – ACO: Analog Comparator Output - The output of the Analog Comparator is synchronized and then directly connected to ACO. The synchronization introduces a delay of 1 - 2 clock cycles."

Edited original post with a followup on my issue after taking Edgar's advice.


text:
MPU9250+arduino pro micro strange behaviour after reset
I have an arduino pro micro + mpu9250. For test sketch I'm using https://github.com/sparkfun/SparkFun_MPU-9250-DMP_Arduino_Library
It works as intended after the first sketch upload. After that if I unplug usb cable thus cutting the both devices power and plug back - the fun starts here) My sketch is working, but this time the response from mpu9250 is like 10 times slower. Here is the weird part - it still works, but just shows the data slower in Serial Monitor and the led blinks are slower. What am I doing wrong?
Here is the example I'm using(from the library mentioned above):
    /* MPU9250 Basic Example Code
 by: Kris Winer
 date: April 1, 2014
 license: Beerware - Use this code however you'd like. If you
 find it useful you can buy me a beer some time.
 Modified by Brent Wilkins July 19, 2016

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

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

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

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

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

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

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

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

MPU9250 myIMU;

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

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

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

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

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

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

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

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

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

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

#ifdef LCD
    display.clearDisplay();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

#ifdef LCD
      display.clearDisplay();

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

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

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

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

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

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

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

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.


text:
Why Commenting Serial.print() gives me a different value?
I am working on with Cypress and Arduino.I am trying to transfer the data from cypress and printing it to the Serial Monitor or Arduino. but the thing is when I am using Serial.print(j) it is showing the right value of i (See in the code about what is i and j), but when I comment or remove Serial.print(j) it is showing the wrong value of i
For example, suppose cypress is sending data 00001934a
and then I am reading this value using
int j = mySerial.read()-'0';
// -'0' is for chaging ascii data to normal integer
//for example ascii value of `0` is 48
//so mySerial will read 48
// and exprerssion value will become `48-48 = 0`

My code
#include <SoftwareSerial.h>

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

mySerial.begin(4800);
}

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

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

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

when the line is not commented the output was
0
0
0
0
1
9
3
4
49
193 //this is the value of i which is correct one

but when I comment the line Serial.println(j) the output was
   14569 // I don't know what the hack is this.

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

Your code doesn't compile. Post a complete, minimal, working sample that show the problem.

Try now, I have only shown the problem, not all code, but still, it is compilable.

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

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.

The problem is that the sketch he posted is not the real sketch.

Please, Wait for some time, I'll post the real code.

That's a shame. However, if he's (as he probably is) doing the same thing in the "real" sketch (his post belies a fundamental lack of understanding of serial reading) then this is still likely the problem.

Sir, I know how the read(), function is working, it is reading one char like 0 and printing its ascii value to the serial montior. thats why I am using a flag, so that i an see the break in my data.

Except if that char hasn't arrived - it returns -1 instead (255 when mapped to an unsigned 8 bit value).

@Majenko. And why we are here solving elementary programming questions? This question is not really about Arduino.

I have used if(mySerial.available()>0){Serial.print("something"); }to check wheather the data is coming or not

Yes - if there is one character available then try and read 8. That is wrong. Very very wrong. Read the blog post I linked to.

I should make it more understandable.I think.

@meditat. It's simple: post the code that outputs the values you show in your question. The last version of your sketch doesn't produce the values you posted. Until that we are just speculating.

@LookAlterno: According to my test, it does produce the value posted.

@EdgarBonet. My test output 1
-49
-49
-49
-49
2
-49
-49
-49
3
-49
-49
-49
-49
49
-1239-1239 forever

Oh look. All those -49s. Looks like -1 - '0' to me...

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.

No j  is updating each time using j = mySerial.read()-'0';everytime.

The while(j!=49) never end because j nevert change inside that while.

yup i think so, that should be inside while, let me check and edit.Check now sir.

Just post your real sketch!


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

Like button1[3]=readAndDebounce(PIN_BUTTON1);?

is it possible to show your wiring pattern?

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.

thanks a lot. It helped me store the button sequence. If you can please suggest me how can I blink the LEDs in same sequence as stored in the array with an delay of 500 millisecond. I am posting my code in the answer section please have a look.

The delay of 500 ms might be tricky. That means that for every button you press, you also have to store the time. So you can check if 500 ms have been passed since that press and blink the corresponding LED. Maybe it helps do create the program first for one button and one LED (with 500 ms delay) and than add more buttons/LEDs. Mostly it's better to gradually extend the program instead of going directly to the end goal.

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

  }


text:
How to program a BSFrance LoRA32u4 from Arduine IDE 8.5?
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?

I give +1 for a well document and written question.

which board should be selected

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.

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.

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


text:
Atmega328P Prescaler to Microseconds
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?

Note that the rollover is not an issue. The limited resolution of micros() (4 µs) could be.

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

I've set my prescaler and I'm on my way. Thank you. I don't fully understand how it works, still, but I'm reading about it.


text:
Problem with action that should happen in loop(continuously)
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:
//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

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.

So if i want all of these actions to happen in a loop, i have to put them into loop and just receive the state of button of the app by using BLYNK_WRITE()?

You probably want to have a global variable in your sketch that holds the virtual pin state. You use the BLYNK_WRITE() function to update that global variable, as that function is only called when the app sends new information to the hardware.


text:
Why was the Atmega16U2 used on the Arduino UNO as a USB to Serial converter?
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?

FTDI is more expensive than the 16U2 AFAIK. Examples of reprogramming it are: to use it as a USB MIDI device or HID.

@Wesley Lee How do you actually reprogram it though?

There is a separate ISP/ICSP header for it. Then use something like an Arduino as ISP, Atmel ICE, etc (I have no time now, but I might bbe able to write an answer and post photos soon)

First reason I'd guess is price:

FT232 on octopart: USD2.65 ~ 3
Atmega16U2 on octopart: 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, 2, 3. 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.

Use the ISP pins by the Atmega16U2:

"They can probably get much better deals" -- I wouldn't be surprised if part of this decision was that Atmel offered the Arduino team a sweetheart deal on that part.

@duskwuff -- True, it could have been the other way around!


text:
Measuring Lithium ion cell voltage used to power Arduino via a boost module
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.

Sidenote: why are you boosting the voltage to 9V (and presumably using the voltage regulator on the nano to bring it back to 5V)?

@Gerben Because the lithium ion cell voltage can be in the range of 3-4.2 volts depending upon the charge level. So to operate the analog circuit  (using LM358) and Arduino nano at a stable voltage I have to boost the input voltage. Plus the XL6009 module will keep the output voltage stable at 9V regardless of the input voltage.

I'm the author of a library called BatterySense 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...

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
Add a connection from the battery positive terminal going into one of the Arduino analog pins
Use the BatterySense library to get the battery voltage and percentage level

Thanks so much OP and Roberto. I also want to measure a LiPo that is powering my Arduino. Great library, I've just checked it out. I suspect that I have the case where my battery negative terminal is not directly connected to GND, as part of the design, sot hat an over-discharge protection IC can do it's job. Any suggestions for that scenario? Here's the Circuit and PCB
https://easyeda.com/GreatScott/LiPoChargeProtectBoost_copy-3d9f4c3ddc7347d7861776340b9b90b7 which is linked to from GreatScott!'s excellent youtube video here https://www.youtube.com/watch?v=Fj0XuYiE7HU

I believe you might get more visibility if you post a proper question rather than a comment, may be referring to this question and answer in yours... I don’t know how you can work around with a non shared GND, but I’ll definitely interested in the answers you’ll get ;-)

Thanks Robert, that's a great suggestion. I'll experiment with measuring the voltage with and without the over-discharge protection IC, trying it anyway, as I suspect the arduino will only be measuring the voltage when it's actually on, and therefore connected to ground via the MOSFET that the protection IC turns on and off. If it gives weird results / there's some difference in the measured battery voltage, then I'll post a new question. Thanks again, will tag you / this!

Cool library guy. +1


text:
IR sensor not incrementing or decrementing inside the loop
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;
    }
  }
}

your description of the problem is unclear. i am unable to understand which part works and which part does not work.

Why do you use so many long delays? You wait for 1 second everytime a person comes in or out. This blocks all other code, that could be running

Actual problm is when the limit of persons exceeds a msg must b sent to admin so i gave it inside loop a if condition bt the prblm is once the limit exceeds msg is sent bt i cant increment or decrement no. Of peraons manually. It is not coming out of if condition  @jsotola

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.

Can u plzz send me the right code


text:
ATMEGA AVcc pin - low pass filter
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.

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.

many thanks for this, and apologies for not spotting this in the data sheet. If I choose not to insert the low pass filter, would there be any benefit in fitting a low value capacitor, to smooth the AVcc input, or should I expect the output from the regulated voltage supply to be okay?


text:
Arduino uno audio output quality improvement
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

The problem isn't the speakers, but that an Arduino is a terrible sound generator regardless of what you drive with it.  You can ironically do quite a bit better with an ATtiny85.  Otherwise you need something with an actual DAC.  Not sure who dowvnoted your question, but they have a point - there are many project writeups out there online, no need to ask a question here, especially when it is one which is too broad to fit the mission of this site.

I did not down vote your question.  However it is likely that it was down voted because you are not asking about a specific problem.  I would suggest you delete this question, go out and try something (your link is an excellent starting point) then come back with a well formed question about a specific problem or improvement.  Remember, none of the stackexchange web sites are good for discussions.   They are designed to create a data base of well defined questions and concise answers.

...I've changed my mind.  Instead of deleting your question - ask a more specific question about how to get better sound quality than is possible from the example you linked to.

@st2000 thanks very much. I updated my question

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

thanks, how can I improve its quality? for example output the audio to an amplifier ?is there any key words which I can search?

The Simple Audio Player example I linked to in the answer uses an Arduino Due which contains at least 1 DAC.  This likely is an improvement in sound quality over the Arduino Uno which has no DAC, only PWM.  Futher, the Simple Audio Player example uses an OpAmp which appears to be driving a small speaker.  The example I linked to in the answer should have better sound quality then the example you linked to in your question.

I've re-read your question.  If you want to stick with the Arduino Uno and still want good quality sound you will likely need to push all sound related hardware and processing off the Arduino Uno board as the Arduno Uno is not powerful enough to handle the necessary data nor does it have a DAC.  Consider this board.

can't I simply connect the speakers output to an external amplifier? for example connect it using a jack to an speaker with internal amplifier?


text:
Running python script using Arduino
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?

Do you have a Yun shield on your Uno?

I am actually using SparkFun Redboard, same as this https://www.robotshop.com/en/sparkfun-inventors-kit-v40.html?gclid=EAIaIQobChMIx8S-n9f42AIVS7jACh16PgRVEAQYAyABEgJc5fD_BwE

Do you have a Yun shield plugged into your SparkFun Redboard?

No, I have directly connected the board to the computer.

Was your intention to make your Arduino trigger the execution of a Python script which is on your computer?

yes, that was what I wanted to

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.

Is there any way I can run a python script?

I knew you were going to ask that. Buy a Yun.

Don't buy a Yún, it is an endless source of troubles. Buy a Raspberry Pi, and you have a full linux operating system for less money.

Tried it with Rpi, completed it in 20min, the same task that I was trying from two days #hackathon


text:
Using INT2/3 on Arduino Micro (Atmega32u4)
My project is using almost all the pins on this board and I require an interrupt pin to read radio state (rather than polling). I'm using I2C, so that leaves INT2 and INT3, which are the TX and RX pins for USB/Serial1. According to the documentation, disabling serial, using Serial.end(), should allow me to take control of those pins. However, using the pins as interrupt handlers doesn't work. Here is a sample sketch:
static int ledpin = 13;
volatile byte state = LOW;

void func()
{
  state = !state;
}

void setup() {
  Serial.end();

  pinMode(ledpin, OUTPUT);

  // INT2
  pinMode(0, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(0), func, CHANGE);

  // INT3
  pinMode(1, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(1), func, CHANGE);
}

void loop() {
  digitalWrite(ledpin, state);
}

This example is mostly copy-pasted from the Arduino website. All the other interrupts work fine, only INT2 and INT3 don't.
Is there a way to use these interrupts?

How do you know that they don't work? If both interrupts are fired, then you can't notice it. "Serial" is the serial port via USB to the computer. "Serial1" is the hardware serial port at pin 0 and 1. If you don't use "Serial1", then pin 0 and 1 are not yet initialized as serial port and they are normal digital pins like any other. Remove the Serial.end. It should work, you could increment a byte and print the byte to the serial monitor (using the USB "Serial"). There are also pcint interrupts: http://www.pighixxx.com/test/portfolio-items/micro/ Is !LOW the same as HIGH, or is that a guess.

You problem isn't with your pins or code, but with debouncing the signals. I've changed the "func()" method to read:
void func()
{
  static uint32_t lastChange = 0; // Note millis() don't change inside ISR, but can be read
  if (millis() - lastChange > 100)
  {
    state = !state;
  }
  lastChange = millis(); // Set new value
}

which will ignore spurious interrupts if they occur within 100ms of each other. This solves the issue that you are seeing, I've tested it on an Arduino Micro I have lying around.

/*
   2019-08-29 Nicola Bernardelli. Going through the ATmega32U4 Datasheet and applying the steps
   to set up the analog comparator on a Pro Micro board.

   While doing this, I understand that the Analog to Digital Converter must be switched off.
   So, if you are needing to stick with ATmega32U4 but also need the ADC (as I do in my current project), you might have to add a
   circuit with a comparator, e.g. LM393 or LM339, instead of using the built-in Analog Comparator.
   Disabling this interrupt and reactivating the ADC has not been added to this sketch.

   Also, a "real" handling of the interrupt-triggered event has not been added and the sketch leaves the possibility of a very fast
   succession of interrupt requests. You might want to check the (currently only one) answer given here:
   https://arduino.stackexchange.com/questions/49195/using-int2-3-on-arduino-micro-atmega32u4

   [I wanted to ask/contribute here https://arduino.stackexchange.com/questions/17480/using-analog-comparator-on-atmega32u4
   (I see that it is 3 years 9 months old but it's still "searchable" on the Internet, which is how I went there. I think that keeping the
   information under that pertinent title is a better option than opening a new thread.)
   So I created an account, but it turns out that I don't have enough "reputation" there to comment, so I wrote into the edit field
   available to give an answer, and that did not work out either:
   "Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed,
   posting an answer now requires 10 reputation on this site (the association bonus does not count)."
   So... pretty much chessmate. Well... their board, their rules.]
*/

#include "Arduino.h"

#ifndef ARDUINO_AVR_PROMICRO
#error This sketch is meant for the Arduino Pro Micro, it is based on the ATmega32U4 Datasheet and the Pro Micro pinout. \
       You might decide to try it on a different ATmega32U4-based board if the pins choice is OK (please check/change the LED pin number).
#endif

#define THIS_BOARD_LED_BUILTIN 17
#define LED_ON_DURATION 200

volatile bool analogCompInterruptToggled;
unsigned long millisLastTrigger;

void setup() {

  Serial.begin(9600);

  analogCompInterruptToggled = false;
  millisLastTrigger = 0;
  pinMode(THIS_BOARD_LED_BUILTIN, OUTPUT);
  digitalWrite(THIS_BOARD_LED_BUILTIN, HIGH);

  /* As per Atmega32U4 Datasheet starting pag 293 (and linked pages). */

  PRR0 &= ~bit(PRADC); // Disables power reduction for the ADC in order to use the ADC input MUX.

  /*
     ACME in ADCSRB: When this bit is written logic one and the ADC is switched off (ADEN in ADCSRA is zero),
     the ADC multiplexer is connected to the negative input to the Analog Comparator. When this bit is written
     logic zero, the Bandgap reference is connected to the negative input of the Analog Comparator
  */
  ADCSRA &= ~bit(ADEN); /* Switches off the ADC so we can use the Muxer with the Analog Comparator instead of the ADC. */
  ADCSRB |= bit(ACME);  /* With the line above => the ADC multiplexer is connected to the negative input of the Analog Comparator. */
                        /* See table at page 295: ACME 0 or (ACME 1 and ADEN 1) => bandgap ref as the Analog Comparator Negative Input. */

  /*                                        ******** A0 NEGATIVE INPUT ********
     Let's select pin ADC7 = A0 as the negative input to the Analog Comparator, as per pag 295 of the ATmega32U4 DataSheet:
     ACME to 1 done above, ADEN to 0 done above, MUX2..0 to 111.
  */
  ADMUX |= 0b00000111;

  /*                                        ******** D7 POSITIVE INPUT ********
     When this bit is set, a fixed bandgap reference voltage replaces the positive input to the Analog Comparator.
     When this bit is cleared, AIN0 is applied to the positive input of the Analog Comparator.
  */
  ACSR &= ~bit(ACBG); // AIN0 = D7 => positive input of the Analog Comparator

  /* Pages 294-295 of the ATmega32U4 Datasheet. */
  ACSR &= ~bit(ACIC); /* Analog Comparator Input Capture disabled. */

  /* Comparator Interrupt trigger mode. 0-0 => TOGGLE, meaning any change; 1-0 => FALLING; 1-1 => RISING). */
  // ACSR &= ~bit(ACIS1); ACSR &= ~bit(ACIS0); // TOGGLE
  // ACSR |= bit(ACIS1);  ACSR &= ~bit(ACIS0); // FALLING
     ACSR |= bit(ACIS1);  ACSR |= bit(ACIS0);  // RISING

  DIDR1 &= ~bit(AIN0D); /* It's actually the rightmost bit, we could write DIDR1 &= ~1 */
  /*
     When this bit is written logic one, the digital input buffer on the AIN0 pin is disabled. [...]
     When an analog signal is applied to the AIN0 pin and the digital input from this pin is not needed,
     this bit should be written logic one to reduce power consumption in the digital input buffer.
  */

  ACSR |= bit(ACIE);
  SREG |= bit(SREG_I);
  /* When the ACIE bit is written logic one and the I-bit in the Status Register is set,
     the Analog Comparator interrupt is activated. When written logic zero, the interrupt is disabled.
  */
}

ISR(ANALOG_COMP_vect) {
  analogCompInterruptToggled = true;
}

void loop() {
  // put your main code here, to run repeatedly:
  if (analogCompInterruptToggled) {
    analogCompInterruptToggled = false;
    digitalWrite(THIS_BOARD_LED_BUILTIN, LOW);
    millisLastTrigger = millis();
    Serial.print("toggled - millis() == ");
    Serial.println(millisLastTrigger);
  }
  else if (millis() > millisLastTrigger + LED_ON_DURATION) {
    digitalWrite(THIS_BOARD_LED_BUILTIN, HIGH);
  }
}