text:
millis and micros always returns 0 (or other constant)
On an Arduino Uno, I have a sketch akin to this:
void setup()
{
    // Generate some PWM signal on Pin 5, using Timer 0.
    pinMode(5, OUTPUT);
    TCCR0A = 0b00110011;
    TCCR0B = 0b00001000;
    OCR0A = 0x80;
    OCR0B = 0x20;
    TIMSK0 = 0b00000100;

    Serial.begin(115200);
}
void loop()
{
    // Just write the result of millis to the terminal.
    unsigned long ms = millis();
    char s[100];
    sprintf(s, "%lu\r\n", ms);
    Serial.print(s);
}

Setup timer 0 to generate a PWM signal, setup the serial port, constantly print the result of millis() to the terminal.
The numbers printed to the console do not increase as expected, but stay "0".
Similarly, if I use micros, "4" is printed constantly.
How's that?

millis and micros appear to use timer 0 internally. Using that timer to also generate a PWM signal messes with their ability to function properly.
The solution is to either use a different timer to generate the PWM signal, or to roll a custom equivalent of those functions.
Why does the official arduino documentation not specify that millis and micros occupy timer 0?
Why are there no Google results mentioning timer 0 when searching for "arduino millis returns 0", "arduino millis constant", "arduino millis not counting" and the like? (There are results with the same symptoms, but for different reasons.)
Who knows.

PWM with analogWrite() and millis() work together on Uno if you don't change Timer0. every ATmega timer handles a pair of pins. Timer0 has 5 and 6 on Uno/Nano/Mini https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/#_notes_and_warnings

You are supposed to use analogWrite() for generating the PWM, and only access the low-level peripherals if you know what you are doing. I agree that mentioning Timer 0 in the millis() doc would be good. Note that a google search on “millis timer 0” return many relevant results.

@Juraj analogWrite does not allow changing the period (because that would then mess with how fast millis would count). But thanks for mentioning it; others might find it useful for there purpose.

In 2014 I wrote a library to use Timer 2 as a millis()/micros() replacement. You can read about it on my personal website here: https://www.electricrcaircraftguy.com/2014/02/Timer2Counter-more-precise-Arduino-micros-function.html. If you use this, you could use Timer 0 for whatever you want. Granted, Timer 2 and Timer 0 are both 8 bit timers with the same level of functionality, so there's no real advantage to using one over the other for timing, but my implementation has 0.5us resolution instead of 4us resolution (8x better) at the cost of more frequent ~4~5us jitter (8x more frequent).

Regarding which timer does what, you have to get in the habit of looking at the source code to see when, how, and why hardware resources like timers and counters, input capture, output compare, UARTs, watchdog timers, external interrupts, pin change interrupts, etc., are being used. Just off the top of my head: millis()/micros() is timer 0, servo library is timer1, tone library is timer 2 I think, etc.

Why does the official arduino documentation not specify that millis and micros occupy timer 0? - probably one reason would be that this would vary from processor to processor. If you start fiddling with the hardware registers you might expect things to not behave as documented. For example, if you change the registers pertaining to serial output, then writing to Serial might not work.

@NickGammon That wouldn't stop me from writing that info down for each controller. Arduino (the company) knows which processors they have on their boards.


text:
Arduino reads hc-05 device connecting status
Hello I want to get an arduino get status of bluetooth hc 05 if connect with device or not . I'm trying by myself and search on internet website but I can't find useful things.

Can you show us the code you have written so far?

if (Serial1.available()) {   Serial1.print("AT+BIND");  Serial.println(Serial1.print("AT+BIND"));  }

This's one code of codes who I tryed .  The other codes mybe the same but with some differents order...

In hc05 there is led that shows you Bluetooth is paired or not. In datasheet it says that connected the PIO9 pin. You can connect this pin to arduino's digitial input pin. After that you can understand is it paired or not.
AT+BIND? gives you which device you currently paired.

If I connect PIO9 pin maybe it's get write in serial.read()  if it's connect or not ...?

No its not like that. When you paired this led turns on so if you make a little bit solder and you can get a wire from there and put this wire to arduino's digitial input pin. When Bluetooth paired this pin goes HIGH and if its not connected this pin goes LOW

Ok I edited the post check it again

Different Bluetooth adapters (using the HC-05 module) provide different signals, besides its Rx and Tx. Most bring out a "key" input that puts the module into command mode where serial communication is between the external pins and the module itself - 'AT' commands & queries to the module's firmware. When the module is not in command mode, the firmware just passes serial data through the Bluetooth radio, ignoring the content. Some provide an LED- or State signal that you can read (or observe on an LED) to know whether the devices is paired (communicating) or unpaired (in command mode).
On some, this is a simple logic signal; on others it is a square wave of 1/2 to 1 Hz which means your code has to track the signal to know whether it is static (typically High when paired) or toggling (for unpaired/waiting to pair).
You need to read your module's datasheet to find out the behavior of this signal on your particular module. If you connect an LED to this signal, or your module has one on the board, you can often make a good enough guess by observing it with a stopwatch. Either way, you then need an Arduino function that samples the LED periodically, remembering what state it saw and for how long, to decide whether the LED is blinking or is steady.

source: Stack Exchange

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

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

sort: votes


text:
Does enabling the Timer1 CompareA interrupt instantly triggers an interrupt?
I am learning Arduino interruptions and I am unable to explain the behavior of a minimalistic interrupt driven project. The project is the following: an Arduino UNO is connected to two LEDs, on ports 9 and 10, and a button on port 2. The button is listened to for RISING interruptions, which are expected to trigger the following 3 seconds sequence: LED1 HIGH (one second); both LEDs HIGH (one second); LED2 HIGH (one second); during which pressing the button should have no effect.
#define led1Pin 10
#define led2Pin 9
#define buttonPin 2

void setup() {

  cli();//stop interrupts

  pinMode(led1Pin, OUTPUT);
  pinMode(led2Pin, OUTPUT);
  pinMode(buttonPin, INPUT);
  digitalWrite(led1Pin, LOW);
  digitalWrite(led2Pin, LOW);
  attachInterrupt(digitalPinToInterrupt(buttonPin), f, RISING);

  TCCR0A = 0;// set TCCR2A register to 0
  TCCR0B = 0;// set TCCR2B register to 0 (sets timer0 prescaler values to "disable timer")
  TCCR2A = 0;// set TCCR2A register to 0
  TCCR2B = 0;// set TCCR2B register to 0 (sets timer2 prescaler values to "disable timer")

  //set timer1 interrupt at 1Hz
  TCCR1A = 0;// set TCCR1A register to 0
  TCCR1B = 0;// set TCCR1B register to 0

  // set compare match register for 1hz increments
  OCR1A = 15624;// = (16*10^6) / (1*1024) - 1
  TCCR1B |= (1 << WGM12);   // turn on CTC mode 1 (compare to OCR1A)
  TCCR1B |= (1 << CS12) | (1 << CS10);// CS12|CS10 => Prescaler 1024
  TIMSK1 = 0;// disable timer compare interrupt

  sei();
}

volatile int index=0;

volatile byte previousState=LOW;
volatile byte state = LOW;

void loop() {
  if (state && !previousState) {
    digitalWrite(led1Pin, HIGH); index=1;
    TCNT1H = 0;
    TCNT1L = 0; //initialize counter value to 0
    TIMSK1 |= (1 << OCIE1A); // enable timer compare interrupt
    previousState = HIGH;
  }
}

void f() {
  state = HIGH;
}

ISR(TIMER1_COMPA_vect){ //timer1 interrupt 1Hz
  switch(index) {
  case 1:
    digitalWrite(led2Pin, HIGH); index=2;
    break;
  case 2:
    digitalWrite(led1Pin, LOW); index=3;
    break;
  case 3:
    digitalWrite(led2Pin, LOW); index=0;
    state=LOW; previousState=LOW;
    TIMSK1 = 0;// disable timer compare interrupt
    break;
  default:
    break;
  }

}

Code adapted from https://www.instructables.com/id/Arduino-Timer-Interrupts/
Upon pressing the button, state is set to HIGH, which assuming previousState and state were LOW, should get the loop to perform a set of action once as it will set previousState HIGH.
These actions are the following: set led1Pin to HIGH, set TCNT1H and TCNT1L to 0, which should put the Timer1 counter to 0, and then set TIMSK1 to 0b00000010, that is, 1 << OCIE1A, to accept the interrupt when it will be triggered, supposedly one second from the instruction that set the counter to 0, as the timer fires interrupts at 1Hz.
But while the expected behaviour is LED 1 on for one second, both LEDs on for one second, then LED 2 on for one second, the observed behaviour is the following, from my tests:

First time pressing the button since Arduino reset : LED 1 and LED 2 on for one second, LED 2 on for one second.
Button presses properly ignored until LED 2 turns off.
Subsequent button presses : either proper behaviour (LED1 on, both LEDs on, LED2 on); or "first press" behaviour (both LEDs on, LED2 on). In both cases, the cycle sometimes instantly restart ([optional : LED1 on;] both LEDs on; LED2 on; LED1 on; both LEDs on; LED2 on), with each state taking one second.

The non-deterministic nature of the problem lets me think I'm mishandling interruptions. The project behaves as if enabling timer compare interrupts instantly triggered one, despite setting the relevant registers to 0 before that. I was unsuccessful in finding information regarding this that would explain the problem.
Is there asynchronous behaviour when setting the TCNT1H and TCNT1L registers to 0 ? Can a compare match interruption somehow be buffered ? And how comes the cycle sometimes execute twice ?

The project behaves as if enabling timer compare interrupts instantly
  triggered one

This can indeed happen, and it's likely what you are experiencing.
Explanation: an interrupt fires when three bits are simultaneously set:

the “interrupt flag” that signals the detection of some specific event
the “interrupt enable” bit associated with that particular interrupt
the “global interrupt enable” bit that is set by the sei()
instruction

In your case, the relevant interrupt flag is OCF1A (Timer/Counter1,
Output Compare A Match Flag), in register TIFR1 (Timer/Counter1
Interrupt Flag Register). This flag is raised by a “timer compare”
event, i.e. when the timer value hits the value stored in OCR1A. If
the interrupt fires, the flag is automatically cleared when the CPU
starts executing the corresponding ISR. Alternatively, the flag can be
cleared manually by overwriting it with a logic 1 (yes, that's kind of
backwards). It is worth noting that the flag records the compare events
whether or not the interrupt is enabled.
You normally expect the interrupt flag to be the last of these three
bits to be set, so that the interrupt is triggered by the compare event.
But this need not be the case. In your program, it is likely that the
interrupt flag is raised one second after startup. The global interrupt
enable is set by your sei() at the end of setup(). Thus, at this
point, as soon as you set the interrupt enable bit the interrupt fires
immediately.
The standard solution to this problem is to clear the interrupt flag
right before setting the interrupt enable bit:
TIFR1  |= _BV(OCF1A);   // clear timer compare flag
TIMSK1 |= _BV(OCIE1A);  // enable timer compare interrupt

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


text:
Help connecting ILI9341 LCD SPI Display to arduino uno
I got this lcd with touchscreen from a store but i have no idea on how to connect it to the arduino uno.
Any help is appreciated.
This is where i bought it from.
The display
My Arduino

your device uses two controllers. ILI9341 and XPT2046.

Maybe, then, you should buy your toys from somewhere that at least gives you a clue what to do with them. Anyway, the pins are clearly marked.

section 7.6 of the ILI9341 datasheet

@Majenko in romania this kind of resources are found in a very small amount of shops.

@jsotola i am new to this stuff, can you help me understand what is going on there?

@xM0nSt3r So buy from somewhere that isn't Romania?

@jsotola by resources i mean parts like lcds, arduinos or anything from this niche.

@jsotola i know it has that diagram but can i use transistors to lower the voltage instead that logic level translator?

why is your question so general?  please update your question to be more specific.  ask what you are really asking ... (deleting my useless comments) ....

do some research ... there is a lot of information on this website about converting 3.3V signals to 5V

@jsotola a'right i am going to look into it, thank you for your time.

You can get it working by two methods

using a voltage divider e.g to shift from 5V to 3.3V you could use two resistors, 100k and 200k respecfully and between both resistors there is voltage of 3.3. One for each pin that needs it.
Using 10K resistors in series between the LCD and the arduino. I really don't know how is working but it works fine that way.

I tested both methods, also the MISO pin from the LCD can be connected directly to your arduino.

Download and install a suitable library
Wire the display to the Arduino as per the markings on the display
Try some of the examples for the library you are using.

Can you give me more details about the wiring?

Read the words on the board and compare them to either the SPI manual page or the instructions for the library.

but can i use transistors to lower the voltage instead of that logic level translator?

Sorry, what are you talking about?

on the page i mentioned in the question it says i have to use this  to make it work, can i replace that with transistors?

Ah, it's a 3.3v display. You will need something to lower the 5V to 3.3V for the SPI signals. You may get away with resistive dividers, if you are lucky.

can you send me a link to those?

https://en.wikipedia.org/wiki/Voltage_divider

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


text:
Create member object using constructor arguments, or pass reference to object via constructor
I'm not entirely sure about the proper C++ terminology, so I'll just illustrate what I'm trying to achieve by giving a Java example since it should be pretty obvious:
public class LcdDecorator {
    private HD44780Lcd lcd;

    public LcdDecorator(int rows, int cols, int i2cAddress) {
        this.lcd = new HD44780Lcd(rows, cols, i2cAddress);
    }
}

or... alternatively...
public class LcdDecorator {
    private HD44780Lcd lcd;

    public LcdDecorator(HD44780Lcd lcd) {
        this.lcd = lcd;
    }
}

For what it's worth, there's no real concern about scope... LcdDecorator is a Singleton that gets created in setup(), then lives forever and gets used by loop() until the power gets shut off.
Here's what I've attempted so far:
LcdFacade.h:
#ifndef CORECONTROLLER_LCDFACADE_H
#define CORECONTROLLER_LCDACADE_H

#include <stdint.h>
#include "../.pio/libdeps/megaatmega2560/HD44780_LCD_PCF8574/src/HD44780_LCD_PCF8574.h"

class LcdFacade {

public:
    LcdFacade(uint8_t rows, uint8_t cols, uint8_t i2cAddress) ;
};

#endif //CORECONTROLLER_LCDFACADE_H

LcdFacade.cpp:
#include "LcdFacade.h"
#include "../.pio/libdeps/megaatmega2560/HD44780_LCD_PCF8574/src/HD44780_LCD_PCF8574.h"

HD44780LCD lcd;

LcdFacade::LcdFacade (uint8_t rows, uint8_t cols, uint8_t i2cAddress) : lcd{rows, cols, i2cAddress} {
    // ... the rest of the constructor goes here ...
}

note: I also tried using parentheses instead of braces for lcd's constructor:
LcdFacade::LcdFacade(uint8_t rows, uint8_t cols, uint8_t i2cAddress) : lcd(rows, cols, i2cAddress) {

In CLion, the 'lcd{rows, cols, i2caddress}' portion of the constructor in LcdFacade.cpp is red-underlined, and reports member initializer 'lcd' does not name a non-static data member or base class
Meanwhile, gcc(?) reports error: no matching function for call to 'HD44780LCD::HD44780LCD() on line 4 of LcdFacade.cpp.
Any ideas?

When you define
HD44780LCD lcd;

at global scope, you are creating a global variable that is initialized
before main() is called. In this case, it is initialized with the
default constructor HD44780LCD::HD44780LCD(), which does not exist,
hence the error. You could avoid this error by calling a suitable
constructor in the initialization, e.g.
HD44780LCD lcd(4, 20, 0x23);

but this may be inconvenient to you.
If you want to initialize lcd in the constructor of LcdFacade, then
it must be a non-static member of the class:
// In LcdFacade.h:
class LcdFacade {
public:
    LcdFacade(uint8_t rows, uint8_t cols, uint8_t i2cAddress);
private:
    HD44780LCD lcd;  // <- non-static member
};

// In LcdFacade.cpp:
LcdFacade::LcdFacade(uint8_t rows, uint8_t cols, uint8_t i2cAddress)
: lcd(rows, cols, i2cAddress) {
    ...
}


text:
Does avr-libc have any reason to word-align C++ class member variables?
This sounds straightforward enough, but I'm struggling to find a good answer.
Suppose I declare a C++ class with private members that collectively occupy an odd number of bytes. Say...
class Foo {
private:
    uint8_t bitflags;
    uint32_t millis;
}

or
class Foo {
private:
    uint8_t rawData[3];
}

If I compile it using GCC or Clang (possibly, wrapped inside the Arduino IDE, or multiply-wrapped inside PlatformIO, CMake, and an IDE like CLion), is there any likely scenario where the compiler (when targeting 8-bit AVR... specifically, the ATmega2560 on an Arduino Mega2560) would be inclined to add padding bytes to the portion of the class stored in SRAM? Say... between bitflags and millis, or between an instance of Foo and a uint64_t right after it?
If yes, what do I need to use to tell the compiler, "absolutely, positively DO NOT pad variables in SRAM (and, if you find yourself in a situation where it's seemingly unavoidable, at least output a prominent compile-time warning, if not an outright compilation-stopping error)?
Then... if I do that... are there any negative consequences to doing that with code that's targeting (and ultimately running upon) an 8-bit AVR?
As far as I know, 8-bit AVR has never had specific opcodes for copying a pair of consecutive bytes between registers and SRAM (I think, because Atmel literally ran out of opcode mapping space, and had nowhere to put hypothetical new opcodes like, "ldw rz, $f00d"), and movw only applied to pairs of registers... so, in theory, there's no reason for the compiler to "optimize" SRAM access to be word-aligned.
That said... I suppose it's not inconceivable that a compiler might default to word-alignment (even on platforms where it doesn't matter), just for the sake of ABI consistency between different platforms.
Before someone suggests, "try it and see!"... I've gotten far enough into learning C++ to know that with C++, you can't trust "compiles without errors and passes unit tests on my computer, with {this} IDE" as a general-purpose proof-of-correctness for C++ involving "implementation-defined" or "undefined" behavior. AFAIK, padding behavior is "implementation-defined".

Re “padding behavior is ’implementation-defined’”: My understanding is that it is defined by the ABI: the padding rules used in a compiled library must match those of the calling code. So you can try and see.

It didn't seem completely nuts to me that they could have chosen to align words in structs because they are passed in registers (if small enough) in the calling convention and because the pairs used by MOVW are always aligned in the sense that they're even:odd pairs (which also become aligned in the memory mapped register file (when it is mapped). That said, it doesn't appear (from tests) that they did this, probably because it wasn't worth bloating structures that may not ever be optimized with MOVW usages. I have no idea what sort of answer would satisfy this question.

OK, how about if I simplify it a bit, and we're talking about a class whose only member is a uint8_t[3]. Basically, I want to make sure that if I bend over backwards & do my own complicated bit-packing to make everything fit into 3 bytes, the compiler isn't going to just laugh at me and make it take 4 bytes anyway.

It kind of sounds like you're heading in the direction of something like a GCC extension __attribute__ ((__packed__)) or the #pragma or C++ attribute way (way; it's still non-standard) of specifying it, but really I don't know. I expect this attribute does nothing in avr-gcc because it would seem to be the normal behaviour in that compiler under common options anyway. But again... I don't know.

GCC has an extension to add attributes to types, which you can use to tell it your alignment requirements.
Additionally it has a #pragma to define the alignment, which could be used alternatively.
But as you already suspect, for this 8-bit target there should be no reason to insert padding bytes.

So your question boils down to find a method to detect unwanted padding. You can do this in a standard compliant way, which I show below. Yes, it does introduce additional types, one per structure. But it does not generate any unnecessary objects that eat your precious resources.
The "trick" is to use the sizeof operator to calculate a valid array size only, if the size of the checked type meets the expectation. If not, a compiler error safely breaks the generation of code. Granted, the error message is misleading an unsuspecting user, so it is really necessary to name the macro and the type accordingly.
This example compiles successfully with a PC as target, but not with an AVR as target. This is intentionally to demonstrate the working, because with an AVR target the type UP should have no padding bytes.
#define ASSERT_TYPE_SIZE(Type, size) \
    typedef char Assert##Type##Size[2 * (sizeof(Type) == (size)) - 1]

typedef struct {
    char c;
    long l;
} UP;
ASSERT_TYPE_SIZE(UP, sizeof (long) + sizeof(long));

typedef struct __attribute__((packed)) {
    char c;
    long l;
} P1;
ASSERT_TYPE_SIZE(P1, sizeof (char) + sizeof(long));

#pragma pack(1)
typedef struct {
    char c;
    long l;
} P2;
ASSERT_TYPE_SIZE(P2, sizeof (char) + sizeof(long));
#pragma pack()


text:
How to add library to Sloeber
Slober has a menu option: Arduino -> Add a library to the selected project
HOWEVER, the "Import Arduino libraries" dialog that comes up only shows 18 libraries, and has no obvious way to add more.
I selected Arduino -> How To, and selected "Add a library to a sketch", but it told me nothing new. It assumes the library I want to add is in the list, and says nothing about how that list itself is managed, where the libraries in it came from, how to add others, etc.
I theorized that Sloeber's list might be somehow generated from the one maintained by the Arduino IDE... but no, the list of libraries shown in Sketch -> Include library is ENORMOUSLY longer than Sloeber's list.
So... where, exactly, does Sloeber's library list come from, and how does one go about adding a library to it that's NOT in the list? Say...

From whatever repository the Arduino IDE itself gets libraries from when you go to Library Manager (confession: I don't use Arduino often enough to know where those libraries are actually hosted, or who decides what qualifies to be listed. I assume it's something like MavenCentral and hosted by the Arduino organization... but I might be completely wrong)

From a "zipfile" (containing whatever files, with whatever additional metadata, is required for Arduino's IDE to regard it as a valid library zipfile)

From a random Github repo, like https://github.com/mrkaleArduinoLib/gbj_htu21 (with library.json, library.properties, and subdirectories for src/ and examples/)

In Arduino or in Window menu in Preferences in Arduino section in Library Manager subsection

the library folders are set in Preferences too

(blush) Argh, I completely forgot that Slober has its own preferences that are separate from File -> Properties. (I do Arduino development just often enough to forget little details like that in between projects). Go ahead and list it as an answer, and I'll accept it :-)

In Arduino or in Window menu in Preferences


text:
I2C cabling rules for 2+ devices
I'm attempting to wire two breakout boards with i2c devices to a Mega2560:

a HD44280 LCD with PCF8574 i2c backpack
a combo board with DS1307 + AT24C32

There are two obvious possibilities for cabling:

two 10-inch ribbon cables that come together right before connecting to the Arduino's SDA and SCL pins. Technically, one could be 6 inches... but I know that with RS485, you're asking for trouble if you do a star with branches of unequal length. The cables can't really be any shorter without seriously impairing my ability to debug it while partially disassembled (the LCD is mounted to the lid, and the cables are long enough to allow me to lay the lid on the desk next to the enclosure and power everything up without putting stress on the cables).

Same 10-inch segments of ribbon cable, but daisy-chained... Arduino to LCD, LCD to RTC. In this case, the second one really needs to be 10", because it's mounted to the only clear spot inside the case I have.

Is one likely to be better or worse than the other?
Are there any rules about WHERE the pullup resistors have to go? The DS1307 module has built-in pullup resistors. Do I have to somehow disable them & use resistors right at the point where the bus connects to the Arduino's SDA & SCL pins, or can the pullups go pretty much anywhere on the bus (including at one end of a star, or at the far end of a daisy chain)?

I2C is generally slow. You don't have to worry about how to route the device connection. Because propagation delay won't be a matter. The main goal should be to minimize the capacitance of the wiring, which means minimizing the total wire length. But as you mentioned one of the cable lengths is fixed, then keep the other one to a minimum. The star topology will work if you keep the wire lengths within 10 inches.


text:
PlatformIO and const PROGMEM
I'm using the DuinoWitchery LCD library (https://github.com/duinoWitchery/hd44780) in a PlatformIO Arduino project with CLion.
The following code works if I stick it in main.cpp:
// near top of class...
const PROGMEM uint8_t decimalDigit[10][8] = {
        {0x07, 0x05, 0x05, 0x05, 0x07, 0x18, 0x18}, // .0
        {0x02, 0x02, 0x02, 0x02, 0x02, 0x18, 0x18}, // .1
        {0x07, 0x01, 0x07, 0x04, 0x07, 0x18, 0x18}, // .2
        {0x07, 0x01, 0x07, 0x01, 0x07, 0x18, 0x18}, // .3
        {0x5,  0x05, 0x07, 0x01, 0x01, 0x18, 0x18}, // .4
        {0x07, 0x04, 0x06, 0x01, 0x06, 0x00, 0x18, 0x18}, // .5
        {4,    4,    7,    5,    7,    0,    0x18, 0x18}, // .6
        {7,    1,    1,    1,    1,    0,    0x18, 0x18}, // .7
        {7,    5,    7,    5,    7,    0,    0x18, 0x18}, // .8
        {7,    5,    7,    1,    1,    0,    0x18, 0x18}, // .9
};

hd44780_I2Cexp lcd(0x27);

// ... snip ...

void setup() {
    for (int x=0; x<8; x++)
       lcd.createChar((uint8_t)x, decimalDigit[x]);
    // ...snip...
}

... but if I move the code into another class, like:
Renderer.h
class Renderer : BaseRenderer {
public:
    virtual void renderTo(hd44780* lcd) override;
    // ... snip ...
private:
const PROGMEM uint8_t decimalDigit[10][8] = {
        {0x07, 0x05, 0x05, 0x05, 0x07, 0x18, 0x18}, // .0
        {0x02, 0x02, 0x02, 0x02, 0x02, 0x18, 0x18}, // .1
        {0x07, 0x01, 0x07, 0x04, 0x07, 0x18, 0x18}, // .2
        {0x07, 0x01, 0x07, 0x01, 0x07, 0x18, 0x18}, // .3
        {0x5,  0x05, 0x07, 0x01, 0x01, 0x18, 0x18}, // .4
        {0x07, 0x04, 0x06, 0x01, 0x06, 0x00, 0x18, 0x18}, // .5
        {4,    4,    7,    5,    7,    0,    0x18, 0x18}, // .6
        {7,    1,    1,    1,    1,    0,    0x18, 0x18}, // .7
        {7,    5,    7,    5,    7,    0,    0x18, 0x18}, // .8
        {7,    5,    7,    1,    1,    0,    0x18, 0x18}, // .9
    };
}

Renderer.cpp
void Renderer::renderTo(hd44780lcd* lcd) {
    for (int x=0; x<8; x++)
       lcd->createChar((uint8_t)x, decimalDigit[x]);
    // ...snip...
}

... the custom characters end up with garbage data.
I think I might be breaking some esoteric rule that governs where you're allowed to put a const PROGMEM uint8_t[], and causing the array declared in Renderer.h to end up in SRAM. But I'm not sure how to confirm it OR fix it.

note: the for/next loop to create the chars is just for the sake of illustration & to demonstrate that something that works in main.setup() fails in Renderer.renderTo(). In real life, the sequence of characters getting rendered to the LCD owns one of the 8 custom characters & redefines it as necessary to be the decimal point and tenths value.

Does it help if you make the data member static const?

I'm pretty sure the first works only because it's in the RAM anyway because createChar doesn't support PROGMEM.

I think the DuinoWitchery LCD library specifically does. I literally copied the code that worked in main.setup() from the library's example code .

Confirmation: hd44780::createChar(uint8_t location, const uint8_t* charmap) ABSOLUTELY treats charmap as a pointer to PROGMEM. I took advantage of CLion's ability to find the source for a method, and edited it to stick a bunch of Serial.print() statements in createChar to see what's happening. The values it's fetching via pgm_read_byte() are definitely NOT the values in my array. So, it looks like my theory that decimalDigit[10][8] is ending up in SRAM is probably correct. I still have no idea why, or how to fix it, though :-(

I also just verified that the decimalDigit[][] array in Renderer.h is DEFINITELY ending up in SRAM (by temporarily hacking createChar() to forcibly treat it like a pointer to SRAM instead of a pointer to flash). So... NOW, the big question is, what do I have to do to get Renderer.h's array to end up in PROGMEM instead of SRAM?

Take the table out of the class.  Keep it in progmem.  Give the class a reference or a pointer to it.

Ok, I haven't noticed link to the library and found wrong one. You've defined it as const member of the class, so in theory you can change it in the constructors initializer list which means it's "runtime code" and therefore ends in the RAM

The PROGMEM qualifier can only be applied to statically-allocated
constant data. When you move the decimalDigit array inside the class,
it becomes a data member, i.e. you have one copy of the array per
instance... in RAM. In this case, PROGMEM does not work. My compiler
says:
warning: ‘__progmem__’ attribute ignored [-Wattributes]

If you want to keep the array inside the class, it must be given the
static qualifier. It then becomes statically-allocated class data (not
instance data):
// Renderer.h:
class Renderer : BaseRenderer {
public:
    virtual void renderTo(hd44780* lcd) override;
    // ... snip ...
private:
    static const PROGMEM uint8_t decimalDigit[10][8];
};

// Renderer.cpp:
const PROGMEM uint8_t Renderer::decimalDigit[10][8] = {
    {0x07, 0x05, 0x05, 0x05, 0x07, 0x18, 0x18}, // .0
    {0x02, 0x02, 0x02, 0x02, 0x02, 0x18, 0x18}, // .1
    // ... snip ...
};

Of course, putting the array within the class is not an obligation. If
it is going to be private anyway, the outside world (the files that
include Renderer.h) does not need to know about its existence.

OK, I ended up blindly stumbling over the solution, even though at this moment I have no idea why it actually works.
I moved the const PROGMEM uint8_t decimalDigit[10][8] = {...} declaration from Renderer.h to the almost-top of Renderer.cpp, so it sits between #include "Renderer.h" and constructor:
#include "Renderer.h"

const PROGMEM uint8_t decimalDigit[10][8] = {
        {0x07, 0x05, 0x05, 0x05, 0x07, 0x18, 0x18}, // .0
        {0x02, 0x02, 0x02, 0x02, 0x02, 0x18, 0x18}, // .1
        {0x07, 0x01, 0x07, 0x04, 0x07, 0x18, 0x18}, // .2
        {0x07, 0x01, 0x07, 0x01, 0x07, 0x18, 0x18}, // .3
        {0x5,  0x05, 0x07, 0x01, 0x01, 0x18, 0x18}, // .4
        {0x07, 0x04, 0x06, 0x01, 0x06, 0x00, 0x18, 0x18}, // .5
        {4,    4,    7,    5,    7,    0,    0x18, 0x18}, // .6
        {7,    1,    1,    1,    1,    0,    0x18, 0x18}, // .7
        {7,    5,    7,    5,    7,    0,    0x18, 0x18}, // .8
        {7,    5,    7,    1,    1,    0,    0x18, 0x18}, // .9
};

Renderer::Renderer(int col, int row, int customCharNumber) : BaseRenderer(col, row) {
    assignCustomChar(customCharNumber);
}

For now, I just have to chalk it up as 'black magic', because some subsequent experiments have forced me to question and doubt everything I ever thought I understood about how #include directives work.

That's not black magic.  You just took it out of the class definition.  If the class needs it as a member, then pass in a pointer or reference.  As it is written now, the decimalDigit array is no longer a part of the class.  It is existing at global scope.

It's nothing to do with black magic or #includes. An array of constants is, by definition, not going to change. Therefore there is no point in including it inside a class, unless marked as static, for scoping purposes.


text:
Problem with Arduuino to breadboard Mega8
I am trying to make an arduino using mega8 mcu. After so much struggling with sync/response/signature  problems and reading the previous questions, finally managed to do it (almost). However I still have some weird problems.
I uploaded the arduinoISP sketch to an Uno for programming the chips: AtMega8A-PU and AtMega8L-8PI (I had a couple of L version from years ago).
For bootloader selected the Mega8 from NG board in IDE 1.8.5 then uploaded to Mega8A-PU
for the L version cloned the ng part in boards.txt and reduced the F_CPU to 8MHz, (same bootloader code) and uploaded to 8l
Now, I'm able to upload sketches to both using a usb-serial breakout board/ avrisp mkII.
my first problem is when I disconnect the converter board neither of the MCUs can start unless I pull up or pull down the RxD pin (#2) which i find accidentally. it seems they both stuck in bootloader part. even if i leave the reset pin floating (using internal pullup) and tie the rxd pin they work fine up on applying power (with like an annoying 15~16s delay). the resistor value I tried 1K and 10K but no difference in operation and delay time. it wont start with rxd open. I couldn't find why?
another question is running the code on mega 8L as reliable as on 8A? (need it for lower V)
More clarification: they both run with Xtals and 22pf caps on breadboard. the 8l also works fine with 16MHz Xtal at 5v.
sketch (I know it's not much of help):
void setup() {
  Serial.begin(19200);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  tone(10,3520);
}

volatile unsigned int i, var = 1;

void loop() {
  digitalWrite(9, HIGH);
  for(i = 0; i < 1500; i++)
                 var += ((var * 3) / 2);
                 // do something (if compiler not wipe it for optimizing :D )
  digitalWrite(9, LOW);
  Serial.println(millis());
}

sample of 8A and (similarly) uno output:
7 11 15 19 23 27 31 35 39 44 48 52 56 60 64 68 72 76 80 84 89 93 97 101 106 110

8L output @ 3.3v @8MHz:
16 24 32 40 51 59 67 75 86 94 102 110

tone() output is the same for all
Appreciate your help

I found here: https://www.arduino.cc/en/Hacking/Bootloader?from=Tutorial.Bootloader
that NG / mega8 bootloader doesn't enable the rx pin internal pullup nor it gets out of the bootloader even if receiving junk data on rx  (which was my case due to leaving it open thus floating). It also has a delay of 6 to 8 seconds intentionally.
Probably I'll use another bootloader since the link to source code on the page was broken or just program the L version without any bootloader and better fuse options.


text:
Does the tone() generates unwanted signal?
I was trying to use the tone function for another project but I found that it also generates an undesired frequency (not the harmonics above of square wave it generates) but a lower frq square wave. Is this normal or somethings wrong with my implementation?
the code is pretty simple:
void setup()
{
    pinMode(7,OUTPUT); //set the pin as output
    tone(7,10000); //start a 10KHz tone
    while(true); //stay here
}

void loop()
{ }

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

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

What happens if you remove "while(true);" from the sketch?

@VE7JRO I just did that but nothing changed. guess the empty loop()  replaces my while. however I moved the the tone() AND the while(true) to the loop() and I still get the same result. but with tone() only in loop() the noise is more stressed I think because it repeatedly calls the function and tone sets the frq although it's the same as previous call.

or just a short or long jump to tone() needs more clocks. but that's not a good reason for noise when I call it once.

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

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

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

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

void loop() { }

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

Library code
If you don't want to trust some zip file from a random web site, here is TonePlayer.h:
/*
 Play tones with hardware timers
 Author: Nick Gammon
 Date:   1 April 2013
*/

#include <Arduino.h>

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

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

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

  };  // end of TonePlayer

/*

 PERMISSION TO DISTRIBUTE

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

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

 LIMITATION OF LIABILITY

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

 */

And here is TonePlayer.cpp:
/*
 Play tones with hardware timers
 Author: Nick Gammon
 Date:   1 April 2013
 */

#include <TonePlayer.h>

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

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

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

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

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

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

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

/*
 PERMISSION TO DISTRIBUTE

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

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

 LIMITATION OF LIABILITY

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

 Example of use:

 #include <TonePlayer.h>

 ...

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

 or, on the Mega 2560:

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

 ...

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

 or, on the Mega 2560:

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

*/

Just put those two files inside a folder "TonePlayer" inside the libraries folder inside your sketches folder, and it should all work.
The library is written for the 16-bit timers, and supports Timer 1 on the Atmega328, and Timers 1, 3, 4, 5 on the Atmega2560. Comments inside the library show how to set up the other timers.

You should probably warn that this library only works with 16-bit timers. 2. No need to split 16-bit writes into bytes, you can write *timerOCR_ = highByte(ocr);. This would save 4 bytes in the class. Since March 2005, gcc knows it must write the high byte first.

I got that code from my page about timers which had an extra sentence mentioning the 16-bit timers, which I have edited into my reply. You are right about the 16-bit writes, but to change that now would alter the call sequence for the constructors which could break existing code, so I'll leave it and take the 4-byte penalty. :)

@edgarbonet thanks for the clarification and detailed tweaks.

@nick thanks for providing the code, it works great. To correct myself I found that there are jitters or spikes with the tone() which increases with the frq. And a series of continius noise of with much less and constant  amplitude which i couldn't track down the source. I may add a photo later.

@user174174, when the standard Arduino tone() function changes to a new frequency, it does that in a nasty way. When creating a sound (for example a siren) it can be heard. That was also improved in the toneAC library.

I had a situation where calling tone() "broke" my IR Receiver. (Specifically, after calling tone(), the IR Receiver viewed all incoming signals as 0s.) This code fixed it! Thanks!

Did you measure it with good equipment? How much dB is the lower frequency? Can you show a spectrum plot?
It could be the software pin toggle. The tone selects a hardware timer, which is used to generate an interrupt. The output pin is toggled in that interrupt. It is in the file Tone.cpp. That interrupt could be delayed by a timer0 interrupt (for millis).
The timer0 runs at 16MHz/(64*256). With those numbers I can not get to the interference frequency that you mentioned.
You could try to use the output of a hardware timer. For example the toneAC library generates a tone at pin 9 and 10. That is as steady as the 16 MHz crystal (very steady).
It could be the equipment that you use to test.
It could be the speaker. Some speakers generate other tones. I had a ultrasound speaker which I could hear squeeking at a much lower frequency. After a search on the internet, I found that such a speaker is known to create lower frequency whistling noises.
It could be the 5V voltage is changed somehow by the circuit.

You wrote: “With those numbers I can not get to the interference frequency that you mentioned.” At 10 kHz, (41×f(timer 0) − 2×f(timer 2))/2 = 19.53125 Hz. At 40 kHz, (82×f(timer 0) − f(timer 2))/2 = 39.0625 Hz. The factor 2 in the denominator comes from the fact that interrupt collisions lengthen alternatively the HIGH level (when the fall is delayed) and the LOW level (when the rise is delayed).

@EdgarBonet, thank you. That is amazing that you could analyze that.

@jot thanks for your help, sadly I don't have any fancy equipment but I managed to record the signal with my laptop.


text:
How to do 'for' loop over inline anonymous array
I have a bunch of pins given names in the header:
#define DIP5 53
#define DIP4 52
#define DIP3 51
#define DIP2 50
#define DIP1 49
#define DIP0 48

If it's not obvious, I have a bunch of DIP switches connected to digital pins 48..53 on an Arduino Mega2560
In setup(), I need to set them all to INPUT_PULLUP. I know it would probably be less total effort to just do a series of pinMode commands, like:
pinMode(DIP5, INPUT_PULLUP);
pinMode(DIP4, INPUT_PULLUP);
// ... and so on

... but I'm trying to enrich my C++ skills & be fancy, so I'm trying to figure out how to declare an anonymous array and foreach through it... something like:
for (int pin : {DIP5, DIP4, DIP3, DIP2, DIP1, DIP0}) {
    pinMode(pin, INPUT_PULLUP);
}

... which, presumably, the compiler will optimize away into 6 inline pinMode commands anyway, but let me feel good about having pretty source code ;-)
except... when I try it, I get the following error:
error: deducing from brace-enclosed initializer list requires #include <initializer_list>
... but when I add #include <initializer_list>, I get a different error:
fatal error: initializer_list: No such file or directory
Any ideas what's wrong?
also... can I safely assume that the compiler will just unroll the whole thing behind the scenes, or is there a real risk it will actually declare a real array in SRAM just to iterate through one time?

define an array dip[0], dip[1] ....

As for the "risk" of an array being created in SRAM, that would anyway be destroyed when the function in which it is defined, typically setup(), exits. If you explicitly define an array, you can still scan it with a C++11 range based for loop, which may improve the program's aesthetics.

I'm trying to enrich my C++ skills & be fancy

The Arduino Mega is probably not the right platform to learn fancy C++.
The development environment doesn't support all the modern C++ stuff. In
particular...

fatal error: initializer_list: No such file or directory

...it rests on avr-libc, which is a C library with only limited support
for C++.

can I safely assume that the compiler will just unroll the whole
thing behind the scenes

No, you can't. The Arduino IDE, by default, calls avr-gcc with the -Os
flag, which means “optimize for code size”. Loop unrolling is the kind
of space vs. speed trade-off the compiler is unlikely to do with this
optimization setting. You can disassemble the .elf file if you want to
know for sure.

is there a real risk it will actually declare a real array in SRAM
just to iterate through one time?

I suggest you follow jsotola's advice and declare the array yourself.
You can declare the array PROGMEM if you want to avoid wasting RAM.
But given that it need not take more than 6 bytes (as uint8_t[]),
I would personally not even bother.

Edgar Bonet answers why for (int pin : {DIP5, DIP4, DIP3, DIP2, DIP1, DIP0}) { isn't working. What you would get (where supported) with this syntax is an initializer_list which itself is not an array type, although it is backed by an array.
If you really did want to do something like that with an AVR-based Arduino you could do:
for (int pin : (const int []){DIP5, DIP4, DIP3, DIP2, DIP1, DIP0}) {
    pinMode(pin, INPUT_PULLUP);
}

This is technically not standard C++. It is the use of something called a compound-literal, which is being used to make an array typed value. This is a feature of C language feature (from C99 onward), not C++. However, the compiler and its configuration for Arduino allows its use as a language extension.
Should you do this? Perhaps not, for the reasons that Edgar, 6v6gt, and jsotola point out.  However, this much can be done if you really wanted. With respect to what it's doing efficiency-wise, you should test it.


text:
Are variables declared in main.cpp static, instance, or...?
Let's suppose you've just created a new Arduino project using PlatformIO, or an IDE like Sloeber. You now have a file named "main.cpp" with two functions (methods?):

void setup()
void loop()

Now, suppose you follow Arduino coding norms, and stick something at the top like:
hd44780_I2Cexp lcd(0x27);

Is the hd44780_I2Cexp object instantiated by it static? Or is main.cpp #include'd into some class in a way that makes everything in it private or public members of that class?
If they're instance methods, is it absolutely 100% guaranteed that the instance is, and forever shall be, a singleton? Or is there any conceivable scenario where there could be two simultaneous instances of it (say, if you were using both cores of an ESP32)?
If it's an instance, but guaranteed to forever be singleton on any future platform that calls itself "Arduino", is there any need to care about the distinction between "instance member" and "static variable" (in the context of main.cpp)?
Should main.cpp "really" have a separate main.h file, and "official" public: and private: blocks for the sake of C++ linguistic purity, or would I just be creating real or potential problems for the sake of intellectual exercise and ideology?

public and private are for classes.  main isn't a class nor is it in one.  It's just a function.  The lcd object you describe creating is at global scope.  It's not part of an instance of any class.  I think maybe you are confusing this with java.

The lcd variable you create is not static nor is it an instance variable.  It is an instance of the hd44780_I2Cexp class that is at global scope.  It's not a member of anything.  It's not an instance variable of anything.  It's not static.  It's just a global object.

If you examine the output when building in verbose mode you'll find mentioned an .ino.cpp file in a temp directory. This is the result of the build process, the documentation for which probably tells you everything you want to know, if not .ino.cpp file doesn't.

In the Arduino IDE, setup and loop are functions, not instances of anything.
There is a file included in the compilation sequence, main.cpp, which has the following code (slightly simplified here):
#include <Arduino.h>

int main(void)
{
    init();

    setup();

    for (;;) {
        loop();
    }

    return 0;
}

So you can see that this bit of "sugar" basically calls setup once and loop repeatedly.
The other function, init, initialises some hardware, like the timers, so that millis() and delay() work as documented.
I can't speak for other IDEs but I assume they do similar things, in order to be compatible.

Whatever you define outside of any function will be global, which is static - it lives for the duration of program execution - and visible to all compilation units that are bound into the eventual execution unit.
If you also include the 'static' declaration ahead of the type, the variable will be file-level static, meaning it will be visibile only within the current file.
This is standard C/C++ behavior for any data type - scalars; vectors, structs & arrays; and objects (C++ only, of course).


text:
Creating formatted String (including floats) in Arduino-compatible C++
I'm using a Mega2560 and a generic SSD1306 OLED display with the Adafruit_SSD1306 (and by extension, Adafruit_gfx) library.
I need to print a bunch of float values (ranging between 30.0 and 99.9) to the display with exactly one decimal place of precision. The catch is, the Adafruit library doesn't have a printf() method, only one that takes a single ready-to-print string.
Here's an (obviously non-Arduino) Java-like example of what I'm trying to accomplish:
String foo = String.format("%.1f, %.1f\%", temp1, hum1);
// "display" is my instance of Adafruit_SSD1306
display.print(foo);

So... how can I do something similar in Arduino-compatible C(++)?
Note: for this specific program, I have (relatively speaking) RAM to burn, so I really don't care if whatever library I use to generate formatted Strings is particularly efficient (as long as it isn't leaking). If it wants to use 4k of RAM and 80k of flash to format a 20-character String, so be it.

use dtostrf() function

Normally for formatting strings I'd suggest the venerable snprintf and similar functions. However, on an 8-bit Arduino when you're using floats that's not an option: the function that does all the formatting for this family if functions has had floating point support surgically removed from it. This is to make the function a fraction of the size so it's not as bloaty in small microcontrollers.
I believe there is a float-capable version somewhere on the internet that could be somehow installed, though I have never looked into doing that.
Instead you need to do the formatting of floats manually.  Everything else can be done with snprintf, but the floats need to be done separately.
Fortunately there's a function specifically for formatting a float into a character array (C-string), called dtostrf and is used thus:
float myVal = 23.49173783;
char *buffer[10]; // Enough room for the digits you want and more to be safe
dtostrf(myVal, 9, 1, buffer);

The first number in the parameter list is how many characters you want to have in your output, including the . and any leading -. Any extra characters are padded with space.  The second number is how many decimal places.  If the first number is negative the value is left-aligned. If it's positive it's right-aligned.  So the code above would give you:
〿〿〿〿〿23.5␀

(Note: I am using 〿 to denote a space character.) If you used -9 you'd get:
23.5〿〿〿〿〿␀

You can, of course, feed that created string into another string using snprintf and the %s placeholder.
char buf2[32];
snprintf(buf2, 32, "The temperature is: %s\r\n", buffer);

buf2 ⇒ "The temperature is: 23.5〿〿〿〿〿"

If you want to trim the string down to just contain the number portion and lose the spaces it's best to left-align it with a negative width, then change the first space to a ␀:
char *space = strchr(buffer, ' ');
if (space != NULL) {
    *space = '\0';
}

The Adafruit_GFX class has two methods named print() and
println(). These behave exactly like Serial.print() and
Serial.println(). Specifically, when printing a float, you can provide
a second argument telling it the number of decimal places you want after
the decimal point:
display.print(temp1, 1);  // 1 digit after the decimal point
display.print(", ");
display.print(hum1, 1);  // ditto
display.print("%");

Background: the reason these methods behave like the ones of
Serial is that both Adafruit_GFX and HardwareSerial inherit them
from the Print virtual class.

it is not ideal for right aligned float numbers on LCD

@Juraj: That's right. However, the format used by the OP in his question ("%.1f, %.1f\%") doesn't do any kind of alignment. Thus I assumed that alignment is not a requirement.

One can use the String() type initialization to convert any number, including float to String. For example to convert 3.14159 simply type ⤵
float num = 3.14159
String str1 = String(num, 1) // 3.1
String str2 = String(num, 2) // 3.14
String str3 = String(num, 3) // 3.141

To the right of the comma is the number of decimal places one wants the string result to have. It has a lot of functionality but that's one of the overloads. You can see them all here!
To see this code working on a .ino sketch check out this GitHub repo
https://github.com/aeonSolutions/aeonlabs-ESP32-C-Base-Firmware-Libraries


text:
Do you actually NEED external resistors for switch connecting IO pin to ground?
Years ago, I encountered a fairly long debate at AVRfreaks.net about whether or not it's OK to directly connect AVR pins that are configured as inputs with internal pullup enabled directly to ground through a button or switch.
From what I recall, the consensus at the time was that it's not (at least, for switches likely to be closed and conducting at reset), because at least some AVR MCUs weren't absolutely guaranteed to have their pins in high-impedance state at reset (at least, not if the chip reset while in brownout state, or something like that).
Thinking back, I'm not sure whether the warnings even applied to the chips I was introduced to at the time (ATtiny2313, ATtiny13, and ATmega162)... I just remember that the others on the site were pretty adamant that I was courting disaster, and I took their word for it.
Fast forward ~15 years.
The current datasheet for the ATmega2560 (at https://ww1.microchip.com/downloads/en/DeviceDoc/ATmega640-1280-1281-2560-2561-Datasheet-DS40002211A.pdf ) does seem to guarantee (on pages 7-9) that the pins used by ports A through L are tri-state high-impedance input pins at reset under all conditions, including when the clock is halted (obviously, any pin Arduino's bootloader subsequently makes use of could behave differently if I tried to hijack it for double-duty reading a button/switch... but the Mega2560 has so many pins, there really isn't any reason to reuse pins Arduino uses for its own purposes).
Offhand, I can think of three potential remaining concerns:

If I screw up and accidentally execute code that configures a pin connected directly to ground through a closed switch as a high output, the pin (and probably the whole chip) is likely to go up in smoke. I can deal with this risk.

If I were powering it with batteries, I might care about the constant power drain wasting battery life. I'm not, and I don't.

I'm not quite sure whether "OK to connect directly to ground through a momentary pushbutton" necessarily equates to "OK to connect directly to ground through a switch that might conceivably be closed and continuously conducting current for the life of the circuit.

So... have I missed anything? And is #3 a legitimate concern, or is it something that's not worth caring about if you're talking about something like 8 pins connected through a DIP switch?
Illustrative circuit:
Ground <-- [switch] --> IO pin (configured for input, internal pullup enabled)

The internal pullup is like 50k. Not much of a current there to be concerned about

I think your analysis is correct.

If I screw up and accidentally execute code that configures a pin connected directly to ground through a closed switch as a high output, the pin (and probably the whole chip) is likely to go up in smoke. I can deal with this risk.

In addition to “there is an obvious bug”, there could also be a bug that is only triggered in very rare conditions, or a “cosmic ray” event which causes the processor to mis-execute instructions.
Or, maybe a metal tool or piece of debris fell across two of the processor pins and the other pin is an output that's currently high. (This is impossible to protect against in all cases, of course.)
In any of these cases, the hazard is that you're turning a situation where the device misbehaves temporarily into a situation where the device is permanently damaged.
Will this happen? Likely not. Is it worth protecting against? Depends on your application, on hard-to-quantify risk probabilities, and how much of a bother it would be to replace the processor.

The main problem is, I'm stuck working with an Arduino Mega2560 protoshield board that only has a sea of isolated ringed pads. If it were breadboard-like, with 2 or more adjacent pads connected (so I could just solder the DIP switch along the boundary between two sets of pads, then solder the resistors into the next pads over), I wouldn't have even bothered to contemplate the need for the resistors. But in this case, soldering even AWG30 WIRES to the DIP switch contacts was a major pain, and resistors would have had me in tears.


text:
Problem with PCB running an Arduino program to manage a GY-521 MPU6050 accelerometer
I'm working on a project based on MPU6050 GY-521 board connected to my PCB (running with an ATMega328P). The code was developed in Arduino.
The PCB is the second version. The first one works fine with the same accelerometer.
But with the second version I'm facing problems because it doesn't work and I can't understand the cause.
I did the following tests:

Run the code in an Arduino Nano board connected to the GY-521 MPU6050 board. Works fine.
Use other PCB to dismiss possible problem while soldering process. Doesn't work.
Probe with other GY-521 MPU6050 board. Doesn't work.

Finally I decided to cut some parts of the code trying to understand what part of this crash. My final test makes an LED blink while the rest part of the code ran.
void setup() {
  Serial.begin(115200);
  Wire.begin();
#if ARDUINO >= 157
  Wire.setClock(400000UL);
#else
  TWBR = ((F_CPU / 400000UL) - 16) / 2;
#endif

  i2cData[0] = 7; // Set the sample rate to 1000Hz - 8kHz/(7+1) = 1000Hz
  i2cData[1] = 0x00; // Disable FSYNC and set 260 Hz Acc filtering, 256 Hz Gyro filtering, 8 KHz sampling
  i2cData[2] = 0x00; // Set Gyro Full Scale Range to ±250deg/s
  i2cData[3] = 0x00; // Set Accelerometer Full Scale Range to ±2g
  while (i2cWrite(0x19, i2cData, 4, false)); // Write to all four registers at once

  //line commented in the last test
  //while (i2cWrite(0x6B, 0x01, true));

  //line commented in the last test
  //while (i2cRead(0x75, i2cData, 1));
  if (i2cData[0] != 0x68) { // Read "WHO_AM_I" register
    Serial.print(F("Error reading sensor"));
    while (1);
  }

  delay(100); // Wait for sensor to stabilize

  //line commented in the last test
  //while (i2cRead(0x3B, i2cData, 6));
  accX = (int16_t)((i2cData[0] << 8) | i2cData[1]);
  accY = (int16_t)((i2cData[2] << 8) | i2cData[3]);
  accZ = (int16_t)((i2cData[4] << 8) | i2cData[5]);

  // It is then converted from radians to degrees
#ifdef RESTRICT_PITCH // Eq. 25 and 26
  double roll  = atan2(accY, accZ) * RAD_TO_DEG;
  double pitch = atan(-accX / sqrt(accY * accY + accZ * accZ)) * RAD_TO_DEG;
#else // Eq. 28 and 29
  double roll  = atan(accY / sqrt(accX * accX + accZ * accZ)) * RAD_TO_DEG;
  double pitch = atan2(-accX, accZ) * RAD_TO_DEG;
#endif

  pinMode(7, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(4, OUTPUT);

}

void loop() {
  /* Update all the values */
  //line commented in the last test
  //while (i2cRead(0x3B, i2cData, 14));
  accX = (int16_t)((i2cData[0] << 8) | i2cData[1]);
  accY = (int16_t)((i2cData[2] << 8) | i2cData[3]);
  accZ = (int16_t)((i2cData[4] << 8) | i2cData[5]);
  tempRaw = (int16_t)((i2cData[6] << 8) | i2cData[7]);
  gyroX = (int16_t)((i2cData[8] << 8) | i2cData[9]);
  gyroY = (int16_t)((i2cData[10] << 8) | i2cData[11]);
  gyroZ = (int16_t)((i2cData[12] << 8) | i2cData[13]);;

  double dt = (double)(micros() - timer) / 1000000; // Calculate delta time
  timer = micros();

  // It is then converted from radians to degrees
#ifdef RESTRICT_PITCH // Eq. 25 and 26
  double roll  = atan2(accY, accZ) * RAD_TO_DEG;
  double pitch = atan(-accX / sqrt(accY * accY + accZ * accZ)) * RAD_TO_DEG;
#else // Eq. 28 and 29
  double roll  = atan(accY / sqrt(accX * accX + accZ * accZ)) * RAD_TO_DEG;
  double pitch = atan2(-accX, accZ) * RAD_TO_DEG;
#endif

  double gyroXrate = gyroX / 131.0; // Convert to deg/s
  double gyroYrate = gyroY / 131.0; // Convert to deg/s
  double gyroZrate = gyroZ / 131.0; // Convert to deg/s

#ifdef RESTRICT_PITCH
  // This fixes the transition problem when the accelerometer angle jumps between -180 and 180 degrees
  if ((roll < -90 && kalAngleX > 90) || (roll > 90 && kalAngleX < -90)) {
    kalmanX.setAngle(roll);
    compAngleX = roll;
    kalAngleX = roll;
    gyroXangle = roll;
  } else
    kalAngleX = kalmanX.getAngle(roll, gyroXrate, dt); // Calculate the angle using a Kalman filter

  if (abs(kalAngleX) > 90)
    gyroYrate = -gyroYrate; // Invert rate, so it fits the restriced accelerometer reading
  kalAngleY = kalmanY.getAngle(pitch, gyroYrate, dt);
#else
  // This fixes the transition problem when the accelerometer angle jumps between -180 and 180 degrees
  if ((pitch < -90 && kalAngleY > 90) || (pitch > 90 && kalAngleY < -90)) {
    kalmanY.setAngle(pitch);
    compAngleY = pitch;
    kalAngleY = pitch;
    gyroYangle = pitch;
  } else
    kalAngleY = kalmanY.getAngle(pitch, gyroYrate, dt); // Calculate the angle using a Kalman filter

  if (abs(kalAngleY) > 90)
    gyroXrate = -gyroXrate; // Invert rate, so it fits the restriced accelerometer reading
  kalAngleX = kalmanX.getAngle(roll, gyroXrate, dt); // Calculate the angle using a Kalman filter
#endif

  gyroXangle += gyroXrate * dt; // Calculate gyro angle without any filter
  gyroYangle += gyroYrate * dt;
  //  gyroXangle += kalmanX.getRate() * dt; // Calculate gyro angle using the unbiased rate
  //  gyroYangle += kalmanY.getRate() * dt;

  compAngleX = 0.93 * (compAngleX + gyroXrate * dt) + 0.07 * roll; // Calculate the angle using a Complimentary filter
  compAngleY = 0.93 * (compAngleY + gyroYrate * dt) + 0.07 * pitch;

  // Reset the gyro angle when it has drifted too much
  if (gyroXangle < -180 || gyroXangle > 180)
    gyroXangle = kalAngleX;
  if (gyroYangle < -180 || gyroYangle > 180)
    gyroYangle = kalAngleY;

  // leer el valor analogo que entra
  // filtrarlo
  // determinar si se enciende el led
  sensorValue = analogRead(sensorPin);
  filBattery = myFilterBattery.getFilteredValue(sensorValue);
  if (filBattery < 750) // hacer la prueba con este nuevo valor
  {
    digitalWrite(3, HIGH);
  }
  else
  {
    digitalWrite(3, LOW);
  }
  digitalWrite(5, HIGH);
  delay(500);
  digitalWrite(5, LOW);
  delay(500);
}

With this code the LED blinks fine, but the commented lines are critical to MPU6050 setup and operation.
If someone can help me to understand what happen to my PCB, I'll be grateful.
Thanks in advance

I've given a short answer, based on the information you've given, which seems to point towards a likely area for you to investigate. However there is lots of information that you haven't given e.g. (a) schematic diagram; (b) PCB layouts for v1 and v2; (c) explanation of why you changed from PCB v1 to v2; (d) details of what changes (if any) you were trying to make between PCB v1 & v2; (e) details of your troubleshooting so far using (e.g.) oscilloscope or logic analyser (a multimeter would only show "gross" mistakes on an I²C bus); (f) details of other suggestions you have already tried.

it is also possible that v1 pcb is actually the bad one. some mistake in the design is allowing the code to run. ... i have seen it happen with two pieces of computer equipment. the one that failed to work was actually the good one.

@jsotola - True (+1). I've opted to start with the simple approach (e.g. in the USA, if you hear galloping hooves, first think horses not zebras). The lack of detail & context from the OP, and missing definition of "working" vs. "not working" etc. etc. makes deep analysis inefficient at this stage. Anyway, the comparison between "working" and "not working" as I recommended in my answer, is likely to make progress - even if that progress gives an unexpected result, as you said in your comment - and yes, over decades of troubleshooting, I've seen situations like you describe too :-) Fun!

@SamGibson, you are absolutely correct, the difference in the two versions is the key to the solution

There has been a request to reject the migration from EE.SE. I'm not sure. We need more complete code (where is i2cData declared?). Also we need to see your debugging prints. Saying "not working" doesn't tell us much.

You have explained that PCB v1 works, and PCB v2 does not work. Therefore, it seems likely the problem is in your PCB design and not in the code.
In your code sample which blinks an LED on PCB v2, but does not communicate with the MPU6050, it seems that you have removed the I²C function calls. Therefore if removing those function calls is what allows your code to run, and if the "working" code used on PCB v1 does not run successfully on PCB v2, then it's logical that you have somehow broken your I²C bus on PCB v2.
I suggest you start by comparing your PCB v1 and v2 designs carefully, focussing especially on the I²C bus and the connections to the MPU6050.

Thanks to all people who take time to answer me.
I found the error in the PCB v2. SamGibson, you are right, the error was in the I²C: the path was touching the GND plane. I separete this carefully and now works fine. Regards


text:
Serial.write(buf, len) error. How to remove an error and pass an array of bytes?
int angleServo1,angleServo2 = 0;
const int axisX=A0; // ось Х подключена к A0
const int axisY=A1; // ось Y подключена к A1
int valX, valY = 0; // переменные для хранения значений осей
int datos[3];
#include <SPI.h>

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

void loop()
 {
      valX = analogRead(axisX); // значение оси Х
      valY = analogRead(axisY); // значение оси Y
      // масштабируем значение к интервалу 0-180
      angleServo1=map(valX,0,800,100,-100);
      angleServo2=map(valY,0,810,100,-100);

       datos[0] = angleServo1;
       datos[1] = angleServo2;
       Serial.write(datos, sizeof(datos));
       delay(100);
}

error: no matching function for call to 'HardwareSerial::write(int [3], unsigned int)'
how to remove an error and pass an array of bytes?

byte datos[3]; changed, I will test the code. I'm not sure that it will work. Because the byte of small value.

it is telling you that HardwareSerial::write() does not have a function that will accept two arguments where the first one is an array of integers and the second one is an unsigned integer ..... i think that HardwareSerial::write() only has a function that accepts one argument that is an integer, not an array

try this: Serial.print(datos);

See: https://github.com/arduino/ArduinoCore-avr/blob/3d09a51bd20f095e1354243e6d8addedfcb6001e/cores/arduino/Print.h#L56-L59

@jsotola, what? write(int)? there is write(byte) and write(buff[], size)

did not word that correctly ... i think that the brain was in neutral ... the serial.write() accepts an array of bytes, not an array of integers

You want to send data to computer processing or print them for user to read? Functions write send raw data. To print the data to Serial monitor print and println functions are used.
There are two write functions. First sends one byte. Second sends array of bytes. There is no write function to send array of ints. You could cast the array of ints to array of bytes to send the array as raw bytes for processing on the receiving side. But then you first should perhaps send to the receiving side some control data about the data package.
  Serial.write((byte*) datos, sizeof(datos));

If you want to print numbers to Serial Monitor, the print functions have variants which take a number and convert it to string. But there is no print function to print an array of numbers. You must print them one by one in a for loop. And put some separator between them (coma, space, new line).

note: sizeof returns the size of the array in bytes


text:
Connect three android to one arduino mega
Android Arduino Mega SerialPort1 SerialPort2 SerialPort3
Is it possible to connect three Android tablets to the Arduino mega through three SerialPort? Rx1 Tx1; Rx2 Tx2; Rx3 Tx3
I managed to connect only one device directly through the cable, but this is only one device.

Sure. Three USB to UART adaptors. Or three serial Bluetooth modules.

may have information how to do this? Link?

If using USB to UART: plug one end into the phone. Plug the other end into the TX/RX pins. Profit. If using bluetooth it's identical to using just one module.

Not every library supports USB-UART, I have already tried five USB-UARTs in the application, there is very little information on the Internet about connecting USB-UART to Android applications.

Then you need to find one that does work.

where is the problem, if you connected one?

@Juraj I guess he connected the Arduino directly through it's built in USB port.

then it is about USB chip drivers for Android?

https://github.com/felHR85/UsbSerial
I found the library, I think I will understand, thanks


text:
How to add additional sensors [Arduino]
I am new to Arduino.
I have currently connected a FSR sensor to the TOUT pin of ESP WROOM-02.
How do I add additional FSR sensor to ESP WROOM-02?

An FSR (Force Sensing Resistor) varies in resistance as force or pressure is applied.  Most often such devices are connected to the positive power rail and the ADC input of a embedded micro controller.  At the same time a second known fixed resistor is connected to the opposite power rail (ground) and the same ADC input.  This forms a resistor divider network where the ADC in the embedded micro controller can measure the force applied to the FSR by measuring the voltage of the resistor divider.
To measure 2 or more FSRs using the same ADC input, consider connecting one lead of each FSR to a digital input/output pin of the embedded micro controller. Then connecting the other lead of each FSR to the ADC input.  To measure the force on the 1st FSR, configure the connected digital pin as a high ouput using software.  So that all the other FSRs do not influence the measurement, configure all the other digital pins to have high impedance.  Often this can be done by programming these other digital pins as inputs.  Cycle through all FSRs in a similar fashion using software.


text:
Will avrdude overwrite the bootloader on my Nano?
I bought an arduino nano (knockoff from Elegoo) and according to the Amazon description it comes with a bootloader.
From what I've read, this means that programming can occur over the usb connection rather than having to rely on a dedicated serial programmer.
I installed the necessary drivers, plugged in the Nano, and ran this command (not to program, just to see if the board would be recognized):
avrdude -p m328p -b 57600 -P /dev/wcbhserial1460 -c arduino
It recognized the board and said it was ready to be programmed. If I then actually go ahead and ask it to flash a hex file onto the board, will the -c arduino argument tell avrdude to use the bootloader or does it just overwrite everything? Can I reprogram multiple times using this command?
I'm using Atmel Studio 7 and am configuring it to call the appropriate avrdude command.
EDIT: According to this answer, the -D flag will program the chip without clearing the flash, allowing the bootloader to preserved. Unfortunately, since the ATmega devices don't support partial flash memory clearing, this will only work once. So essentially I need to reupload the bootloader each time, which kinda defeats the purpose of it right?
It looks like though he is talking about using an AVRISP, so does all that not apply if you're just programming using the bootloader and the usb connection in the first place?

if you write over ICSP header, the bootloader will be erased. if you use bootloader to write hex over UART the bootloader will stay


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.