text:
Set board manager as ATmega16
I tried to download the ATmega16 board in my Arduino. I have set below URL under File->Preference->Additional board manager URL
https://mcudude.github.io/MightyCore/package_MCUdude_MightyCore_index.json
I am getting below attach images. How can we resolve this error and install atmega16 board manager?
I am using Arduino version 1.6.9. I don't have any issue in opening MightyCare and Arudino URL from my chrome browser.

I believe you will get the same error even if you did not have the MightyCore additional URL added to your preferences. This might be caused by network security settings preventing the Arduino IDE from downloading the file. Try whitelisting the Arduino IDE in your firewall software. You can configure proxy settings in the network tab of File > Preferences if necessary.

"Issue raised only when I update the mightcore URL" Have you verified this by removing the MightyCore additional Boards Manager URL from your preferences and opening Boards Manager? Boards Manager always attempts to download the official Arduino Boards package index file first followed by the additional URLs. It has the unfortunate behavior of giving up after the first URL that fails download. So if the Arduino URL fails then it won't even attempt your additional URLs.

Great, so we now know the problem has nothing to do with MightyCore. Can you open the page https://downloads.arduino.cc/packages/package_index.json from the browser on your laptop?

@per1234 Apologies! For not giving enough info in my question. Yes I am able to open the json page(mightycare and arduino) from my browser without any issue.

Definitely look into whether the problem is caused by your network security settings.

Thanks for everyone help here.
I have resolved by few steps.
1) File -> preference -> Board manager URL as like below. Basically URL are seperated by commas.
http://arduino.esp8266.com/stable/package_esp8266com_index.json,https://mcudude.github.io/MightyCore/package_MCUdude_MightyCore_index.json
2) Deleted the tmp file (package_index.json.tmp) which is in the path C:\Users\SIMBU\AppData\Local\Arduino15\
This helped me to resolve the issue.


text:
Using an Arduino Nano to program (as ISP) a standalone 328p
I uploaded the ArduinoISP sketch to an Arduino Nano to use it as a programmer for other chips.
It worked successfully to program an ATtiny45, I did the usual wiring between them, and added a 10uF between RST and GND of the Nano. Everything worked.
Now I'd like to program a standalone ATmega328p with the Nano, I did the usual wiring as well (see this tutorial), as well as this 10uF cap.
But it does't work:

avrdude: Device signature = 0x000000
  avrdude: Yikes!  Invalid device signature.
           Double check connections and try again, or use -F to override
           this check.

The reason might be because this 328p comes from an Arduino Uno, probably configured to be ext-clocked by a crystal. Whereas I don't have any crystal here and wanted to clock the 328p with the internal clock.
Question: how can I restore the 328p to factory default / internal clock, if I don't have a crystal?
Or what other reason can this error be?
Edit: a solution is found here: Change the fuses of an Arduino Uno (can an Arduino Uno change its own fuses?)

There is some differences (signature numbers) between similar processors, like ATMega328P-PU and ATMega328PU. Check this link

Solution: https://arduino.stackexchange.com/questions/68779/change-the-fuses-of-an-arduino-uno-can-an-arduino-uno-change-its-own-fuses

You can temporarily put it in an UNO. Don't connect this UNO via USB, but use jumper wires to connect the ISP pins plus the power pins to the other Arduino that you are using as an ISP programmer. (You could also use the (2x3) ISP header on the UNO if that's more convenient.)
Or, you could use a high voltage programmer.
Or get/desolder a crystal from some junk electronics. Exact frequency doesn't matter that much. I think somewhere between 1 Mhz and 16 Mhz would work.
You can then reset the fuses, so it doesn't need a crystal.

Thank you for your answer. I will try to put it on a Uno temporarily just the time of setting clock to internal. How to do this from arduino IDE ? When I select Board: Uno there is no submenu to select clock internal / external. Any idea ?

@Basj sorry about that. I kind of glossed over the fact that you only use the UNO for the crystal, and still need to connect it tho the other Arduino used as ISP programmer. I edited my answer to reflect that. Looking at your edit, it seems like you already  figured it out yourself. Which it great.

That error basically says the bootloader you are trying to burn does not appear to be for that device.  This could be due to corruption or (more likely in your case) harvesting and reconfiguring the hardware.
If the error does not appear when you try to load the bootloader for the Uno (original device you harvested it from for those harvesting from other configurations), you will know it is the latter.
Either way, you can try to -f it by running avrdude to burn the bootloader via command line (as it says).  I've successfully saved  stuff with a corrupt bootloader this way although i've never found it worth the hassle to harvest and reconfigure- if you pulled it off the uno, surely you can stitch it to a clock.
If your clock is off by a bit, you may just need to get lucky over several attempts :)

source: Stack Exchange

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

sort: votes


text:
How to deep sleep ATtiny/ATmega (to run for years with batteries) but still detect a button press?
Question (TL;DR): what is the optimal method to deep sleep (to run an ATtiny45 or ATmega on batteries for 1+ year) but still be able to detect a button press? Is it possible to deep sleep until a button is pressed?
I'm using a classic "debounce" method to detect a button press:
int buttonState;
int lastButtonState = LOW;
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;

void setup() {
  pinMode(2, INPUT);
}

void loop() {
  int reading = digitalRead(2);
  if (reading != lastButtonState) { lastDebounceTime = millis(); }
  if ((millis() - lastDebounceTime) > debounceDelay) {
    if (reading != buttonState) {
      buttonState = reading;
      if (buttonState == HIGH) {
         // Button pressed, do something here!
         // In my actual code, it sends a packet via RF 433 Mhz
      }
    }
  }
  lastButtonState = reading;
  // snore(20);          // TinySnore here
}

My ATtiny45 should run during 1 year on 3 AA batteries, so I added a deep sleep using TinySnore. It works, and made the consumption go from more than 1mA to 0.2mA (@1 Mhz).
I know it's possible to go down to 5 µA if I snore(1000); but then obviously it won't be able to detect a button press.
I tried various sleep values: snore(10);, snore(20);, snore(50);, etc. but I didn't get consistent results.
Thus the question: how to deep sleep until a button is pressed?

I was thinking about using attachInterrupt() but then what kind of sleep should we use? snore()? delay()?

#include <avr/sleep.h> with sleep_cpu and friends, woken up by an interrupt. Nick Gammon has a pretty extensive forum post on this: https://www.gammon.com.au/forum/?id=11497 (https://github.com/connornishijima/TinySnore/blob/master/src/tinysnore.cpp uses the same functions but only seems to be able to do timer-wakeups)

Thank you @MaximilianGerhardt. In this example: https://www.gammon.com.au/forum/?id=11497&reply=4#reply4, why is there no use of attachInterrupt? Are there different methods?

Instead of attachInterrupt(), the interrupt service routine (ISR) for the necessary vectors are hooked directly, e.g. ISR (PCINT0_vect) { .. }. An example with attachInterrupt is in the first post with the code labeled Waking from sleep with a signal, which matches your button better. When an interrupt is configured for a pin, a change event will automatically wake the CPU from sleep. See datasheet (http://www.farnell.com/datasheets/1698186.pdf) section 7.1 "Sleep Modes", "INT0 and pin change"

Just a caution that putting a standard ATMEGA. Board into sleep mode leaves the supporting circuitry (USB interface etc) drawing power so you would be better to go for the ATTINY.

ATTINY's are designed to easily do this since they can wake from power down sleep mode by a pin change...

Basically you want to...

Connect a normally-open push button between an IO pin and ground.
Enable the pull-up on the IO.
Enable the pin change interrupt on the IO pin.
Enable interrupts.
Enter "power down" sleep mode.

When the button is pushed, it will connect the IO pin to ground, which will cause a pin change interrupt, which will wake the chip from sleep.
Note that you do not need to do anything in the pin change ISR (you can use the EMPTY_INTERRUPT compiler macro). If the ISR is empty, execution will pick up on the line after the sleep upon waking.
While in deep sleep, the chip will use an astonishingly small amount of power.  For example, an ATTINY25/45/85 running off of a 3V coin cell at room temp will use less than 0.2uA...

A typical CR2032 coin cell is rated for 235mAh to 2V, so at this rate we'd expect to be able to wait for a button press like this for 100+ years.
IRL the battery will likely self discharge and physically deteriorate long before then (rated at 1% per year), but still not too shabby.

Thank you for this great answer! Linked question: https://arduino.stackexchange.com/questions/70292/how-to-assign-an-interrupt-to-a-button-press-with-an-attiny-interrupt-not-fire

First I was unable to make the intterupt work for multiple pins, but finally here is a working code:
#include <avr/interrupt.h>
#include <avr/sleep.h>

ISR(PCINT0_vect) {
  if (digitalRead(0) == LOW)           // # PB0 = pin 5 pressed => LED on
    digitalWrite(4, HIGH);
  else if (digitalRead(1) == LOW)      // # PB1 = pin 6 pressed => LED off
    digitalWrite(4, LOW);
  else if (digitalRead(2) == LOW)      // # PB2 = pin 6 pressed => LED on
    digitalWrite(4, HIGH);
}

void setup() {
  pinMode(4,OUTPUT); // LED
  pinMode(0,INPUT_PULLUP);
  pinMode(1,INPUT_PULLUP);
  pinMode(2,INPUT_PULLUP);
  ADCSRA = 0; // ADC disabled
  GIMSK = 0b00100000;  // General Interrupt Mask Register, / Bit 5 – PCIE: Pin Change Interrupt Enable / When the PCIE bit is set (one) and the I-bit in the Status Register (SREG) is set (one), pin change interrupt is enabled. Any change on any enabled PCINT[5:0] pin will cause an interrupt. The corresponding interrupt of Pin Change Interrupt Request is executed from the PCI Interrupt Vector. PCINT[5:0] pins are enabled individually by the PCMSK0 Register. / see https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf
  PCMSK = 0b00000111;
}

void loop() {
  sleep_enable();
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_cpu();
}

Note: PCINTs are handled by a single PCINT_vect here.
PS: as mentioned by Maximilian in a comment, this post gives nice solutions: Detecting key presses on a keypad whilst asleep.

I would put the MCU in deep sleep and then use the reset button.

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


text:
How to assign an interrupt to a button press with an ATtiny? (interrupt not fired with my code)
(Here is finally a solution).
I'm using the following code on a ATtiny45 to assign an interrupt to a button press (pin #7, PB2, INT0). However the LED doesn't blink when the button is pressed, as if the interrupt is not working. Why?
Note: I'd like to use the least power when no interrupt happens, to have a current in the order of magnitude of ~ 1 µA, to run from batteries for years.
#include <avr/sleep.h>

void setup()
{
  pinMode(4, OUTPUT);  // LED
  pinMode(0, INPUT_PULLUP);
  pinMode(1, INPUT_PULLUP);
  pinMode(2, INPUT_PULLUP);      // pin #7 = PB2
  digitalWrite(4, HIGH); delay(100); digitalWrite(4, LOW);  // LED blink, working here
}

void wake()
{
  sleep_disable();
  detachInterrupt(0);
  digitalWrite(4, HIGH);  // LED not working here when pressing the button
}

void loop()
{
  sleep_enable();
  ADCSRA = 0;
  attachInterrupt(0, wake, CHANGE);
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_cpu();
}

Note:

I'm using Arduino IDE with damellis' attiny, I also tried with Spence Konde's ATtinyCore but it's the same
In my real code, I have 3 buttons, on pin #5, #6, #7, so eventually I'd like to have interrupts for all these three pins.
I've read https://gammon.com.au/forum/?id=11497 but using noInterrupts() / interrupts() did not change anything in my case.
I've tried "Sketch J" from https://gammon.com.au/forum/?id=11497 but EIFR = bit (INTF0); gives an error: 'EIFR' was not declared in this scope (I'm compiling from Arduino IDE); probably this works on an ATmega but not ATtiny.

Edit: Here is a working code of deep sleep, with an interrupt when the pin #5 (PB0) changes...
#include <avr/interrupt.h>
#include <avr/sleep.h>

ISR(PCINT0_vect) {
  if (digitalRead(0) == LOW)
    digitalWrite(4, HIGH);
  else
    digitalWrite(4, LOW);
}

void setup() {
  pinMode(4,OUTPUT); // LED
  pinMode(0,INPUT_PULLUP);
  pinMode(1,INPUT_PULLUP);
  pinMode(2,INPUT_PULLUP);
  ADCSRA = 0; // ADC disabled
  GIMSK = 0b00100000;  // General Interrupt Mask Register, / Bit 5 – PCIE: Pin Change Interrupt Enable / When the PCIE bit is set (one) and the I-bit in the Status Register (SREG) is set (one), pin change interrupt is enabled. Any change on any enabled PCINT[5:0] pin will cause an interrupt. The corresponding interrupt of Pin Change Interrupt Request is executed from the PCI Interrupt Vector. PCINT[5:0] pins are enabled individually by the PCMSK0 Register. / see https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf
  PCMSK = 0b00000111;  // Pin-change interrupt for PB0, PB1, PB2
}

void loop() {
  sleep_enable();
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_cpu();
}

...but for an unknown reason, if I add this code:
ISR(PCINT1_vect) {
  if (digitalRead(1) == LOW)
    digitalWrite(4, HIGH);
  else
    digitalWrite(4, LOW);
}

the pin-change interrupt for PB0 still works (PCINT0), but not the interrupt for PB1 (PCINT1). Why?

the reason is bad code ... do not use delays in the ISR ... set a flag variable only ... do the blink inside the loop() block

Without having an Arduino at hand: Don't you need to enable interrupts in general? Like calling sei() or so?

@Basj - Sorry, I can't help you. I don't have an ATtiny to use for testing.

Possible duplicate of How to deep sleep ATtiny/ATmega (to run for years with batteries) but still detect a button press?

Look at the datasheet of the ATtiny45. In the section “Sleep Modes”,
there is a table that lists the wake-up sources available for each sleep
mode. For the mode “power-down”, INT0 is listed as a possible wake-up
source, but there is a small footnote:

For INT0, only level interrupt.

This means that the CHANGE mode you are trying to use will not wake-up
the MCU out of power-down. You have to instead
attachInterrupt(0, wake, LOW);

In my real code, I have 3 buttons, on pin #5, #6, #7, so eventually
  I'd like to have interrupts for all these three pins.

You may then have to look into the “pin-change” interrupt. This is
something different from the INT0 you are using here, and is not
generally supported by the Arduino core. You will have to either get
some pin-change-interrupt library, or work with no library using the
information from the datasheet (not that hard). Pin-change interrupt is
also a wake-up source for power-down.

Edit: Answering extra questions from comments.

How did you know that "only level interrupt" means only "LOW"?

The Arduino documentation states that the mode
parameter of attachInterrupt() can be either LOW, CHANGE, RISING
or FALLING. A few boards also support HIGH, but the ATtinies are not
among them. A “level” can be either LOW or HIGH, whereas CHANGE,
RISING and FALLING are “edges”.
This is corroborated by the ATtiny45 datasheet: “The INT0
interrupts can be triggered by a falling or rising edge or a low level.”

Is pin-change interrupt PCINT?

Yes.

why do you think it isn't supported by the Arduino core?

The attachInterrupt() API only really makes sense for INT0, INT1,
etc... not for PCINT. You can also look at the source code.

Isn't it standard to interrupt when a pin changes states?

If you wish, you can configure INT0 to interrupt on a rising edge, a
falling edge, or any logical change. But this uses an edge-detection
logic which relies on the main clock, and thus does not work in
power-down mode.
For more details on INT0 vs. PCINT, their differences, and how to use
them, please refer to the datasheet, specifically to the “External
Interrupts” section I linked to above.

Addendum: Extra question:

why it doesn't work [with ISR(PCINT1_vect) {...}]?

Gcc tells me “warning: ‘PCINT1_vect’ appears to be a misspelled
signal handler”. And indeed, there is no such interrupt vector on the
ATtiny45: there is only PCINT0_vect, and this interrupt is shared by
all the pins that can generate a pin change interrupt. If you want to
know which pin triggered the interrupt, you will have to figure that out
within the interrupt handler itself.
This is the single point that makes the PCINTs trickier to work with
than INT0 and co.: each PCINT interrupt is shared by a group of pins. On
the ATtiny45, there is only one such group, and PCINT0_vect is the
only interrupt handler. Larger AVRs have more groups (3 on the
Uno/ATmega328P), and PCINT1_vect makes sense on them.
Also beware of the somewhat confusing naming scheme. Avr-libc defines
some macros PCINTn, where n is a number. These macros expand to bit
numbers, and are meant to be used in code like this:
PCMSK = _BV(PCINT0)   // sense changes in pin PCINT0 = PB0...
      | _BV(PCINT1)   // and PCINT1 = PB1...
      | _BV(PCINT2);  // and PCINT2 = PB2

In these macros, the number n identifies an individual pin. Avr-libc
also defines the macros PCINTm_vect for defining interrupt handlers.
In these macros, the number m identifies a pin group.

Thank you for your answer, and for the update!

I edited my question and added some working code of interrupt for PCINT0. Do you know why it doesn't work for PCINT1?


text:
How precise is the timing of pulseIn()?
I've been using the pulseIn() function for processing PWM-based binary data encoding. It works well for distinguishing pulses which are significantly different lengths, e.g. 500us vs. 1500us. That makes it more than sufficient for handling typical IR remotes.
However, I want to make my own IR system which can use more than 2 pulse lengths, so that data transfer can occur faster. Ideally, I'd like to use 8 different pulse lengths for octal encoding (e.g. 200us, 400us, 600us, etc.).
I've noticed quite significant variations in the values returned by pulseIn() though (+/- 10%). I expect at least some of it is introduced by the IR transmitter and receiver modules, but I don't have good enough equipment to verify that.
Assuming I can mitigate that external error, is pulseIn() likely to be precise enough to distinguish such similar pulses?

The pulsein() function is very lossy, in that it is a hard loop and returns a number * the assumed clock cycles it takes for per loop
...
// wait for the pulse to stop
while ((*portInputRegister(port) & bit) == stateMask) {
  if (numloops++ == maxloops)
    return 0;
  width++;
}

// convert the reading to microseconds. The loop has been determined
// to be 20 clock cycles long and have about 16 clocks between the edge
// and the start of the loop. There will be some error introduced by
// the interrupt handlers.
return clockCyclesToMicroseconds(width * 21 + 16);

The most accurate method for capturing the timing of a PIN is use the INPUT CAPTURE FEATURE. Look at the this example . It enables the input capture at 1x of CPU for max resolution and each edge of the input pin captures the timer's clock value for reading from the generated Interrupt service. It also enables the timer overflow interrupt to as to maintain large absolute time, to be capture. Since the 1x will roll rather quickly. The captures store the time into an array for reading by the main loop.

Where for signals over IR the typical library to use is shirriff/Arduino-IRremote library. Where it has several demo's that will read and send the IR from a demodulated signal. To allow one to build a sketch of their own design. This code originally creates a timer interrupt that polls the input pin at a rate determine by
#define USECPERTICK 50  // microseconds per clock interrupt tick

in the IRremote.h file. For my purposes I have change it to 25 us. Where I find this still can be intermittently missing pulse streams.
Note the demodulation is best accomplished within the IR receiver, which in turn outputs this signal of interest. Where to add some background. Using the typical 38KHz modulation, equates to a minimum resolution of 26.3uS per pulse's cycle. sherriff's library shows typically most bauds or bits are in the order of 10+ pulses. Which appear to meet your desired timings.
microtherion/Arduino-IRremote fork of shirriff's work improves the reception by replacing the timer interrupt polling of the pin with the use of PinChangeInterrupts. Which I have merged into my own mpflaga/Arduino-IRremote fork, that adds several other features.
So you could use any of the above libraries. Or create your own app that uses either of the below to capture edges.

polls on a Timer event (e.g. 50uS)
captures the micros() on a PinChangeInterrupt
uses Input Capture Interrupts to grab the exact time

Brilliant answer. The Arduino-IRremote is a very high quality library. Easily readable, and has a lot of well thought out design that means it is very reliable.

Here is some test data of a pulseIn test. One Arduino sent what were supposed to be 14us pulses, and the other spat out this data:

18,18,18,12,18,18,18,18,18,18,18,18,18,18,18,18,18,24,19,18,18,18,18,18,24,18,18,18,19,18,18,12,18,18,19,18,18,18,18,18,18,18,18,18,18,18,19,18,19,24,18,18,18,18,18,18,18,24,18,18,18,18,18,18,18,18,18,18,18,18,18,19,18,18,18,18,18,18,18,18,18,18,19,18,18,18,11,18

As you can see, the pulses are by no means accurate. The time would be more accurate if the sending and recieving ends were written in assembly, or even offloaded to their own processors.

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


text:
Change the fuses of an Arduino Uno (can an Arduino Uno change its own fuses?)
For now, I'm using an Arduino Uno alone including its 328p (no other external chip to program).
I would like to change its fuses to internal 8 Mhz clock (because then I'll move the 328p out of the Arduino Uno), and for simplicity I'd like to do it from Arduino IDE.
Here is what I tried:

I created a new entry in boards.txt copy-pasted from Uno, fuses modified, like this:
atmega328p.name=Atmega328p
atmega328p.upload.tool=avrdude
atmega328p.upload.protocol=arduino
atmega328p.upload.maximum_size=32256
atmega328p.upload.maximum_data_size=2048
atmega328p.upload.speed=115200

atmega328p.bootloader.tool=avrdude
atmega328p.bootloader.low_fuses=0x62
atmega328p.bootloader.high_fuses=0xD9
atmega328p.bootloader.extended_fuses=0xFF
atmega328p.bootloader.unlock_bits=0x3F
atmega328p.bootloader.lock_bits=0x0F
atmega328p.bootloader.file=optiboot/optiboot_atmega328.hex

atmega328p.build.mcu=atmega328p
atmega328p.build.f_cpu=8000000L
atmega328p.build.board=AVR_UNO
atmega328p.build.core=arduino
atmega328p.build.variant=standard

I selected this board in Tools > Board: Atmega328p
I tried to Upload any sketch (and not Upload with programmer since I have no other chip connected to the Arduino Uno), hoping it would modify the fuses during the (successful) Upload process.

I think it didn't work (when I move the 328p outside of the Uno it doesn't work).
How can I change the fuses for an Arduino Uno directly from Arduino IDE, to enable internal 8 Mhz clock?

PS: "Tools > Burn Bootloader" does not succeed, but I think this is normal, since there is just the Arduino Uno, and no other chip / nothing to use as a "Programmer":

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

You need a programmer to burn fuses.  If you have another arduino then you can use the Arduino as ISP example sketch in the IDE.  You can't burn fuses just using the USB cable like you upload code with.  The only reason that can talk to the chip at all is because there is another chip to convert it to serial and a bootloader on the 328P to allow it to upload code via serial.

Thank you for your answer. Just be sure: 1) is it really impossible for an Arduino Uno to change its own fuses ?

if I use a Nano as programmer (Arduino as ISP) to program the Uno, during which process will the fuses be modified? During "Burn bootloader" or during "Upload with programmer"?

As mentioned in the other answer, it seems that it's not possible for an Arduino Uno to change its own fuses.
So here is how I did:

I used a Nano (loaded with "Arduino as ISP") as programmer for the Uno with this classical wiring (except that in my case, the left board, the programmer, is a Nano):

I added this to boards.txt (source here):
##############################################################
atmega328bb.name=ATmega328 on a breadboard (8 MHz internal clock)
atmega328bb.upload.protocol=arduino
atmega328bb.upload.maximum_size=30720
atmega328bb.upload.maximum_data_size=2048
atmega328bb.upload.speed=57600
atmega328bb.upload.tool=avrdude
atmega328bb.bootloader.tool=arduino:avrdude
atmega328bb.bootloader.low_fuses=0xE2
atmega328bb.bootloader.high_fuses=0xDA
atmega328bb.bootloader.extended_fuses=0x05
atmega328bb.bootloader.file=atmega/ATmegaBOOT_168_atmega328_pro_8MHz.hex
atmega328bb.bootloader.unlock_bits=0x3F
atmega328bb.bootloader.lock_bits=0x0F
atmega328bb.build.mcu=atmega328p
atmega328bb.build.f_cpu=8000000L
atmega328bb.build.core=arduino
atmega328bb.build.variant=standard
atmega328bb.build.board=AVR_BARE

I used "Programmer: Arduino as ISP", then "Burn bootloader" then "Upload with programmer" with any sketch.
Then the fuses are programmed to Internal 8 Mhz, and we can take the ATmega328p out of the Uno and move it on a breadboard! Working now :)

This is technically possible, but tricky.
First you'd have to wire up the Arduino with some jumpers in such a way that the 328P can use its ICSP header to reprogram the 16U2/8U2 via that chips own header. With the right custom firmware in place you could then re-wire the board so that the 16U2 changes the fuses of the 328P upon boot and reuploads the firmware before switching into its usual function. Then it's just a matter of having the 328P reprogram the 16U2 with the original DFU firmware, and presto! An Arduino that changed its own fuses!
If you just need to change the fuses without a ICSP programmer then that can be done by just programming the 16U2 chip directly through its USB port (although technically that doesn't qualify as the Uno "programming itself").


text:
How to use ATtiny pins that are usually 'reserved' for chip programming?
How to program an ATtiny45 to use the pins 1, 5, 6, 7 (i.e. PB5, PB0, PB1, PB2) as input or output?
pinMode(5, OUTPUT);
pinMode(0, OUTPUT);
pinMode(1, INPUT);
pinMode(2, INPUT);
digitalWrite(5, HIGH);
...

These pins are usually used to program the ATtiny itself, so how to avoid a conflict?
Of course, I could just avoid these 4 pins, but then as there are also pins for VCC and GND, there would be only 2 pins left: PB3, PB4!
Question: how to use the pins as input/output that are usually used for ATtiny programming?

Linked question:

Should I connect pins 1, 5, 6, 7 of the ATtiny to the programmer
Or should I connect pins 1, 5, 6, 7, as well as 8 and 4 (VCC and GND) of the ATtiny to the programmer?

If the second bullet is correct, when connecting VCC and GND, won't it make the ATtiny run the previously uploaded code?

Clue: They aren't reserved for programming. They double as the programming pins.

The ATTiny chips commonly used in Arduino-like boards, such as the Adafruit Trinket or the Digispark USB will usually have a bootloader which runs before your own code. The bootloader checks for a certain state on the USB port of the board, to see if something is waiting to write a new program to the chip.
The bootloader accepts new code from the host computer, if present, and writes it to a certain location in flash memory. If the bootloader does not find anything connected to the USB connector trying to load a new program, then it (the bootloader) starts executing from flash at the location where your program has been stored.
But, what if you want to write a new bootloader, or not have a bootloader? In that case, you can write new software using the MOSI, MISO, and SCK (clock) pins if the RESET pin is pulled to ground.
See:
http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf#page=151
In order to make use of all 6 non-power pins as I/O for the Trinket or Digispark, a "fuse" is set in the ATTiny chip which disables the RESET pin's normal purpose of holding the chip in reset. This means you cannot pull RESET to ground and load a program the normal way.
If the RESET pin is disabled, and the bootloader is not present, then there is another method for loading software, called "High Voltage Serial Programming". Not to worry, the "high" voltage is is about 12V.
See:
http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85_Datasheet.pdf#page=155
You can find schematics, or purchase kits/products that allow you to program an ATTiny chip in HV mode online. Many use the small 12V "A23" or "A27" batteries commonly found in RF remote control transmitters to get the 12V signal to put the chip in high-voltage programming mode.

this looks like an answer to OP's other question

Both seem to be related...

Thank you for your answer!

@Basj If this answers your question, please mark it.

You can just normally use all pins except for the reset pin (pin 0). When you want to program the Attiny, you just connect the programmer. It will reset the Attiny through the reset pin and put it into ISP programming mode. At that point your code hasn't run.
Note: If you want to program the Attiny while it still sits in its circuit, you have to be careful, that the connected circuit does not disturb the ISP communication. The safest way is to disconnect the Attiny from its circuit and then program it.

Also account for the ISP communication disturbing your connected circuit.

Just to be sure: when I use Arduino Uno as ISP programmer for an ATtiny, I usually connect pins 1, 5, 6, 7. Do I also need to connect VCC and GND of the ATtiny to VCC and GND of the Arduino Uno? If so, when connecting VCC and GND, won't it make the ATtiny run the previous code? (I updated the question at the end to include this remark).

Yes, you need to also connect GND and VCC. Unless your ATTiny project has it's own power-supply/batteries ( in which case you still need to connect GND). The programmer will pull the reset pin LOW, which will stop your original program from running and enter the ATTiny into "ISP mode".


text:
Motor with ultrasonic sensor
I am new to programming so bear with me.
I am writing a simple code to control a motor such that the motor will turn at full speed as long as the sensor does not detect an object within 5" of the sensor. If it does see something at 5 inches or less, then I want  to motor to stop.
My question is this: When using an IF statement, do you have to have the ELSE, or can you simply do two IF statements with no ELSE?
Here is my example:

int motorpin1 = 10 , motorpin2 = 11;
int trig = 12;
int echo = 9;
float distance;
float time;

void setup()
{
  pinMode (motorpin1, OUTPUT);
  //yellow wire
  pinMode (motorpin2, OUTPUT);
  //blue wire

  pinMode (trig, OUTPUT);
  pinMode (echo, INPUT);
  Serial.begin (9600);

}

void loop()
{
 // setup ultrasonic sensor to control
 //motor
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  time = pulseIn(echo, HIGH);
  distance = time/148.1;

  Serial.println(distance);

 if distance <5,digitalWrite (motorpin1, LOW);
 digitalWrite (motorpin2, LOW);

 if distance >=5, digitalWrite (motorpin1, HIGH);
 digitalWrite (motorpin2, LOW);
 delay (1000); //wait for 1 second

Is there a better way to do this with an ELSE statement? I want to capture the parameter where the code controls the specific parameters of >5  and then <or=5. Also, my next thing is to pause, and reverse the motor if after 1 second, the sensor still sees an object <=5.
Definitely a learning curve for this old brain of mine!

did you try to compile your code?

start thinking about if statements in your everyday life ... they happen all the time ... for example if (red light) {stop car}; ... then think if there would be an else block .... don't forget that you can put any command in the else block ... else if is useful

You can do something along the line of
if (distance < 5) {
    digitalWrite (motorpin1, LOW);
}
else {
    digitalWrite (motorpin1, HIGH);
}

It seems like you only set motorpin2 to LOW and never to HIGH. If you don't want to set it HIGH, move that line to the setup() section. There is no need to keep setting it LOW.

you could use a C++ ternary operator ... replace your six lines with one line ... digitalWrite (motorpin1, (distance < 5) ? LOW : HIGH );

@jsotola Well, if you're to bother going that route, the ternary operator is itself unnecessary: digitalWrite (motorpin1, !(distance < 5)); or just  digitalWrite (motorpin1, distance >= 5);

it depends on if HIGH is equal to true and LOW is equal to false

You could use a ternary operator and I do this myself, but since the question is asked by a beginner, I valued readability over reducing number of lines.

@jsotola, something considered and discarded. No one in their right mind will design a core with LOW as truthy an vice versa. Anyway, particularly for new people it's okay the way it is.


text:
Adafruit Si4713/IDE not working
My IDE shows "Adafruit Radio - Si4713 Test", but without "RDS on!", which is supposed to show up. The radio I use (Inscabin M60) shows static. Am I doing something wrong?
Adafruit Radio - Si4713 Test
Couldn't find radio?
Adafruit Radio - Si4713 Test
Couldn't find radio?
Adafruit Radio - Si4713 Test
Couldn't find radio?
Adafruit Radio - Si4713 Test
Couldn't find radio
Adafruit Radio - Si4713 Test
The italic represents where I made a mistake.
This is the code, where I only changed the error message. I previously changed the #define FMSTATION to 9670, but KTCK has taken that signal, so I changed it back.
/***************************************************
This is an example for the Si4713 FM Radio Transmitter with RDS
Designed specifically to work with the Si4713 breakout in the
adafruit shop
----> https://www.adafruit.com/products/1958
These transmitters use I2C to communicate, plus reset pin.
3 pins are required to interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
Many thx to https://github.com/phrm/fmtx/blob/master/firmware/firmware.ino !
****************************************************/
#include <Wire.h>
#include <Adafruit_Si4713.h>
#define _BV(n) (1 << n)

#define RESETPIN 12

#define FMSTATION 10230      // 10230 == 102.30 MHz

Adafruit_Si4713 radio = Adafruit_Si4713(RESETPIN);

void setup() {
  Serial.begin(9600);
  Serial.println("Adafruit Radio - Si4713 Test");

  if (! radio.begin()) {  // begin with address 0x63 (CS high default)
    Serial.println("Couldn't find radio");
    while (1);
  }

  // Uncomment to scan power of entire range from 87.5 to 108.0 MHz
  /*
  for (uint16_t f  = 8750; f<10800; f+=10) {
   radio.readTuneMeasure(f);
   Serial.print("Measuring "); Serial.print(f); Serial.print("...");
   radio.readTuneStatus();
   Serial.println(radio.currNoiseLevel);
   }
   */

  Serial.print("\nSet TX power");
  radio.setTXpower(115);  // dBuV, 88-115 max

  Serial.print("\nTuning into ");
  Serial.print(FMSTATION/100);
  Serial.print('.');
  Serial.println(FMSTATION % 100);
  radio.tuneFM(FMSTATION); // 102.3 mhz

  // This will tell you the status in case you want to read it from the chip
  radio.readTuneStatus();
  Serial.print("\tCurr freq: ");
  Serial.println(radio.currFreq);
  Serial.print("\tCurr freqdBuV:");
  Serial.println(radio.currdBuV);
  Serial.print("\tCurr ANTcap:");
  Serial.println(radio.currAntCap);

  // begin the RDS/RDBS transmission
  radio.beginRDS();
  radio.setRDSstation("AdaRadio");
  radio.setRDSbuffer( "Adafruit g0th Radio!");

  Serial.println("RDS on!");

  radio.setGPIOctrl(_BV(1) | _BV(2));  // set GP1 and GP2 to output
}

void loop() {
  radio.readASQ();
  Serial.print("\tCurr ASQ: 0x");
  Serial.println(radio.currASQ, HEX);
  Serial.print("\tCurr InLevel:");
  Serial.println(radio.currInLevel);
  // toggle GPO1 and GPO2
  radio.setGPIO(_BV(1));
  delay(500);
  radio.setGPIO(_BV(2));
  delay(500);
}

Your Arduino using this code obviously fails to communicate with the radio. Please show how you've connected the board to your Arduino.


text:
RFID system for proximity detection with data logging
I am wondering if anybody has ideas for developing an Arduino-based system that would use RFID to log occurrences when two people are in close proximity to each other (e.g., <= 1 meter).  Ideally, I would like to construct something that would operate in a manner very similar to the OpenBeacon system -- and, preferably, the events/data would be transmitted via wi-fi in real time.
My ideas are as follows, so any feedback or alternative solutions would be greatly appreciated.  (Please keep in mind that I am not an engineer!)
I am thinking of using a wi-fi enable microprocessor (e.g., Arduino Yun) that would serve as the reader or detection system.  For beta-testing, this device could be set in an enclosed case and attached to a belt.  I presume it would require a fairly robust battery supply.  The other person would be wearing an RFID tag that has a range of <= 1 meter and would log the event.  Ideally, a reading would take place roughly every 30 seconds, and the captured event would be transmitted over wi-fi.
Here are a few other things to keep in mind:

The people using the hardware should not have to do anything other than simply wear the constructed devices.
The reader itself should be as small as possible.
My ultimate goal is the data logging of the proximal events.

I am certainly open to other technologies, as my ultimate goal is simply the proximity detection with data logging (preferably via wi-fi).
Thanks in advance!
Brian

Consider using two basic XXMhz transceivers:
-Master loops through used ID's and transmits them one at a time.
-If a belt receives an ID other than it's own, it remains quiet.
-If a belt receives it's own ID, it transmits "Marco" (quietly) to the other belts.
-For a receiver to hear the very quiet signal, it will need to be very close.
-The RSSI signal can be monitored for signal strength to determine close(enough) proximity.
-If sufficient proximity is detected, the event is reported to the Master.
-If it receives no response, it informs the Master.
-Master proceeds to the next ID.

In this setup, you only need to provide networking (WiFi/Ethernet) to the master. (cheaper)
So that each belt can identify the others, "Marco" could be the transmitter's ID, but you'll need to add some sort of "protocol" so the belts know if the ID they hear is from the Master or another belt.
If ID is only 7 bits, the "protocol" could be as simple as a bitmask:
Server = Send(ID &  (1 << 7)); //1XXXXXXX
  Belt = Send(ID & ~(1 << 7)); //0XXXXXXX

Belts only reply to their ID if MSB is 1
This example has excessive range for your purpose (250m); these radios will be screaming at each other and the RSSI signal is unlikely to provide meaningful data.
http://www.seeedstudio.com/depot/nRF24L01Module-p-1394.html
Using RFID, you are wanting (very)long range from an (intentionally) short-ranged system.
Using ISM, you are wanting (very)short range from an (intentionally) long-ranged system.

Neither is 100%, but both should work.

This is a cheapo 125khz reader from Seeed Studio (Shenzhen):
http://www.seeedstudio.com/wiki/index.php?title=Electronic_brick_-_125Khz_RFID_Card_Reader
The range on it is very limited and I'm not suggesting you buy that specific one. Instead, just notice the pinout, +,-,TX,RX. You will find many, many readers with that same pinout. When a tag is detected, the reader blindly transmits the ID via UART (serial). You will also find many WiFi modules with similar TX/RX pins.
In your situation, the Arduino is actually wasteful since it's only purpose will be to mirror the reader's data from it's RX to it's TX. It's better to cut out the middle-man and just connect the (voltage-compatible) reader directly to the WiFi module to save power.
Many wireless modules are capable of automatically going low-power when there is nothing to do. Part of the receiver circuit will activate for transmitting, but since you are only transmitting sporadically from the belts, neither the receiver or transmitter needs to be powered constantly. I think you will be pleasantly surprised by the battery life.

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


text:
Why is the serial monitor not printing a variable?
I connected an Adafruit color sensor to my Arduino and am having it make calculations. However, when the calculations are done and sent to the serial monitor, it says "NDVI: " without printing the value. The code is attached below. Thanks!
Code:
/* TSL2591 Digital Light Sensor */
/* Dynamic Range: 600M:1 */
/* Maximum Lux: 88K */

#include <Wire.h>
#include <Adafruit_Sensor.h>
#include "Adafruit_TSL2591.h"

#define IR850 5
#define IR940 6
#define BLUE 9
#define GREEN 10
#define RED 11

// Example for demonstrating the TSL2591 library - public domain!

// connect SCL to I2C Clock
// connect SDA to I2C Data
// connect Vin to 3.3-5V DC
// connect GROUND to common ground

Adafruit_TSL2591 tsl = Adafruit_TSL2591(2591); // pass in a number for the sensor identifier (for your use later)

/**************************************************************************/
/*
    Displays some basic information on this sensor from the unified
    sensor API sensor_t type (see Adafruit_Sensor for more information)
*/
/**************************************************************************/
void displaySensorDetails(void)
{
  sensor_t sensor;
  tsl.getSensor(&sensor);
  Serial.println(F("------------------------------------"));
  Serial.print  (F("Sensor:       ")); Serial.println(sensor.name);
  Serial.print  (F("Driver Ver:   ")); Serial.println(sensor.version);
  Serial.print  (F("Unique ID:    ")); Serial.println(sensor.sensor_id);
  Serial.print  (F("Max Value:    ")); Serial.print(sensor.max_value); Serial.println(F(" lux"));
  Serial.print  (F("Min Value:    ")); Serial.print(sensor.min_value); Serial.println(F(" lux"));
  Serial.print  (F("Resolution:   ")); Serial.print(sensor.resolution, 4); Serial.println(F(" lux"));
  Serial.println(F("------------------------------------"));
  Serial.println(F(""));
  delay(500);
}

/**************************************************************************/
/*
    Configures the gain and integration time for the TSL2591
*/
/**************************************************************************/
void configureSensor(void)
{
  // You can change the gain on the fly, to adapt to brighter/dimmer light situations
  //tsl.setGain(TSL2591_GAIN_LOW);    // 1x gain (bright light)
  //tsl.setGain(TSL2591_GAIN_MED);      // 25x gain
  tsl.setGain(TSL2591_GAIN_HIGH);   // 428x gain

  // Changing the integration time gives you a longer time over which to sense light
  // longer timelines are slower, but are good in very low light situtations!
  //tsl.setTiming(TSL2591_INTEGRATIONTIME_100MS);  // shortest integration time (bright light)
  // tsl.setTiming(TSL2591_INTEGRATIONTIME_200MS);
  // tsl.setTiming(TSL2591_INTEGRATIONTIME_300MS);
  // tsl.setTiming(TSL2591_INTEGRATIONTIME_400MS);
  // tsl.setTiming(TSL2591_INTEGRATIONTIME_500MS);
  tsl.setTiming(TSL2591_INTEGRATIONTIME_600MS);  // longest integration time (dim light)

  /* Display the gain and integration time for reference sake */
  Serial.println(F("------------------------------------"));
  Serial.print  (F("Gain:         "));
  tsl2591Gain_t gain = tsl.getGain();
  switch(gain)
  {
    case TSL2591_GAIN_LOW:
      Serial.println(F("1x (Low)"));
      break;
    case TSL2591_GAIN_MED:
      Serial.println(F("25x (Medium)"));
      break;
    case TSL2591_GAIN_HIGH:
      Serial.println(F("428x (High)"));
      break;
    case TSL2591_GAIN_MAX:
      Serial.println(F("9876x (Max)"));
      break;
  }
  Serial.print  (F("Timing:       "));
  Serial.print((tsl.getTiming() + 1) * 100, DEC);
  Serial.println(F(" ms"));
  Serial.println(F("------------------------------------"));
  Serial.println(F(""));
}

/**************************************************************************/
/*
    Program entry point for the Arduino sketch
*/
/**************************************************************************/
void setup(void)
{
  pinMode(IR850, OUTPUT);
  pinMode(IR940, OUTPUT);
  pinMode(RED, OUTPUT);
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);
  digitalWrite(IR850, LOW);
  digitalWrite(IR940, LOW);
  digitalWrite(RED, LOW);
  digitalWrite(GREEN, LOW);
  digitalWrite(BLUE, LOW);
  Serial.begin(9600);

  Serial.println(F("Starting Adafruit TSL2591 Test!"));

  if (tsl.begin())
  {
    Serial.println(F("Found a TSL2591 sensor"));
  }
  else
  {
    Serial.println(F("No sensor found ... check your wiring?"));
    while (1);
  }

  /* Display some basic information on this sensor */
  displaySensorDetails();

  /* Configure the sensor */
  configureSensor();

  // Now we're ready to get readings ... move on to loop()!
}

/**************************************************************************/
/*
    Shows how to perform a basic read on visible, full spectrum or
    infrared light (returns raw 16-bit ADC values)
*/
/**************************************************************************/
void simpleRead(void)
{
  // Simple data read example. Just read the infrared, fullspecrtrum diode
  // or 'visible' (difference between the two) channels.
  // This can take 100-600 milliseconds! Uncomment whichever of the following you want to read
  uint16_t x = tsl.getLuminosity(TSL2591_VISIBLE);
  //uint16_t x = tsl.getLuminosity(TSL2591_FULLSPECTRUM);
  //uint16_t x = tsl.getLuminosity(TSL2591_INFRARED);

  Serial.print(F("[ ")); Serial.print(millis()); Serial.print(F(" ms ] "));
  Serial.print(F("Luminosity: "));
  Serial.println(x, DEC);
}

/**************************************************************************/
/*
    Show how to read IR and Full Spectrum at once and convert to lux
*/
/**************************************************************************/
uint16_t ir, full;
void advancedRead(void)
{
  // More advanced data read example. Read 32 bits with top 16 bits IR, bottom 16 bits full spectrum
  // That way you can do whatever math and comparisons you want!
  uint32_t lum = tsl.getFullLuminosity();
  uint16_t ir, full;
  ir = lum >> 16;
  full = lum & 0xFFFF;
  Serial.print(F("[ ")); Serial.print(millis()); Serial.print(F(" ms ] "));
  Serial.print(F("IR: ")); Serial.print(ir);  Serial.print(F("  "));
  Serial.print(F("Full: ")); Serial.print(full); Serial.print(F("  "));
  Serial.print(F("Visible: ")); Serial.print(full - ir); Serial.print(F("  "));
  Serial.print(F("Lux: ")); Serial.println(tsl.calculateLux(full, ir), 6);
}

/**************************************************************************/
/*
    Performs a read using the Adafruit Unified Sensor API.
*/
/**************************************************************************/
void unifiedSensorAPIRead(void)
{
  /* Get a new sensor event */
  sensors_event_t event;
  tsl.getEvent(&event);

  /* Display the results (light is measured in lux) */
  Serial.print(F("[ ")); Serial.print(event.timestamp); Serial.print(F(" ms ] "));
  if ((event.light == 0) |
      (event.light > 4294966000.0) |
      (event.light <-4294966000.0))
  {
    /* If event.light = 0 lux the sensor is probably saturated */
    /* and no reliable data could be generated! */
    /* if event.light is +/- 4294967040 there was a float over/underflow */
    Serial.println(F("Invalid data (adjust gain or timing)"));
  }
  else
  {
    Serial.print(event.light); Serial.println(F(" lux"));
  }
}

int lightvalue;
int NDVIred;
int NDVIinfrared;
int NDVI;
boolean (hasrun) = false;

/**************************************************************************/
/*
    Arduino loop function, called once 'setup' is complete (your own code
    should go here)
*/
/**************************************************************************/
void loop(void)
{
  lightvalue = 255;
  //simpleRead();
  //advancedRead();
  //unifiedSensorAPIRead();
  if(hasrun==false){
  analogWrite(RED, lightvalue);
  advancedRead();
  NDVIred = full;
  delay(5000);
  analogWrite(IR940,lightvalue);
  advancedRead();
  NDVIinfrared=full;
  NDVI=(NDVIinfrared-NDVIred)/(NDVIinfrared+NDVIred);
  Serial.print("NDVI: "); Serial.write(NDVIred);
  delay(1000);
  exit(0);
  }
}

You wrote:

Serial.print("NDVI: "); Serial.write(NDVIred);

You are misusing here the Serial.write() method. This method is meant
for sending raw bytes through the serial port. Since you are printing
text, you probably want the numeric value NDVIred to be printed out as
text, as a decimal number.
For printing text, use Serial.print() and Serial.println():
Serial.print("NDVI: "); Serial.println(NDVIred);

I did that and it now prints "NDVI: 0". Is there a problem with the variables?

@Chris: No, no problem with the variable. You are just seeing its value, which happens to be zero.

No, the code does what it's supposed to do. There is however a problem with the scope of the variable named full. It is defined as a global variable and again as a local variable inside of advancedRead(). Which explains why NVDIred is assigned a value of zero (which is the value of the still unchanged global full variable). Remove the definition of full from advancedRead() to fix this.


text:
LCD displays more digits than serial monitor
I am doing a BPM monitoring system. The serial monitor displays accurate BPM values ranging from 60 to 100+. But my LCD display is not accurate. Example, on the serial monitor, my bpm is about 67, but on the LCD it displays 676. What do I need to do to fix it?
PulseSensorPlayground pulseSensor; // Creates an instance of the PulseSensorPlayground object called "pulseSensor"

void setup() {
    Serial.begin(9600); // For Serial Monitor
    lcd.begin();
    lcd.backlight();

    // Configure the PulseSensor object, by assigning our variables to it.
    pulseSensor.analogInput(PulseWire);
    pulseSensor.blinkOnPulse(LED13); //auto-magically blink Arduino's LED with heartbeat.
    pulseSensor.setThreshold(Threshold);

    // Double-check the "pulseSensor" object was created and "began" seeing a signal.
    if (pulseSensor.begin()) {
        Serial.println("We created a pulseSensor Object !"); //This prints one time at Arduino power-up, or on Arduino reset.
    }
}

void loop() {
    int myBPM = pulseSensor.getBeatsPerMinute(); // Calls function on our pulseSensor object that returns BPM as an "int".
    // "myBPM" hold this BPM value now.
    if (pulseSensor.sawStartOfBeat()) { // Constantly test to see if "a beat happened".
        Serial.println("♥ A HeartBeat Happened ! "); // If test is "true", print a message "a heartbeat happened".
        Serial.print("BPM: "); // Print phrase "BPM: "
        Serial.println(myBPM); // Print the value inside of myBPM.

        lcd.setCursor(0,0);
        lcd.print("BPM: "); // Print phrase "BPM: "
        lcd.print(myBPM);
    }
    delay(50); // considered best practice in a simple sketch.
}

I fixed the formatting and the indentation for you. You should always keep the indentation right (the Arduino IDE even has an autoformatting function for this), because it helps you spot structural errors.

What happens if you add lcd.print("    "); after the other LCD code to fill the space behind the BPM with spaces? I suspect that the additional 6 comes from a former display call and just is retained because you don't overwrite it. Adding the spaces will make sure, that the space after the BPM is always empty.

I am thinking the same thing. And if I am understanding this correctly, you mean adding lcd.print("    "); after lcd.print("BPM: ");? I already did sir but the former display still keeps displaying.

@AccelLim: You need to insert lcd.print("  "); after lcd.print(myBPM);. You want the last digit of the number to be removed.

If you use the standard LCD lib from Arduino you could clear the Screen with lcd.clear() instead of simply position the cursor to (0,0) with lcd.setCursor(0,0). Link: https://www.arduino.cc/en/Reference/LiquidCrystalClear

As PMF said: Insert it after lcd.print(myBPM);. Then please report back

its working fine now. Thank you very much :)

The additional "6" seems to come from one of the first values. Maybe the first value printed is just a rogue value and all the following values are correct.
The point is that this rogue value may take one more character on the display than the other (correct) values. And when you just move the cursor and print again the previously displayed text is only changed if it is overwritten by the new text. The correct values are shorter, so the last digit of the rogue value is not overwritten. This of course doesn't happen with Serial, since Serial doesn't print to the same space again and again (like a LCD does with its limited space).
What to do now: You can use lcd.clear() to remove all text from the display before printing new values. Though this can lead to a noticeable flicker on the display. Often it is better to just make sure to overwrite all possible leftover text with spaces via lcd.print(" ");. Insert this after the lcd.print(myBPM) (since you want to remove all leftover digits after that). In this case you only have 1 leftover digit, so one space is enough. To be sure that this won't happen again when for whatever reason you get more than one leftover digit you can use multiple spaces (lcd.print("    ");).


text:
Battery solution Nano 33 iOT
Since the Nano 33 boards are quite new right now, I haven't found any details on how to hook one up with batteries.
I'm pretty daft when it comes to electronics (I'm a software man), and I read that the new Nano 33 requires 3.2V, which is a bit of a departure from the 5V the old models supported.
From what I can tell, I might be able to use a single LiFePO4 cell. Am I correct in this assumption? And if so, are there any pitfalls in going this route?
EDIT: I might have misunderstood the difference between operating voltage and input voltage. Does this mean that I can plug any AA battery pack in as a power source?

The regulator can take up to 21 V. Use 2 x 18659 Li-Ion batteries in series.

You can either use the 3.3V pin to supply power to the board, or use the Vin pin.
By using the VIN pin to power goes through a (step down) voltage regulator, that provides a nice stable 3.3V to the board. The regulator in the Nano 33 IoT is the MPM3610, which requires an input voltage of at least 4 - 4.5 Volt. Which is more that a LiPo or LiFePo single cell can supply. You could use a multi-cell battery pack. Or a USB power bank. So this solutions is not really ideal.
The other option was to connect the battery directly to the 3.3V pin. The voltage of a LiFePo however changes as it is being discharged. The voltage is around 3.65V when full, and 2.5-2.75V when "empty". The 3.2V rating is called the nominal voltage (kind of an average voltage).
So it's a bit too high when full, and too low when empty. The voltage also isn't regulated, so it can fluctuate a bit, based on the amount of current that's being used.
The maximum voltage for the SAMD21 on this Nano is 3.63V. Maximum voltage for the gyro (LSM6DS3) is 3.6V. The absolute maximum voltage for the radio (NINA-W10) is 3.6V.
So a full LiFePo is slightly too high for the Nano. Though I think you should be fine. But don't try this with a regular LiPo of Lion battery (4.2V when full).

Thanks so much for replying to my question. Do I understand correctly that I could use three 1.5 volt AA batteries connected in a serial fashion to power the nano via the VIN pin?

Not quite. If you take 4V as the low point for voltage regulator, it would stop working if the batteries reach 1.33V, using only around 10% of the AA's total charge. I'd use at least 4 AA cells. Since it's a switching regulator it doesn't really matter what voltage you give it as long as it's between 4V/4.5V and 21V (unlike a linear regulator that just wastes the extra voltage). I'd go for 6 AAs. That way you can run them totally flat. The regulator is also a bit more efficient at a higher voltage.

Thanks a lot! That's exactly what I needed to know.

I tried running the board with  ~9.5V from 6 AA batteries, and while it did power up, the BLE module seems not to be working. I'm trying to figure out where to go from here by posting in the official Arduino forums.

You used the VIN pin, right? Do you have a multimeter, so you can measure the 3.3Volt rail?

I did use the VIN pin indeed! As mentioned, it managed to power a sketch that didn't use the BLE module. I'm not quite sure how to use a multimeter to measure the rail. (hence me being pretty daft with electronics :D)

If you can run some kind of blink sketch, while powered from batteries, the 3.3V is probably fine, but measuring can definitively rule that problem out. To measure, set the multimeter to measure voltage. If it has multiple range settings, select the smallest range that's still above the 3.3Volt. Then connect the black probe to the GND pin on the Nano, and the red prove to the 3.3V pin.

Thanks a bunch! Will do that when I get back to work tomorrow. (Can't believe I get to do this kind of stuff at work! Next up in the series: Me doing things I have no idea how to do)

I do have a second Nano 33 BLE that I can try. Tomorrow I will also try with a normal lithium power bank through the USB to see if that works. The price you pay for being an early adopter huh?

So the BLE only works when powered via USB?

That's what it seems like to me. Tomorrow I will use LED blink codes to debug the BLE sketch. I want to see how far the code execution reaches before it stops.

Haha! I think it was me leaving the "wait for serial" code in the example, which doesn't go past while(!Serial). Sorry, that's a stupid mistake from my part.


text:
Are there any GPS data pusher for Arduino?
I plan to build a GPS logger for my car using a GPS device, an Arduino board and a SD Card. The plan is that the GPS device forwards the position to the Arduino which is responsible for storing the data on the SD card. However, I would like to regularly (say every hour) send my current position to a server at home.
For that you can use GPS pusher or puller, but I couldn't find any such devices on the Internet. Do these devices exist? What are my (other) options?

Not sure what goes into a data pusher but you could probably do it cheaper with a GSM module and server. - It wouldn't surprise me to find that in the device you're referring to.

Yes, that would be possible, but then I need a SIM and a dataplan imho.

So you want something besides the GSM shield?

If possible, yes.

How do you want to communicate with a server over the internet?

How do you expect to "push" gps data to a server? The only options you have available to you is 1) Internet (as suggested, bluetooth to phone and phone internet connection). 2) GSM module and either a) use data plan to push via internet, or b) use SMS to another device at the server location. Either way, you're going to need to transport the data over some medium for which you are going to have to have a "plan". As has been asked, what is the server connected to (I suspect the internet). There's no FREE magical internet like medium the Arduino can latch onto.

Check this shield out, it sounds almost exactly like what you need, plus it has OBD2 (CAN) access to log RPM, indicated speed, steering wheel angle, and whatever else your car exposes. You can get a GPS module from Sparkfun as well. Matter of fact, I'm using it in a very similar project, but development is paused until I upgrade to a Mega, since I've run out of RAM.

The shield comes with example code that's hacked together from other sources but it serves the demo purpose well.
As for pushing to a server--that'd be tougher. I would go the route of a Bluetooth shield and make a corresponding app for the phone that pushes the data.

Hi Nick and thanks. I see that you can use this for logging. Put what about pushing data to a remote host?

Easiest would probably be a Bluetooth shield and an app on an Android phone.

Yes, but then I still need a Internet connection.

How else are you going to access a server on the internet?


text:
Are there any pressure sensor for 22 kg (~50lbs) and more?
I'm looking for pressure sensors up to 22 kg and more. So far the highest capacity I could found was 25 lbs. Do higher ones not exist?

Why do you need to measure such a high pressure?

Use a lever to reduce your force. If you have a 4 foot lever, with a pivot on one end, and your sensor under the other, if you apply 10 pounds of force 1 foot from the pivot, you will get 2.5 pounds of force at on the sensor. This is how bathroom scales work to measure large loads with a small sensor.

Yes, they exist - do a search for "load cell"

Your problem may be that you are using sub-optimal search terms.
The kilogram is not a unit of pressure, but instead of mass.
Scales technically do not sense mass, but instead sense force.
This is assumed to be the force exerted by a resting body under earth gravity.
Pressure is force over an area, such as pounds-per-square-inch (PSI) or the Pascal which is a newton per square meter.
Anyway, the sensor you want is called a force cell.
The nice ones are rated in newtons or kilonewtons, with a kg being equivalent to
9.8 newtons.
Here is a load cell that take up to 50 kg.
http://www.phidgets.com/products.php?product_id=3135
Sources:
http://en.wikipedia.org/wiki/Force


text:
Trouble with variable types and integrating DHT11 temperature sensor
I am trying to modify this sketch;
https://github.com/itsallvoodoo/home_automation/blob/master/Arduino_HVAC_Controller/HVAC_Controller/HVAC_Controller.ino
But I have a different temperature sensor, a DHT11, and I am using the libraries from Adafruit.
The DHT11 can't be constantly polled, 1 second intervals is the maximum rate.
I am currently working (fighting) with the portion towards the bottom in the section:
boolean getTemp() {

As my sketch stands, I have "currentTemp" statically assigned to 79 degrees. When I upload, the arduino acts as I would expect it to given that data.
If I change it to 0 (zero) and try to set the temp by reading the sensor in the section starting at line 237  like this;
boolean getTemp() {

  currentTemp = 0;
  long temp = 0;

  if ((millis() - TempLastCheck) > 2000) {
    TempLastCheck = millis();
    //  currentTemp = dht.readTemperature(true);
      temp = dht.readTemperature(true);
     Serial.println(dht.readTemperature(true));
  }

The LCD is blank after it restarts, and the arduino triggers the "heat" relay because the temperature is 0 (zero)
I'm sure I'm missing something simple, because the DHT11 outputs floats, or something... I'm too new to this language to know what I'm missing. Any help will be greatly appreciated.
// name:     HVAC_Controller.ino
// author:   Chad Hobbs

// -------------LIBRARIES---------------- THESE ARE REQUIRED TO BE IN YOUR SKETCHBOOK\LIBRARY FOLDER FOR COMPILING ----
#include <Wire.h>                   // Protocol to communicate with I2C devices
#include <Adafruit_MCP23017.h>      // LCD protocol
#include <Adafruit_RGBLCDShield.h>  // LCD + Button shield protocol
#include "DHT.h"                // DHT11 Temp/Humidity Sensor
// --------------PARAMETERS---------------------
int heat = 55;                    // This is the default heater trigger temp setting
int cool = 70;                    // This is the default cooling trigger temp setting
int buffer = 1;                   // This is the range away from the setpoint the heat or AC will overcool/heat to prevent shorter cycles
int heatPin = 7;                  // Digital pin used for turning on the heater relay
int coolPin = 8;                  // Digital pin used for turning on the AC relay
int cycleTime = 60;               // The length of time to delay running the AC or heat to prevent short cycling
boolean heatRunning = false;      // Stores whether the heater is currently running or not
boolean coolRunning = false;      // Stores whether the AC is currently running or not
long currentTemp = 0;             // Current room temperature

int serialSpeed = 9600;           // Default serial comm speed
long oldTemp = 0;                 // Used to only update the currentTemp if the temp has changed
unsigned long timeOut;            // Backlight timeout variable
boolean editable = false;         // Determines whether or not button presses will do anything, used to avoid accidental changes
char* menu[] = {"Cooling", "Heating"};  // Menu display for either setting the high point or the low point of the temp range
int menuPosition = 1;             // Current position in the setting menu
unsigned long heatLastRan;        // Stores the time the heater last ran
unsigned long coolLastRan;        // Stores the time the AC last ran
unsigned long TempLastCheck;      // Stores the last sensor reading ran

// -------------Library Interaction--------------
// Create our LCD Shield instance
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();
#define ON 0x7            // For single color LCD, set on to white
#define OFF 0x0           // For single color LCD, set off to black

#define DHTTYPE DHT11   // DHT 11
#define DHTPIN 4     // what pin we're connected to
DHT dht(DHTPIN, DHTTYPE);

// ----------------------------------------------------------------------------------------
// Function Name: setup()
// Parameters:    None
// Returns:       None
// Description:   This function executes housekeeping duties and staging for the loop() function; executed once
// ----------------------------------------------------------------------------------------
void setup() {

  //  pinMode(busPin,INPUT);  // Designate temperature bus pin data direction
  pinMode(heatPin, OUTPUT);               // Heat circuit relay
  pinMode(coolPin, OUTPUT);               // Cooling circuit relay
  Serial.begin(serialSpeed);

  lcd.begin(16, 2);       // set up the LCD's number of columns and rows
  lcd.setBacklight(ON);   // Start off with backlight on until time-out
  timeOut = millis();     // Set the initial backlight time
  TempLastCheck = millis();  // Set the initial sensor timing

  dht.begin();
}

// ----------------------------------------------------------------------------------------
// Function Name: loop()
// Parameters:    None
// Returns:       None
// Description:   This is the main executing block of the program, calling all ancillary functions to operate the Arduino
// ----------------------------------------------------------------------------------------
void loop() {
  if ((millis() - timeOut) > 30000) {                   // Turn on backlight for 30 seconds, else turn it off
    lcd.setBacklight(OFF);
    editable == false;
  } else {
    lcd.setBacklight(ON);
  }

  lcd.setCursor(0, 1);                  // Starting position of character printing

  uint8_t buttons = lcd.readButtons();  // Constantly check to see if something has been put on the bus

  // --------------Handle updating Temp Change Display---------------------
  if (getTemp()) {                      // Constantly check to see if the temperature has changed, and update appropriately
    lcd.clear();
    lcd.print("Temp:");
    lcd.print(currentTemp);
  }

  // --------------Handle Button Presses---------------------
  if (buttons) {
    timeOut = millis();
    lcd.setBacklight(ON);

    if (buttons & BUTTON_SELECT) {      // Allow parameters to be changed only if the Select button has been pressed first
      editable = true;
    }
    if (editable) {                     // go to buttonHandler to handle menu switching and parameter manipulations
      buttonHandler(buttons);
    }
  }

  // --------------Handle Heat and Cooling Cycles---------------------
  powerControl();

}

// ----------------------------------------------------------------------------------------
// Function Name: powerControlHandler()
// Parameters:    None
// Returns:       None
// Description:   This function will handle turning AC or Heat off and on based on current temp, timers, and setpoints
// ----------------------------------------------------------------------------------------
void powerControl() {

  // TODO: Add in fan relay control

  // This executes if the heater is running and it gets warm enough to turn off.
  if (heatRunning && (currentTemp > (heat + buffer))) {
    heatRunning = false;
    heatLastRan = millis();
    digitalWrite(heatPin, HIGH);
    return;
  }

  // This executes if the AC is running and it gets cool enough to turn off
  if (coolRunning && (currentTemp < (cool - buffer))) {
    coolRunning = false;
    coolLastRan = millis();
    digitalWrite(coolPin, HIGH);
    return;
  }

  // This executes if it gets cold enough and the heater has not run for a minimum time (short cycle protection)
  if ((currentTemp < heat) && ((millis() - heatLastRan) > cycleTime)) {
    digitalWrite(heatPin, HIGH);
    heatRunning = true;
    return;
  }

  // This executes if it gets hot enough and the AC has not run for 10 minutes (short cycle protection)
  if ((currentTemp > cool) && ((millis() - coolLastRan) > 60)) {
    digitalWrite(coolPin, HIGH);
    coolRunning = true;
    return;
  }

  return;
}

// ----------------------------------------------------------------------------------------
// Function Name: buttonHandler()
// Parameters:    None
// Returns:       Boolean, True if the temperature has changed, else False
// Description:   This function polls the temp sensors, retrieves the values, and then returns
// ----------------------------------------------------------------------------------------
boolean buttonHandler(uint8_t buttons) {

  // --------------PARAMETERS---------------------
  int heatModifier = 0;
  int coolModifier = 0;

  // --------------SETUP---------------------
  lcd.clear();

  // If the UP Button is pushed, increasing the setpoint
  if (buttons & BUTTON_UP) {
    if (menuPosition == 0) {
      coolModifier = 1;
    }
    if (menuPosition == 1) {
      heatModifier = 1;
    }
  }

  // If the Down Button is pushed, decreasing the setpoint
  if (buttons & BUTTON_DOWN) {
    if (menuPosition == 0) {
      coolModifier = -1;
    }
    if (menuPosition == 1) {
      heatModifier = -1;
    }
  }

  // If the Left Button is pushed, change the menu context
  if (buttons & BUTTON_LEFT) {
    if (menuPosition == 1) {
      menuPosition = 0;
    } else {
      menuPosition = 1;
    }
  }

  // If the Right Button is pushed, change the menu context
  if (buttons & BUTTON_RIGHT) {
    if (menuPosition == 1) {
      menuPosition = 0;
    } else {
      menuPosition = 1;
    }
  }

  // If anything has been modified, update accordingly
  heat = heat + heatModifier;
  cool = cool + coolModifier;

  // Print proper menu title and setpoint
  lcd.setCursor(0, 0);
  lcd.print(menu[menuPosition]);
  lcd.setCursor(0, 1);
  lcd.print("Setpoint: ");

  if (menuPosition == 0) {
    lcd.print(cool);
  }
  if (menuPosition == 1) {
    lcd.print(heat);
  }

}

// ----------------------------------------------------------------------------------------
// Function Name: getTemp()
// Parameters:    None
// Returns:       Boolean, True if the temperature has changed, else False
// Description:   This function polls the temp sensors, retrieves the values, and then returns
// ----------------------------------------------------------------------------------------
boolean getTemp() {

  currentTemp = 79;
  long temp = 0;

  if ((millis() - TempLastCheck) > 2000) {
    TempLastCheck = millis();
    //  currentTemp = dht.readTemperature(true);
     //temp = dht.readTemperature(true);
     Serial.println(dht.readTemperature(true));
  }

  /////////////////////////////////////////////////////////////////////////////////////////////////////
  //  sensors.requestTemperatures(); // Send the command to the device to get temperatures

  // Go through devices and read the temperatures
  //  for(int x = 0; x < numOfDevices; x++){
  //   temp = sensors.getTempF(addrs[x]);
  //  if(temp != currentTemp){
  //   currentTemp = temp;
  //    }
  //  }
  /////////////////////////////////////////////////////////////////////////////////////////////////////
  // Check to see if temperature has changed
  if (currentTemp != oldTemp) {
    oldTemp = currentTemp;
    return true;
  }
  else {
    return false;
  }
}

First of, you read the temperature and put it into local variable temp. You need to copy the value from temp into currentTemp.
Secondly, you are reading the temperature twice in a row. Once to assign it to temp and again for the Serial.println.
  if ((millis() - TempLastCheck) > 2000) {
    TempLastCheck = millis();
    currentTemp = dht.readTemperature(true);
    Serial.println(currentTemp);
  }

When setting the currentTemp to 0 inside getTemp, getTemp never return true, because you initialized the value of currentTemp with 0 (long currentTemp = 0;). So it never changed, and the lcd is never updated. Just change it to something like:
long currentTemp = -100;


text:
Building a low voltage disconnect w/ timer - need help with the timer
I'm trying to build almost exactly this device:
http://www.reuk.co.uk/wordpress/reuk-shop-low-voltage-disconnects-lvd/buy-reuk-programmable-low-voltage-disconnect-with-display/
It is a low voltage disconnect but has an interesting feature that requires the "cutoff" and "reconnect" voltages to be reached for 10 seconds before the connection is actually cut/re-connected to prevent premature status changes from voltage spikes/sags (Such as starting a car, or a motor with high start draw)
I need some example code that handles the timer portion. I can handle the "if this voltage is reached, disconnect the relay" (or transistor in the link I provided) part.
I need help making it "If this voltage has reached XX for 10 seconds then -do something-"

Assuming you have a function voltageIsReached(), here's a very simple way of doing it, which is OK if you don't have anything else to do in the mean time.
if (voltageIsReached()) {
    long end = millis() + 10000;   // 10s from now
    boolean voltageWasReachedFor10s = false;
    while (voltageIsReached()) {
        if (millis() >= end) {
            voltageWasReachedFor10s = true;
            break;
        }
        delay(1);
    }
    if (voltageWasReachedFor10s) {
        // Do whatever you have to do
    }
}

If you do have something else to do while you're waiting for this 10s state, you will need to adapt this, but I hope it'll get you started.

Write a function that has a static variable that keeps the previous time that the voltage has not been reached. That routine will read the voltage and reset the static variable to current time whenever the voltage has not been reached.
Such a routines can either return a logic value or a time value , depending on your implementation.


text:
Irregularly triggering an ISR using timers
I seek to call an ISR routine after a fixed time of 400us. This action needs to be done every now and then (in the range of 0.8-3.0ms). For that matter, I thought I'd set timer2 to CTC mode, use OCR2A to set some TOP value for 400us and let the timer call the ISR routine after 400us. Within the ISR I would then stop the timer from triggering interrupts, until I need to count to 400us again, where I would activate the timer interrupt again.
This works, as expected, except for the fact, that after activating the interrupt for OCR2A again, it instantly triggers. The code below, produces a 1ms alternating signal, instead of 1ms+400us.
My question is, am I on a good way with this, or should I use the overflow ISR and preload the timer? Or any other method? The problem is, that after the 1ms waiting time in the main loop, I'd expect the counter to count from 0 to 100, meaning 400us. However on an oscilloscope I see the pin toggle each 1ms.
uint32_t timestamp;

void setup() {
  Serial.begin(115200);
  pinMode(9, OUTPUT);
  cli();         // disable global interrupts
  // Timer2 for counting (to release the pin)
  TCCR2A |= (1 << WGM21); // CTC mode, clear timer on compare match
  TCCR2B |= (1 << CS22); // Prescalar 64

  OCR2A = 99; // ticks, before ISR is called
  TIMSK2 |= (1 << OCIE2A); // enable timer compare interrupt
  TCNT2 = 0x00; // set the timer to 0
  // counting time[s] = (OCR+1)/(F_cpu/prescalar)
  // 99 = 400us | 124 = 500us
  sei(); // enable global interrups
  timestamp = micros();
}

void loop() {
  uint32_t now = micros();
  if (now - timestamp > 1000) {
    timestamp = now;
    cli();
    TIMSK2 |= (1 << OCIE2A); // enable timer compare interrupt
    sei();
    TCNT2 = 0x00;
  }
}

ISR(TIMER2_COMPA_vect) {
  // Serial.print(F("Here\n"));
  PORTB ^= 2; // set pin 9 high again
  // TCNT2 = 0x00; // reset timer for testing
  // deactivate the counter
   cli();
   TIMSK2 = 0x00; // unlink the ISR from timer
   sei();
}

However on an oscilloscope I see the pin toggle each 1ms.

That's what you expect. You set up the timer to fire every 1 ms. Since the ISR is called some time after that (and that is what toggles the pin) you will see the pin toggle every 1 ms.
I've reworked your example a bit to make it clearer, and to toggle the pin when we start the timer, and again when the ISR fires:
uint32_t timestamp;

void setup()
  {
  pinMode(9, OUTPUT);
  // Timer2 for counting
  TCCR2A = bit (WGM21); // CTC mode, clear timer on compare match
  OCR2A = 99;           // ticks, before ISR is called

  // counting time[s] = (OCR+1)/(F_cpu/prescalar)
  // 99 = 400us | 124 = 500us
  timestamp = micros();
  }  // end of seupt

void loop()
{
  uint32_t now = micros();
  if (now - timestamp >= 1000)
    {
    timestamp = now;
    TIFR2 = bit (OCF2A);   // clear any pending interrupt
    TCNT2 = 0;             // make sure counter is zero
    TIMSK2 = bit (OCIE2A); // enable timer compare interrupt
    TCCR2B = bit (CS22);   // start timer: Prescalar 64
    PINB = bit (1);        // toggle pin 9
    }  // end of if
}  // end of loop

ISR(TIMER2_COMPA_vect)
{
  PINB = bit (1); // toggle pin 9
  TCCR2B = 0;     // stop timer
}  // end of TIMER2_COMPA_vect

You can see from the scope output that the timer is started every 1 ms (as expected) because Cursor 1 is at -1 ms. The width of the pulse is 400 µs, as expected.

In my example I do not have to set so many settings each time I want to start the timer.

I took out the cli and sei so I saved you two lines. Don't forget to count them!
If you leave the timer running, it may well have reached the counter again (even though not generating an interrupt). Thus this line is important (even more so for you):
TIFR2 = bit (OCF2A);   // clear any pending interrupt

Also, if you leave the timer running, you may have a race condition. Say the timer is just about to tick over and generate the interrupt. You clear the flag (as shown above), but one machine cycle later the timer reaches the counter and sets it again, just before you get a chance to zero it. With the timer running, there could be combinations of when you enable interrupts, zero the flag, and clear the pending interrupt flag, that could occasionally work against you. Having the timer stopped is much safer.
Now if you are worried about the number of lines you need to start it (I wouldn't be) then you can move this line into setup:
TIMSK2 = bit (OCIE2A); // enable timer compare interrupt

Since you stop the timer in the ISR it doesn't matter if the interrupt is still enabled. Now you just have three lines to start the timer:
TIFR2 = bit (OCF2A);  // clear any pending interrupt
TCNT2 = 0;            // make sure timer is zeroed
TCCR2B = bit (CS22);  // start timer: Prescalar 64

I think we've agreed that clearing the compare flag is important, so this isn't any lengthier.

looking at your divisioning of the time axis, and from code, it is clear, that there is a 600us break, not 1ms!

Yes, there's a 600 µs break, because you start the timer every 1 ms, and it runs for 400 µs, thus there will be a 600 µs break.

I seek to call an ISR routine after a fixed time of 400us.

That's exactly what my posted code does. The pin goes high at the time you desire, in loop, and it goes low 400 µs later. That's what you wanted: a 400 µs interval.

As far as I can tell, the only additional thing is TIFR2 = bit (OCF2A);. In your code, you stop the timer alltogether. Isn't it cleaner the way I did, where I just disconnect the timer from the interrupt? In my example I do not have to set so many settings each time I want to start the timer. Or is it even desirable to use the overflow timer instead,... would that result in less hastle when starting the timer?

btw.: looking at your divisioning of the time axis, and from code, it is clear, that there is a 600us break, not 1ms! Since both timers (timer0 running micros() and timer2) run parallel, it is clear, that the break is 1ms-400us = 600us.

See amended answer.

Thanks for the additional explanation. I was originally worried about the flag, that was set on compare match, but now I totally agree, that stopping the timer is what I was looking for!


text:
Splitting up code in multiple files causing `multiple definition` and `undefined reference` error
I have the following very basic program that reads MPU6050(accelerometer and gyroscope) sensor using the I2C library, and prints the sensor information. This program works as expected.
#include <Arduino.h>
#include <MPU6050_6Axis_MotionApps20.h>

inline void printToSerial(bool, bool) __attribute__((always_inline));

MPU6050 imu;
int16_t ax, ay, az, gx, gy, gz;

void setup() {
  imu.initialize();

  imu.setFullScaleGyroRange(MPU6050_GYRO_FS_250);
  imu.setFullScaleAccelRange(MPU6050_ACCEL_FS_2);

  imu.setXAccelOffset(-1451);
  imu.setYAccelOffset(-682);
  imu.setZAccelOffset(1448);
  imu.setXGyroOffset(69);
  imu.setYGyroOffset(-16);
  imu.setZGyroOffset(29);
  Serial.begin(9600);
}

void loop() {
  imu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
  printToSerial(false, true);
  delay(50);
}

void printToSerial(bool a, bool g){
  if(a){
    Serial.print(ax); Serial.print("\t");
    Serial.print(ay); Serial.print("\t");
    Serial.println(az);
  }

  if(g){
    Serial.print(gx); Serial.print("\t");
    Serial.print(gy); Serial.print("\t");
    Serial.println(gz);
  }
}

But as I want to add more functionality to the main program - I want to move MPU6050 specific code to separate file.
So, I created Sensor.h with the following content,
#ifndef SENSOR_H
#define SENSOR_H

#include <MPU6050_6Axis_MotionApps20.h>

extern MPU6050 imu;
extern int16_t ax, ay, az, gx, gy, gz;

void sensorInit();
void sensorUpdate();

#endif

And placed the implementation in the Sensor.cpp file.
# include "Sensor.h"

void sensorInit(){
  imu.initialize();

  imu.setFullScaleGyroRange(MPU6050_GYRO_FS_250);
  imu.setFullScaleAccelRange(MPU6050_ACCEL_FS_2);

  imu.setXAccelOffset(-1451);
  imu.setYAccelOffset(-682);
  imu.setZAccelOffset(1448);
  imu.setXGyroOffset(69);
  imu.setYGyroOffset(-16);
  imu.setZGyroOffset(29);
}

void sensorUpdate(){
    imu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
}

And finally, modified the main.cpp file in the following way,
#include "Sensor.h"
#include <Arduino.h>

inline void printToSerial(bool, bool) __attribute__((always_inline));

void setup() {
  sensorInit(); // replaced few lines of codes
  Serial.begin(9600);
}

void loop() {
  sensorUpdate(); // replaced few lines of codes
  printToSerial(false, true);
  delay(50);
}

void printToSerial(bool a, bool g){
  if(a){
    Serial.print(ax); Serial.print("\t");
    Serial.print(ay); Serial.print("\t");
    Serial.println(az);
  }

  if(g){
    Serial.print(gx); Serial.print("\t");
    Serial.print(gy); Serial.print("\t");
    Serial.println(gz);
  }
}

But when I try to build the code, I get the following error in the linking step,
.pio\build\uno\src\main.cpp.o (symbol from plugin): In function `MPU6050::dmpInitialize()':
(.text+0x0): multiple definition of `MPU6050::dmpInitialize()'
.pio\build\uno\src\Sensor.cpp.o (symbol from plugin):(.text+0x0): first defined here
.pio\build\uno\src\main.cpp.o (symbol from plugin): In function `MPU6050::dmpInitialize()':
(.text+0x0): multiple definition of `MPU6050::dmpPacketAvailable()'
.pio\build\uno\src\Sensor.cpp.o (symbol from plugin):(.text+0x0): first defined here
.pio\build\uno\src\main.cpp.o (symbol from plugin): In function `MPU6050::dmpInitialize()':
(.text+0x0): multiple definition of `MPU6050::dmpGetAccel(long*, unsigned char const*)'
.pio\build\uno\src\Sensor.cpp.o (symbol from plugin):(.text+0x0): first defined here
.pio\build\uno\src\main.cpp.o (symbol from plugin): In function `MPU6050::dmpInitialize()':
(.text+0x0): multiple definition of `MPU6050::dmpGetAccel(int*, unsigned char const*)'
.pio\build\uno\src\Sensor.cpp.o (symbol from plugin):(.text+0x0): first defined here
.pio\build\uno\src\main.cpp.o (symbol from plugin): In function `MPU6050::dmpInitialize()':
(.text+0x0): multiple definition of `MPU6050::dmpGetAccel(VectorInt16*, unsigned char const*)'
.pio\build\uno\src\Sensor.cpp.o (symbol from plugin):(.text+0x0): first defined here
.pio\build\uno\src\main.cpp.o (symbol from plugin): In function `MPU6050::dmpInitialize()':
(.text+0x0): multiple definition of `MPU6050::dmpGetQuaternion(long*, unsigned char const*)'
.pio\build\uno\src\Sensor.cpp.o (symbol from plugin):(.text+0x0): first defined here
.pio\build\uno\src\main.cpp.o (symbol from plugin): In function `MPU6050::dmpInitialize()':
(.text+0x0): multiple definition of `MPU6050::dmpGetQuaternion(int*, unsigned char const*)'
.pio\build\uno\src\Sensor.cpp.o (symbol from plugin):(.text+0x0): first defined here
.pio\build\uno\src\main.cpp.o (symbol from plugin): In function `MPU6050::dmpInitialize()':
(.text+0x0): multiple definition of `MPU6050::dmpGetQuaternion(Quaternion*, unsigned char const*)'
.pio\build\uno\src\Sensor.cpp.o (symbol from plugin):(.text+0x0): first defined here
.pio\build\uno\src\main.cpp.o (symbol from plugin): In function `MPU6050::dmpInitialize()':
(.text+0x0): multiple definition of `MPU6050::dmpGetGyro(long*, unsigned char const*)'
.pio\build\uno\src\Sensor.cpp.o (symbol from plugin):(.text+0x0): first defined here
.pio\build\uno\src\main.cpp.o (symbol from plugin): In function `MPU6050::dmpInitialize()':
(.text+0x0): multiple definition of `MPU6050::dmpGetGyro(int*, unsigned char const*)'
.pio\build\uno\src\Sensor.cpp.o (symbol from plugin):(.text+0x0): first defined here
.pio\build\uno\src\main.cpp.o (symbol from plugin): In function `MPU6050::dmpInitialize()':
(.text+0x0): multiple definition of `MPU6050::dmpGetGyro(VectorInt16*, unsigned char const*)'
.pio\build\uno\src\Sensor.cpp.o (symbol from plugin):(.text+0x0): first defined here
.pio\build\uno\src\main.cpp.o (symbol from plugin): In function `MPU6050::dmpInitialize()':
(.text+0x0): multiple definition of `MPU6050::dmpGetLinearAccel(VectorInt16*, VectorInt16*, VectorFloat*)'
.pio\build\uno\src\Sensor.cpp.o (symbol from plugin):(.text+0x0): first defined here
.pio\build\uno\src\main.cpp.o (symbol from plugin): In function `MPU6050::dmpInitialize()':
(.text+0x0): multiple definition of `MPU6050::dmpGetLinearAccelInWorld(VectorInt16*, VectorInt16*, Quaternion*)'
.pio\build\uno\src\Sensor.cpp.o (symbol from plugin):(.text+0x0): first defined here
.pio\build\uno\src\main.cpp.o (symbol from plugin): In function `MPU6050::dmpInitialize()':
(.text+0x0): multiple definition of `MPU6050::dmpGetGravity(int*, unsigned char const*)'
.pio\build\uno\src\Sensor.cpp.o (symbol from plugin):(.text+0x0): first defined here
.pio\build\uno\src\main.cpp.o (symbol from plugin): In function `MPU6050::dmpInitialize()':
(.text+0x0): multiple definition of `MPU6050::dmpGetGravity(VectorFloat*, Quaternion*)'
.pio\build\uno\src\Sensor.cpp.o (symbol from plugin):(.text+0x0): first defined here
.pio\build\uno\src\main.cpp.o (symbol from plugin): In function `MPU6050::dmpInitialize()':
(.text+0x0): multiple definition of `MPU6050::dmpGetEuler(float*, Quaternion*)'
.pio\build\uno\src\Sensor.cpp.o (symbol from plugin):(.text+0x0): first defined here
.pio\build\uno\src\main.cpp.o (symbol from plugin): In function `MPU6050::dmpInitialize()':
(.text+0x0): multiple definition of `MPU6050::dmpGetYawPitchRoll(float*, Quaternion*, VectorFloat*)'
.pio\build\uno\src\Sensor.cpp.o (symbol from plugin):(.text+0x0): first defined here
.pio\build\uno\src\main.cpp.o (symbol from plugin): In function `MPU6050::dmpInitialize()':
(.text+0x0): multiple definition of `MPU6050::dmpProcessFIFOPacket(unsigned char const*)'
.pio\build\uno\src\Sensor.cpp.o (symbol from plugin):(.text+0x0): first defined here
.pio\build\uno\src\main.cpp.o (symbol from plugin): In function `MPU6050::dmpInitialize()':
(.text+0x0): multiple definition of `MPU6050::dmpReadAndProcessFIFOPacket(unsigned char, unsigned char*)'
.pio\build\uno\src\Sensor.cpp.o (symbol from plugin):(.text+0x0): first defined here
.pio\build\uno\src\main.cpp.o (symbol from plugin): In function `MPU6050::dmpInitialize()':
(.text+0x0): multiple definition of `MPU6050::dmpGetFIFOPacketSize()'
.pio\build\uno\src\Sensor.cpp.o (symbol from plugin):(.text+0x0): first defined here
.pio\build\uno\src\main.cpp.o (symbol from plugin): In function `MPU6050::dmpInitialize()':
(.text+0x0): multiple definition of `MPU6050::dmpGetCurrentFIFOPacket(unsigned char*)'
.pio\build\uno\src\Sensor.cpp.o (symbol from plugin):(.text+0x0): first defined here
.pio\libdeps\uno\I2Cdevlib-MPU6050/MPU6050.h:436:7: warning: type 'struct MPU6050' violates one definition rule [-Wodr]
 class MPU6050 {
       ^
.pio\libdeps\uno\I2Cdevlib-MPU6050\MPU6050.h:436:7: note: a different type is defined in another translation unit
 class MPU6050 {
       ^
.pio\libdeps\uno\I2Cdevlib-MPU6050/MPU6050.h:1036:18: note: the first difference of corresponding definitions is field 'dmpPacketBuffer'
         uint8_t *dmpPacketBuffer;
                  ^
.pio\libdeps\uno\I2Cdevlib-MPU6050\MPU6050.h:436:7: note: a type with different number of fields is defined in another translation unit
 class MPU6050 {
       ^
C:\Users\iamcr\AppData\Local\Temp\cc1jV0kL.ltrans0.ltrans.o: In function `MPU6050::getDeviceID() [clone .constprop.29]':
<artificial>:(.text+0xbba): undefined reference to `imu'
<artificial>:(.text+0xbd0): undefined reference to `imu'
<artificial>:(.text+0xbd4): undefined reference to `imu'
C:\Users\iamcr\AppData\Local\Temp\cc1jV0kL.ltrans0.ltrans.o: In function `main':
<artificial>:(.text.startup+0x10c): undefined reference to `imu'
<artificial>:(.text.startup+0x11c): undefined reference to `imu'
C:\Users\iamcr\AppData\Local\Temp\cc1jV0kL.ltrans0.ltrans.o:<artificial>:(.text.startup+0x12a): more undefined references to `imu' follow
C:\Users\iamcr\AppData\Local\Temp\cc1jV0kL.ltrans0.ltrans.o: In function `main':
<artificial>:(.text.startup+0x282): undefined reference to `ax'
<artificial>:(.text.startup+0x286): undefined reference to `ax'
<artificial>:(.text.startup+0x28a): undefined reference to `imu'
<artificial>:(.text.startup+0x28e): undefined reference to `imu'
<artificial>:(.text.startup+0x298): undefined reference to `ay'
<artificial>:(.text.startup+0x29c): undefined reference to `ay'
<artificial>:(.text.startup+0x2a0): undefined reference to `imu'
<artificial>:(.text.startup+0x2a4): undefined reference to `imu'
<artificial>:(.text.startup+0x2ae): undefined reference to `az'
<artificial>:(.text.startup+0x2b2): undefined reference to `az'
<artificial>:(.text.startup+0x2b6): undefined reference to `imu'
<artificial>:(.text.startup+0x2ba): undefined reference to `imu'
<artificial>:(.text.startup+0x2c4): undefined reference to `gx'
<artificial>:(.text.startup+0x2c8): undefined reference to `gx'
<artificial>:(.text.startup+0x2cc): undefined reference to `imu'
<artificial>:(.text.startup+0x2d0): undefined reference to `imu'
<artificial>:(.text.startup+0x2da): undefined reference to `gy'
<artificial>:(.text.startup+0x2de): undefined reference to `gy'
<artificial>:(.text.startup+0x2e2): undefined reference to `imu'
<artificial>:(.text.startup+0x2e6): undefined reference to `imu'
<artificial>:(.text.startup+0x2f0): undefined reference to `gz'
<artificial>:(.text.startup+0x2f4): undefined reference to `gz'
<artificial>:(.text.startup+0x30c): undefined reference to `gy'
<artificial>:(.text.startup+0x310): undefined reference to `gy'
<artificial>:(.text.startup+0x328): undefined reference to `gz'
<artificial>:(.text.startup+0x32c): undefined reference to `gz'

Main.cpp, Sensor.cpp and Sensor.h files are in the same directory. I am using PlatformIO to build and deploy the code on an Arduino Uno and the platformio.ini file content is the following,
[env:uno]
platform = atmelavr
board = uno
framework = arduino
lib_deps = jrowberg/I2Cdevlib-MPU6050@0.0.0-alpha+sha.fbde122cc5

I am wondering what is causing the linking errors.

The failing is not with your code. The failing is with the MPU6050_6Axis_MotionApps20.h library. It erroneously has code in the header rather than in a separate CPP file.
You have done everything right. The author of that library could do well in taking a leaf out of your book.
To get it working you will have to move the code out of the header file into the .cpp file - or move it to reside inside the class definition and make it inline.

I would be nice if there were a feature that would tell me how many people were typing in answers, scrapping mine now.

@Majenko Thanks! I just added inline keyword before each offending method in the header file, and the resolved the multiple definition issue. I've also added MPU6050 imu; int16_t ax, ay, az, gx, gy, gz; to global space of main.cpp to resolve the undefined reference issue.