body:
A test with an Arduino Uno.

I used the usb connector to power-on the arduino uno. The led is at PB5, so I have exchanged PB0 and PB5. My test is therefor not the same.

    #define LED_PB  PB5   // pin 13, onboard led
    #define INP_PB  PB0   // pin 8, antenna

    void setup(void)
    {
      noInterrupts();
      PORTB |= 1 << INP_PB; /* pullup */
      DDRB |= 1 << LED_PB; /* LED */
      if (!(PINB & 1 << INP_PB))
        PORTB |= 1 << LED_PB; /* turn on LED */
      while (1) ;
    }

    void loop()
    {
    }

Using it next to my computer and phone, sometimes the led stays on. I can even find a spot behind my computer monitor (with CCFL backlight) where the led always turns on.

Then I went outside, away from metals, wifi, and so on. The air humidity outside is 70% at the moment, which is high. I put it on a wooden table, so there is no charge by plastic. I used a battery to power the arduino uno. Then the led **never** turns on.

In such a clean environment, the internal pullup resistor was probably strong enough to pull the pin high during that very short time.

@IgorLiferenko, @sa_leinad gave the right answer. What you noticed is normal. It is totally normal. That behaviour can be expected. It will be worse when your circuit is not well designed.
A oscilloscope will not help. As soon as you connect a oscilloscope, you have changed something. It will also be very hard to detect that very short time (less than a microsecond).

In my opinion the influence by radio waves is only half of the problem. I think the electrical charge of the air, and the capacitive coupling of the wire with the air might have a larger effect.


sender: user

message:
Where in datasheet is the warning about unreliability of reading PINxn?

I use atmega32u4 (but believe it applies to all models). Here is the [datasheet][1].

Consider the following C program (I use AVR-GCC 5.4.0):

    #include <avr/io.h>
    int main(void)
    {
      PORTB |= 1 << PB5; /* pullup */
      DDRB |= 1 << PB0; /* LED */
      if (!(PINB & 1 << PB5))
        PORTB |= 1 << PB0; /* turn on LED */
      while (1) ;
    }

There are two situations:

 - connect a 10cm wire to PB5 pin (the other end of the wire is in the air): the result is that sometimes after poweron the led is on, sometimes the led is not on.

 - do not connect anything to PB5 pin: the result is that after poweron led is never on.

I have a standard setup. Nothing tricky. If it does not work reliably, this gotcha **MUST** be documented in datasheet. This setup is supposed to deal with a stupid button. But sometimes it detects a keypress while there is no keypress.

The question is: where in datasheet there is a warning about this gotcha?
And did somebody come across such case, or I'm the first in the world?

**EDIT** See also [this][2] question.

  [1]: https://www.pjrc.com/teensy/atmega32u4.pdf
  [2]: https://electronics.stackexchange.com/q/388648/91037

sender: assistant

body:
> did somebody come across such case, or I'm the first in the world?

You are not the first. I recently got bitten by the very same issue.

However, unless you are close to an unusually strong radio source, I do
not think it has anything to do with electromagnetic interference. In my
experience, the internal pullup is perfectly reliable for reading
switches and push buttons, even on a breadboard with jumper wires acting
as antennas. If you use `pinMode()` and `digitalRead()` instead of
direct port access, you too will find the internal pullup is perfectly
fine.

Before I give you the answer (suspense...), let's look closely at what
your code does. The disassembly looks like this:

<!-- language: lang-lisp -->

    main:
        sbi  PORTB, PB5 ; turn on pullup on PB5
        sbi  DDRB,  PB0 ; set LED pin as output
        sbis PINB,  PB5 ; read PB5, if it is LOW then:
        sbi  PORTB, PB0 ;   turn on LED
    0:  rjmp 0b         ; hang in an infinite loop

In the situation when the LED turns on, every instruction there executes
in two CPU cycles, save for `sbis`, which takes a single cycle in this
case. Now, let's look at the timings, and specifically at the states of
the pullup and the input circuitry during each of the first seven CPU
cycles:

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

    cycle   instruction   pullup latch PINB5
    ----------------------------------------
       1   sbi PORTB, PB5   off    X     X
       2      cont.         off    X     X
       3   sbi DDRB,  PB0   on     X     X
       4      cont.         on    LOW    X
       5   sbis PINB, PB5   on     X    LOW
       6   sbi PORTB, PB0   on     X     X
       7      cont.         on     X     X

In the table above, “X” means “don't care”. Each instruction takes
effect at the beginning of the _next_ CPU cycle, when the clock's rising
edge commits the result of the instruction to the affected flip-flops.
That's why the pullup turns on only at the beginning of cycle 3.
Now, since the pin did read LOW, that means the PB5 flip-flop was LOW
while the CPU was reading it, during cycle 5. This in turn means
that the synchronizing latch before that flip-flop was LOW during
cycle 4.

Your expectation was for the pin to read HIGH. So let's see: how fast
should the pin voltage have risen in order for the pin to indeed read
HIGH? Since the input latch is transparent during the first half of each
cycle, this means that the voltage should raise past the Schmitt
trigger's threshold during cycle 3 and the first half cycle 4.
So the rise time should be less than 1.5 cycles. Or rather
1.5 cycles minus the combined propagation delay of the PORTB5
flip-flop and the logic that controls the pullup from that flip-flop's
output. Probably around 90 ns. That's short!

By now you have probably guessed: the culprit is not electromagnetic
interference, it's stray capacitance. A simple calculation will show you
that about _three picofarads_ is enough to produce the effect you are
seeing. This is the kind of stray capacitance you will find everywhere,
even between the PCB traces of your Arduino board. Note that
electromagnetic noise can add some unpredictability to what you see, as
the pin is susceptible to it when it's completely floating, i.e.
_before_ you turn on the pullup, which makes the initial voltage (at the
beginning of cycle 3) unpredictable. But once the pullup is on and
the pin has settled, you won't care about noise anymore, unless it's
unusually strong.

The solution to your problem is simply to wait for the pullup to charge
the stray capacitance. A microsecond delay should be enough to fix the
issue. Alternatively, use the Arduino functions instead of direct port
access: they are so slow that you will not need any extra delay.

> where in datasheet there is a warning about this gotcha?

In section 18.2.4 – Reading the Pin Value: “[The synchronizing latch] is
needed to avoid metastability if the physical pin changes value near the
edge of the internal clock, **but it also introduces a delay**.”
(emphasis mine).

**Edit**: In a previous version of this answer, I incorrectly stated
that `sbi` is a single cycle instruction, which required the voltage to
rise in half a cycle instead of 1.5 cycles. The corrected timing is
still short enough for stray capacitance to be a valid explanation of
the observed behavior.

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

**In summary**:

* The stray capacitance attached to the pin, together with the pullup
  resistor, for an RC circuit.
* As the pin is initially floating, it's initial voltage is
  unpredictable.
* When the pullup is turned on, the voltage starts to rise from whatever
  initial value it had to 5 V.
* After some time, which can be typically of the order of the RC time
  constant, the input Schmitt trigger turns HIGH.
* After some extra delay introduced by the synchronizer, the PINxn
  flip-flop turns HIGH.
* If the CPU reads the PINx register before that happens, it gets a LOW
  reading.


message:
Running two NEMA 17 motors, one by one, using the Arduino Uno

I am new to Arduino. I am trying to run two stepper motors [NEMA 17][1] through respective [A4988 driver][2] and controlling via Arduino Uno.

The thought is that first stepper motor will carry out a first horizontal scan and then as it reaches to its initial position, second stepper motor will move a single step in vertical direction. This is a kind of raster scan that I want to perform with both motors.

When I am running the code, only horizontal scan motor is running and vertical scan motor is not moving. I have checked my circuit, motors and drivers and everything is working fine. I think there is some mistake in my code. It is a basic level code and I would really appreciate the help for helping me out.

    int x, y; //stepper motor 'x' and stepper motor 'y'
    #define BAUD (9600)

    void setup()
    {
      Serial.begin(BAUD);
      pinMode(6,OUTPUT); // Enable for x
      pinMode(5,OUTPUT); // Step for x
      pinMode(4,OUTPUT); // Dir for x
      digitalWrite(6,LOW); // Set Enable low for x

      pinMode(9,OUTPUT); // Enable for y
      pinMode(8,OUTPUT); // Step for y
      pinMode(7,OUTPUT); // Dir for y
      digitalWrite(9,LOW); // Set Enable low for y
    }

    void loop()
    {

      digitalWrite(9,LOW); // Set Enable low for y

      for(y = 0; y < 20; y++)
      {
         digitalWrite(6,LOW); // Set Enable low for x
         digitalWrite(4,HIGH); // Set Dir high for x - Clockwise

         Serial.println("CLOCKWISE HORIZONTAL SCANNING IN PROGRESS");

         for(x = 0; x < 50; x++) // Loop 50 times
         {
          digitalWrite(5,HIGH); // Output high for x
          delay(10); // Wait
          digitalWrite(5,LOW); // Output low for x
          delay(100); // Wait
         }

        digitalWrite(6,LOW); // Set Enable low for x
        digitalWrite(4,LOW); // Set Dir low for x - Anticlockwise

        Serial.println("ANTICLOCKWISE HORIZONTAL SCANNING IN PROGRESS");

        for(x = 0; x < 50; x++) // Loop 50 times
        {
          digitalWrite(5,HIGH); // Output high
          delay(10); // Wait
          digitalWrite(5,LOW); // Output low
          delay(100); // Wait
        }

        Serial.println("ONE STEP CLIMB ON VERTCAL AXIS");

        digitalWrite(7,HIGH); // Set Dir high for y

        digitalWrite(8,HIGH); // Output high for y
        delay(100); // Wait
        digitalWrite(8,LOW); // Output low for y
        delay(100); // Wait
      }

      digitalWrite(9,LOW); // Set Enable low for y
      digitalWrite(7,LOW); // Set Dir low for y

      Serial.println("RESETTING ON VERTCAL AXIS");

      for(y = 0; y < 20; y++) // Loop 20 times
        {
          digitalWrite(8,HIGH); // Output high for y
          delay(10); // Wait
          digitalWrite(8,LOW); // Output low for y
          delay(100); // Wait
        }

    }

Do i need to look after the delay being provided??

  [1]: https://reprap.org/wiki/NEMA_17_Stepper_motor
  [2]: https://www.pololu.com/product/1182/

body:
A minor issue that probably won't affect your result is that

    Serial.println("ONE STEP CLIMB ON VERTCAL AXIS");
    --> digitalWrite(9,LOW);  // This line 'needs' adding
    digitalWrite(7,HIGH); // Set Dir high for y

I can't see anything in the code that will prevent the motors running, OK it will take ~13 seconds to start moving, but it should move.

So - without any hardware attached to the motor spindles - is it possible to switch the motors over to check for a wiring breakage issue?  With one motor working and one not it implies to me that either the motor is broken, the wiring is broken or the driver circuit is broken.  If the fault moves then its a motor/wiring fault if it stays the same then its a driver fault.


message:
Caluclate lux value from LDR

I am using an LDR (Iduino SE012) to measure light. It returns a 10-bit value of the incoming voltage and I don't know how to convert this into lux, lumen candela or any other light-intensity unit. I was googling for datasheets but nothing useful came up. So is there any way how I can extrapolate a light intensity from the voltage?

I mean one idea that I would have is to measure some things where I know the lux output, but since I don't have such things or a luxmeter I'm pretty stuck. It also returns 1024 pretty quick if you hold it into the sun (Altough the sun is very strong today and it has 36°C). Is there maybe a "minimal value" at wich it returns the full voltage? From that point I could calculate it for all the other values.

Here are some datasheets I found:

 - https://www.manualshelf.com/manual/iduino/se012/datasheet-english.html
 - https://wakamatsu.co.jp/waka/SE012.pdf

body:
You can't.

The LDR has a spectral sensitivity which is _very different_ from the
human eye's. The definition of the lux, or any photometric unit for
that matter, pretty much _requires_ that your sensor is filtered in such
a way as to have the human eye's spectral sensitivity.


message:
Can't upload code to an Arduino LilyPad using FTDI

I've tried to upload my code to an Arduino LilyPad (328) using an FTDI basic breakout, but i get this:

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

    avrdude: stk500_recv(): programmer is not responding

    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x29

I tried to install the latest FTDI drivers from the FTDI website, tried another PC, tried to install the CDM-2.08.28 driver (latest I think) and nothing.

If I change the PC port the USB Serial Port doesn't change (is always COM3).

body: Does the Loopback test work? Connect Lilypad's Reset to Gnd, connect D0 to D1, open the serial monitor, see if typed text is echoed back.  If, you have FTDI problems that you need to resolve.


message:
Getting 0 cm from ultrasonic sensor when nothing is in front

My Ultra sonic sensor (HC-SR04) is returning these types of values when it has nothing in front:

    Ping: 144cm
    Ping: 0cm
    Ping: 0cm
    Ping: 0cm
    Ping: 105cm
    Ping: 105cm
    Ping: 94cm
    Ping: 0cm
    Ping: 378cm
    Ping: 0cm
    Ping: 0cm
    Ping: 0cm
    Ping: 0cm
    Ping: 0cm
    Ping: 0cm
    Ping: 106cm
    Ping: 106cm
    Ping: 0cm
    Ping: 0cm
    Ping: 0cm
    Ping: 106cm
    Ping: 250cm
    Ping: 0cm
    Ping: 108cm
    Ping: 0cm
    Ping: 108cm
    Ping: 0cm

I am not able to understand why I am getting 0 cm. This value is critical in the program that I am using. Here is a test code which gives me these output:

    #include <NewPing.h>

    #define TRIGGER_PIN  A5
    #define ECHO_PIN     A4
    #define MAX_DISTANCE 200

    NewPing sonar(TRIGGER_PIN, ECHO_PIN);

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

    void loop() {
      delay(1000);
      Serial.print("Ping: ");
      Serial.print(sonar.ping_cm());
      Serial.println("cm");
    }

Because  of these 0s my robot is making turns which are not expected.

Any idea why this might happen ?

body:
The documentation for the NewPing library states:

> **Constructor**
>
>     NewPing sonar(trigger_pin, echo_pin [, max_cm_distance]);

and

> max_cm_distance is optional [default = 500cm].

Then:

> `sonar.ping_cm();` - Send a ping, returns the distance in centimeters or
> 0 (zero) if no ping echo within set distance limit

So it would seem that if there is nothing in front of your sensor closer than 500cm, this library returns 0cm. Probably not the best design, but at least it is disclosed.

Thus, you need to write your code such that a 0cm measurement is treated as no obstruction visible; more like an infinite cm measurement.


message:
Updating ATmega16u2

I have the UNO Mini Strong from www.diymore.cc.
I am having the issue of keyboard.h not being recognized.
I have been trying to find the firmware mentioned in https://www.arduino.cc/en/Hacking/DFUProgramming8U2 from here https://github.com/arduino/Arduino/tree/master/hardware/arduino/avr/firmwares/atmegaxxu2 but, page is gone!

Does anyone know where the firmware can be found and should this work on the board I am trying to use?

body:
I tried to make a little research and it looks that the hardware folder was cleared (see [here][1]).

The json file made me think that now this is shipped like libraries, so through a dedicated package which gets downloaded later.

Consequently I checked in the installation folder and... there it is!

In the folder `<arduino install dir>\hardware\arduino\avr\firmwares\atmegaxxu2` you will find a lot of hex files (e.g. `Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex`)

I checked on my portable installation of arduino 1.8.5, but it should be there also for installed versions

  [1]: https://github.com/arduino/Arduino/tree/master/hardware


message:
Turn off power to a moisture sensor except when reading values

I have an Arduino Uno and a moisture sensor (looks like a YL-69 clone) submerged in water. I need to read the sensor's (analog) value every 3 min or so. The problem is: the sensor is always powered by the Arduino (GND and VCC), i.e. the current passes through it at all times. Because of this, one of the sensor's electrodes (presumably containing copper) grows a cyan residue. I'd like to NOT supply any power to the sensor except for the brief moment when I need to read the value. How can I do this?

EDIT: I've just noticed a related question (link below). The user decided to intermittently power the sensor via a digital pin, rather than VCC. Is this reasonable?

https://arduino.stackexchange.com/questions/20492/does-a-moisture-sensor-need-warm-up-time?rq=1

body:
If your sensor draws less than 40mA to operate, then you can safely "power" it from an GPIO pin.

The related question also asks how long the sensor must be powered in order to get a stable reading. For a sensor such as this one, it appears to be a simple resistive voltage divider, with the moisture sensor itself providing one leg of the divider circuit. The active component appears to be a comparator to provide a digital HIGH/LOW output as an alternative to the analog output.

Most schematics show a capacitor between ground and the voltage divider output, presumably to reduce noise. You need to allow for this capacitor to charge up and become stable before you take a reading. The time for this depends somewhat on the value of that capacitor and the supply voltage you are using.

Safe to assume, however, that a wait time of 1 second is more than enough.


body:
Here are other anti-corrosion measures for moisture sensors I found:

A moisture sensor with gold-plated electrodes:
https://www.dfrobot.com/product-599.html#.UhflOL-N_H0

Replacing metal electrodes with graphite:
http://tuxgraphics.org/electronics/200908/eth-flower-watering.shtml

Capacitive (i.e. not resisitive) moisture sensor:
https://www.amazon.com/DFROBOT-Gravity-Capacitive-Corrosion-Resistant/dp/B01GHY0N4K/ref=cm_cr_arp_d_product_top?ie=UTF8

Non-corrosive high quality sensor ($$$):
https://www.vegetronix.com/Products/VH400/


body: I built a project very similar to this last winter to monitor moisture levels in the soil of plants that I was keeping over winter in my basement.  I used GPIO pins to power the sensors similar to what jose can u c described above and  performed testing to determine the minimum on time to get readings.  I found that 150ms was enough to get stable readings in soils varying from completely saturated and with standing water to very dry (plant leaves starting to show signs of drying out).


body: I use in my project the fully waterproof sensor SMT50 (see http://www.truebner.de/en/smt50). It is specified from 3.3V to 30V power supply with a current of around 3 mA, so that should be possible to supply it from a GPIO. Please not that the GPIO output voltage decreases with current (see AVR datasheet pin driver strength).


message:
How to produce multiple DC voltages for a single project

So the title pretty much says it all, but for an example, I have an arduino board, 5-12 V, an LED bank 18 V, and an ultrasonic mister 24 V.

I know some brute force methods to power them from one outlet, but I was wondering if there is a more elegant way to get the voltage for each device with only one transformer instead of three. The solutions I've come up with are less than elegant, and only moderately compact.

I was just wondering what solutions you guys have employed and hoped I could find something helpful.

body:
First you want to take a regulated 24V supply. To that you want to add a switch-mode ("Buck") regulator to drop you down to 5V.  You don't want to try using an LDO for this unless you are happy to have a heat sink the size of a small car. A good cheap choice is a "UBEC" that can take 24V in and give 5V out (I use [these](https://hobbyking.com/en_us/kingkong-5v-3a-ubec.html)).

That 5V can then be fed direct into the Arduino.

Depending on what the "LED bank" is you may get away with an 18V (or adjustable) LDO, or an adjustable buck regulator. Or a simple (though high wattage) resistor may be all that is needed. You will have to provide more detail on this to get more help.


message:
RX and TX pin in Arduino Uno

I have LED Cube Project, and I want to activate the LED with My Android apps (Bluetooth). The LED Cube used A0-A5 and D0-D13 Pins, and the Bluetooth need RX and TX (D0, D1).

Where I can put the RX and TX (for Bluetooth HC-05) while D0, D1, and all analog and digital pins are used by the LED?

body:
> You can't magic more pins out of thin air.

Yes you can!

You can have as many output (and even input) pins as you want. I managed to build 8x8x8 LED cube using ATTiny13 with just 6 output pins (using only 5 of them)

All it takes is a little extra coding and "shift registers". (For extending outputs use the one with "latch", but for LEDs normal one is enough)

[![CD4094 Top View][2]][2]

You can use three (for example [CD4094][1]) 8 bit shift registers. You connect three Arduino pins to "DATA" (a.k.a. SERIAL DATA INPUT) pin of each register. Then one Arduino pin to three "CLOCK" pins and one Arduino pin to three "OUTPUT ENABLE" pins.

Then in the code you send a sequence of bits into the registers simulating the clock signal and when that's over just set output enable to make the registers output a value on their 8 output pins each.

This way you use just 5 pins, and when you chain the registers together (last "Q8" pin of one register can go to "DATA" pin of second one) you can theoretically have as many outputs as you need at the cost of output update speed.

This way you can free most of your Arduino pins including TX and RX.

  [1]: http://www.midondesign.com/Documents/4094BC.PDF
  [2]: https://i.stack.imgur.com/nZ54p.png


message:
How to write a library that support both HW and SW Serial communication and allow user to chose which one to use?

I'm working on a library for Arduino/ESP8266/Teensy that use serial to send AT commands. I want to make it as customizable as possible, so I avoided to hardcode the serial and I ask for a reference in the startup method:

    void MyClass::init(HardwareSerial* hwSerialPtr)
    {
       _serialPtr = hwSerialPtr;
       ...
    }

On some devices, it will be useful to use `SoftwareSerial` instead of the HW one, due to only one serial is available and so keep it for debugging purposes or other features.

So my question is: how can I accept both types? I read both HW and SW serial have `Stream` as base-clase, but it does not have methods like `begin()` etc.

A possible solution I though is so have two pointers (one for HWSerial and one for SWSerial) then wrap some methods like `begin()`, `println()`, `...` in my class and, ond the base of which pointer has been set, use one or the other.

Something like this:

    class MyClass{
       public:
          void init(HardwareSerial* hwSerialPtr);
          void init(SoftwareSerial* swSerialPtr);

       private:
          HardwareSerial* _hwSerialPtr;
          SoftwareSerial* _swSerialPtr;

          void begin(long baud);
          void println(const String &s)
    };
then

    void MyClass::begin(long baud)
    {
       if( _hwSerialPtr != null ){ _hwSerialPtr->begin(baudrate); }
       else if( _swSerialPtr != null ){ _swSerialPtr->begin(baudrate); }
    }

    ...etc...

but this solution seems to me very tricky and not optimized.

Any better ideas?

body:
The trick here is to go "up a level".  Both `HardwareSerial` and `SoftwareSerial` inherit from the `Stream` class.  It is *that* class that provides the majority of the interface that you actually use.

So you can provide a constructor with a `Stream` object alone and use that:

    class Foo {
        private:
            Stream *_dev;

        public:
            foo(Stream *dev) : _dev(dev) {}
            foo(Stream &dev) : _dev(&dev) {}

            void begin() {
                _dev->println("I am ready");
            }
    };

    Foo myFoo(Serial1);
    SoftareSerial btSerial(11,12);
    Foo myOtherFoo(btSerial);

What the `Stream` class *doesn't* provide, though, is `.begin()` for setting the baud rate. It has to be left to the user to configure the port before using it.

    Serial1.begin(115200);
    myFoo.begin(); // --> "I am ready" on Serial 1

or:

    btSerial.begin(9600);
    myOtherFoo.begin(); // --> "I am ready" on Software serial pins 11/12.

This is known as *polymorphism*, where an object is seen as one of the parent classes in the inheritance chain and is one of the most powerful aspects of object-oriented programming.

Not having `begin` in your library is no big deal really. It increases the flexibility (a user can more easily select their baud rate), and it means you don't force them to include SoftwareSerial if they don't need it.

There are other things that inherit `Stream`, as well, such as a networking `Client`. So instantly you class can be used with network connections as well as just serial.

So stick to using `Stream`. It's the accepted way of doing things, and perfectly normal. For example, it's how my [ICSC library](https://github.com/MajenkoLibraries/ICSC/blob/master/src/ICSC.h) handles serial objects.  (I used to use the multiple pointer method, but it really really got messy when trying to support other platforms. I ended up with `HardwareSerial`, `SoftwareSerial`, `USBSerial`, `Client`... a real mess. So much simpler to just use `Stream`.)

----

BTW, before you ask, I have two constructors with very slight differences so that you can construct an object either by passing a Stream object by reference (as I do in the examples) or as a pointer (which can be great if you want to use this in another class which itself has a pointer to a Stream object).

----

Another option is to combine the Stream pointer with a `dynamic_cast` to try and identify the type of object being passed.

    void Foo::begin(int baud) {
        if (HardwareSerial *hs = dynamic_cast<HardwareSerial *>(_dev)) {
            hs->begin(baud);
        } else if (SoftwareSerial *ss = dynamic_cast<SoftwareSerial *>(_dev)) {
            ss->begin(baud);
        } else {
            // We don't know what to do here
            // so do nothing?
        }
    }

In this way `dynamic_cast` is being used like Java's `instanceof` operator to work out what kind of object it is that is being used.

Of course, that then means that you're really restricting the library to only working with those two types of object, but it is still possible to pass other class types as long as the user pre-configures them before calling your begin function. Which gets confusing - which type does the user need to `.begin()` and which types have `.begin()` called for you? It's just cleaner to always have it as the user must call `.begin()` themselves - there's no ambiguity then.


body:
I second Majenko's advice: inherit from `Stream` and let the user handle
the call to `begin()` if at all possible. However, if you really insist
in calling `begin()` from your class, then I suggest you make your class
a template, like this:

    // T is the type of the serial port, typically HardwareSerial or
    // SoftwareSerial.
    template<class T> class MyClass {
        public:
            MyClass(T& port) : port(port) {}
            void begin(unsigned long baud) { port.begin(baud); }
        private:
            T& port;
    };

Your user would then instantiate it as

    MyClass<HardwareSerial> myObject(Serial);
    MyClass<SoftwareSerial> myOtherObject(mySerial);

Of course, it doesn't look nice, and it may confuse your users, but it
has the advantage that it can work with anything that remotely looks
like `HardwareSerial`, e.g. `AltSoftSerial` or other alternative
software serial implementations.


message:
Arduino Mega upload issue

I have made my own version of an Arduino Mega and I am encountering some issues. Whenever I try to upload any sketch to the Mega, I get the following error message:

avrdude: stk500v2 ReceiveMessage(): timeout

I can upload just fine to the 16u2 as well as the 2560 using ICSP and Nick Gammons Atmega_Board_Programmer sketch. I have the correct board and COM port selected, and the cable, computer, and USB(2.0) port can upload to other Arduino boards just fine.

I have had some other troubles with the board that have been solved, but this issue remains. Please see [my Arduino forum post](http://forum.arduino.cc/index.php?topic=560968.0) for more details on these issues.

My current guess is that there may some sort of issue with the transmission lines between the 16u2 and the 2560. [Here is a picture of the pcb traces](https://i.stack.imgur.com/rDvvi.jpg). Can anyone look them over to see if there are issues with the traces?

If the traces seem fine, can anyone think of another reason why the upload does not work?

body:
So as of right now the problem has been solved. The issue was that the decoupling capacitor on the reset line near the 2560 was designed to be a 22pF capacitor, but I had put a 100nF capacitor, which increases the time constant by a factor of 5000, prohibiting the auto-reset circuitry from operating correctly. Removing the 100nF and putting in the 22pF seems to have solved the issue of only being able to upload once after burning the bootloader.

Thank you everyone for your support.


message:
Cannot use radio transmitter after switching to LowPower library

My Arduino Mini board has DHT22 temperature sensor and 433MHz radio transmitter modules. I'm using `DHT` and `RCswitch` libraries to make use of them. Code looks like this:

    void setup() {
      tempSwitch.enableTransmit(RADIO_PIN);
      dht.begin();
    }

    void loop() {
      float temp = dht.readTemperature();

      unsigned long message = createTemperatureMessage(SENSOR_ID, temp);
      tempSwitch.send(message, 32);

    #ifdef MY_DEBUG
      unsigned int sleepCount = 1;
    #else
      // 3600s / 2 / 8s == 225
      unsigned int sleepCount = 225;
    #endif
      for (; sleepCount > 0; sleepCount--) {
        LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
      }
    }

So I'm reading temperature and sending it using `RCswitch` library. Initially I just had `delay(1000);` instead of fancy `LowPower` sleep loop but I wanted to make my "device" more battery-friendly so I switched to low-power sleep.

The problem is that now Arduino is only sending data first time and after sleeping 30 minutes (in "release" mode) it does not send anything anymore. If I reduce 30 minutes to 8 seconds it is capable of sending data as well as if I replace sleep with `delay(30*60*1000);`.

From beyond it looks like something is not caching up after the sleep. Do I need to "wake" radio module in any special way? How to fix that?

body:
I've never tried this, but if you are putting the Arduino to sleep I would expect it to cut power to the devices (does it?) if it does then after a 30 minute sleep I would expect the devices to come back up in the initial state.  Guessing by your code the initial state of the radio is Tx Disabled, so try moving the

    tempSwitch.enableTransmit(RADIO_PIN);

to before the

    float temp = dht.readTemperature();

line.

I'd also be concerned that the DHT22 is not in the correct state after you wake up.

Can you try doing a 1 second LowPower sleep in debug mode, I suspect it would work more often.


message:
Hex/Byte Reversing and Conversion

I'm working on an RFID system using a MFRC522 with this Library : https://github.com/miguelbalboa/rfid
Here's the code I have right now:

    int A=(mfrc522.uid.uidByte[0]);
    int B=(mfrc522.uid.uidByte[1]);
    int C=(mfrc522.uid.uidByte[2]);
    int D=(mfrc522.uid.uidByte[3]);

    Serial.println("UID is %x %x %x %x", A, B, C, D);

This results in the following output:

    UID is 35 C5 5A 59

My issue is - how do I first reverse that UID : from `35 C5 5A 59 to 59 5A C5 35`
- and second convert and print the corresponding decimal value of that reversed UID. In this case, it would be 1499120949.

I should mention that I need it as a string at the end to add it to the end of a POST command.

body:
Your UID has 4 bytes, which correspond to 32 bits. To get a decimal value from these bytes, you have to put them together in one variable. For this you can use an `unsigned long`. To put the bytes together, you can shift the values to the byte boundaries:

    unsigned long dec_value = (D << 24) | (C << 16) | (B << 8) | A;

`<<` shifts the bits of the byte by the specified amount of bits to the left; The bitwise OR `|` puts the now not overlapping bytes together in one value. I have reversed the order of the bytes in this code, as you wrote, that this is necessary.

To convert this `unsigned long` to a string you can use the function `ltoa()`:

    char buf[50];
    ltoa(dec_value, buf, 10);  // 10 is the base value not the size - look up ltoa for avr

If you want to use a `String` object (which should be avoided because of heap fragmentation), you can contruct the `String` directly from the `long` value:

    String my_UID = String(dec_value);


body:
A standard way to convert individual bytes to a number is to use bit
shifts and bitwise OR, as shown in chrisl's answer. When doing this,
however, one has to take care not to overflow the bit shifts. On the
AVR-based Arduinos, an `int` is 16 bits long. Shifting it by
24 bit positions to the left is guaranteed to overflow, which in
C++ leads to undefined behavior.

The solution, as explained in Majenko's comment, is to cast to the final
type _before_ shifting, like this:

    uint32_t uid = (uint32_t) mfrc522.uid.uidByte[0] << 0
                 | (uint32_t) mfrc522.uid.uidByte[1] << 8
                 | (uint32_t) mfrc522.uid.uidByte[2] << 16
                 | (uint32_t) mfrc522.uid.uidByte[3] << 24;

Note that I got rid of the useless intermediate variables `A` through
`D`.

Once you have have the numerical value, you may try to use it without
explicitly converting to a string. Instead, you rely on the `print()`
or `println()` methods to implicitly do the conversion only when needed,
as in

    Serial.print("UID = ");
    Serial.println(uid);

or even, on a network connection:

    client.print(uid);

This will save you the memory needed to store the string. If you really
need to have the converted string in memory, which could happen if you
need to provide a Content-Length before sending the data, you can do so
with the function `ultoa()` from the avr-libc:

    char uid_str[11];  // max = 10 digits + terminating NUL
    ultoa(uid, uid_str, 10);  // convert to base 10

Please note that `ltoa()` is **not** appropriate here, as calling it
will implicitly convert the value to a **signed** `long`, which has the
potential to overflow and yield a negative result.

This “C string” – a NUL-terminated character array – can then
be converted to a String object if needed, but I advice you against doing so
if at all possible. String objects are more convenient to manipulate,
but they are absolutely not memory friendly, which can quickly become an
issue on most Arduinos.


body:
To add a bit to the whole hex and decimal story:
Those are just representations of numerical values your computer/microprocessor does not really care about.

    int x = 0
    int y = 0b0
    int z = 0x0
these are all the same value and internally stored as binary, just like any other number.

You **specifically told** the println function to *display* said number(s) in hexadecimal representation with the format specifier `%x`
`Serial.println("UID is %x %x %x %x", A, B, C, D);`
using `%d` or `%i`(for integer) will print out decimal values for each number.

Converting byte array to larger data type
-----------------------------------------

If you actually want them to be reversed, you could simply cast the array variable (which is nothing but a pointer) to an uint32_t pointer:

    uint32_t dec_value = *(uint32_t*)mfrc522.uid.uidByte

Note the `*`s
We first cast the pointer to a pointer of a different type `(uint32_t*)`
and then access it's value, by prepending another `*`, which is then stored in `dec_value`, equaling 1499120949 now.

This works because in C/++ data structures in memory are guarenteed to be in the order you specified.
 Therefore, you essentially tell the computer to 'see' these very 4byte (32bit) as a single value rather than a independent bytes.

Usually, when converting byte arrays to larger data types, you will find the values you receive are not what you would expect. This is because they are stored in a different order (depending on the machine) known as [endianness][1]

Here is a function that addresses this issue (similiar to the other answers)

    uint32_t bytearray_to_uint32(unsigned char *buffer)
    {
        uint32_t value = 0;

        value |= (uint32_t)buffer[0] << 24;    // cast to target type before
        value |= (uint32_t)buffer[1] << 16;    // shifting to avoid overflow
        value |= (uint32_t)buffer[2] << 8;     // no parentheses needed due to operator precedence
        value |= buffer[3];

        return value;
    }
Applying this function to your case would result in `902126169 (0x35c55a59)` instead of the desired `1499120949 (0x595ac535)`.

Also check out [ntohl][2] when dealing with endianness still puzzles you.

  [1]: https://en.wikipedia.org/wiki/Endianness
  [2]: https://msdn.microsoft.com/de-de/library/windows/desktop/ms740069(v=vs.85).aspx


body:
I think this does what you need.  You already have the data in an array so to reverse it you go backwards through the list and assemble the number.  To fit 4 bytes into 32bits you need to multiply each byte by (256 * its position), which is what the left shift `<<` does.  So by placing the code in a small loop you get some compact code that should do the job.

    int A=(mfrc522.uid.uidByte[0]);
    int B=(mfrc522.uid.uidByte[1]);
    int C=(mfrc522.uid.uidByte[2]);
    int D=(mfrc522.uid.uidByte[3]);

    Serial.println("UID is %x %x %x %x", A, B, C, D);
    // ^ Your code
    uint32_t reversed = 0;
    for (int x = 3; x > -1; --x) // go backwards through the array
    {  // Take the existing value and multiple by 256 (left shift by 8) then add the latest byte on.
       reversed = (reversed << 8) + mfrc522.uid.uidByte[x];
    }
    String decValue = String (reversed);  // Covert the number to a string


message:
Why do COM port numbers between Arduino and Processing not match?

I have a Processing program that reads data sent to the serial port by an Arduino. When I go to device manager it shows that the Arduino is plugged into COM 4, however in order to get Processing to read the data the number I need for the COM in the following line is 2:

    String portName = Serial.list()[2]

Why do the numbers not match?

Thanks!

body: If you print out portName it should be __COM4__ it seems you must have 3 COM ports on your machine otherwise you would use index 0; Serial.List() appears to return an array or list which you are taking the third item located at index 2.


message:
Posting TinyGPS++ co-ordinates as paramaters with GPRS

I'm able to view my co-ords on the Serial Monitor using `Serial.println(gps.location.lat(), 6);`

I believe the data type returned by `gps.location.lat()` is double. I need to pass this value to a webservice with AT commands over GPRS.

`double latitude = gps.location.lat()`

Later in my code I execute AT commands to begin HTTP POST. I would like to know how to pass these double values in my paramaters.

`gsm.println("AT+HTTPPARA=\"URL\",\"http://webservice/service1\"");
 gsm.println("AT+HTTPDATA=192,10000");
 gsm.println("latitude=" + latitude);` < This is not allowed.

How can I pass this parameter to my web service.

body:
One solution may be to split the commands:

    gsm.print("latitude=");
    gsm.println(latitude);

I'm not sure how you should pass multiple parameters; if it is the usual syntax you can write something like

    gsm.print("latitude=");
    gsm.print(latitude);
    gsm.print("&longitude=");
    gsm.println("longitude);

If I have the time I'll research into this a bit.

To check what is the problem, you may try to send "static" messages, like

    gsm.println("latitude=12.345");

To check if this format is the correct one

EDIT: after a very quick research

It looks like the AT commands are a bit more complicated. In order to send the parameters, at least on a SIM800L, you should:

 - send the HTTPDATA command (the first parameter is the length of the payload)
 - wait for the board to send you the command DOWNLOAD
 - Send the body of the request, which is formatted as a JSON object. This means you have to send something like `{ "latitude" : 12.345, "longitude": 98.765 }`

After all, it is much faster to use a library already developed for this, for instance [ArduinoSIM800L][1] (check a library available for your GPRS modem, or modify this one)

  [1]: https://github.com/carrascoacd/ArduinoSIM800L


message:
Connecting Arduino and Processing, how do I know what COM to read?

I'm using Processing to read data from the serial port that the Arduino sends. When I go to device manager it shows that the Arduino is in COM 4, but in order for Processing to read from the Arduino the COM I need to type in is 2:

    String portName = Serial.list()[2]

Why do the numbers not match?

Thanks!

body:
Because the two numbers are completely different types of numbers.

The number 4 for COM4 means that it is the fourth serial communications port as defined by which I/O ports are used to communicate with the actual hardware. I.e. you'll have COM1, COM2, COM3 and so on. It doesn't matter if the hardware is actually there or anything is connected - the names are the same.

The number 2 in Serial.list()[2] means that you're selecting the third (!) element of the array returned by Serial.list(). I.e. in this case we're counting from 0 instead of 1.

In addition to that, Serial.list() only returns available ports. I.e. if the hardware for COM3 is not installed physically, it will not be returned by Serial.list(). Also the list is not guaranteed to be sorted in any specific order.

You'll want to print out the contents of the array returned by Serial.list() and let the user select which of the ports he wants to use.


message:
MemoryFree library showing Irregular Behaviour..!

I simply burned the code written below but it is showing me irregular behaviour.. as in output's last paragraph, free memory increases after a runtime allocation, how it is possible? The output is attached :

    #include <MemoryFree.h>
    String str="rajat";
    int flag=0;
    void setup()
    {
      // put your setup code here, to run once:

      Serial.begin(9600); Serial.println(freeMemory(), DEC);  // print how much RAM is available.
      Serial.println("Lets Start");
    }

    void loop()
    {
        Serial.println("");
        Serial.println("Rajat0");
        Serial.println(freeMemory(), DEC);
        Serial.println("Rajat1");
        str=str+"rjt";
        Serial.println(str);
        Serial.println("Rajat2");
        Serial.println(freeMemory(), DEC);
        Serial.println("Rajat3");
        Serial.println("");
          delay(1000);
    }
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/PYjqp.png

body:
Free memory can be found in two forms:

* The free space between the heap and the stack. This is usually the
  main chunk of free memory.
* Heap “holes”, i.e. pieces of unallocated memory within the heap. The
  presence of these holes is called “heap fragmentation”.

There are various versions of the MemoryFree library. The simplest ones
only report the main chunk between the heap and the stack. The more
sophisticated ones walk the malloc()'s free list in order to also count
the heap holes. Which approach is better? I would argue that the naive
version is fine, as heap holes is something you should not count on,
because it is never guaranteed that a particular allocation will fit in
any of those holes.

You are visibly using one of the naive versions. As you grow your
string, the object calls `realloc()`, which in some cases copies the
string's character array and frees the original one, potentially
creating a heap hole. Eventually, [small holes can coalesce into a
larger one][coalesce] big enough for the next allocation, and
`realloc()` can end up using this large hole and freeing the chunk at
the top of the heap. When this happens, the heap shrinks, and the main
chunk of free memory gets larger, which is what `freeMemory()` is
reporting to you.

In summary, it's normal and expected behavior. If you want something
less surprising, use a version of the library that does count the holes.
But then you may run into a more displeasing surprise: a heap–stack
collision, or an out-of-memory condition, can happen even with loads of
memory buried inside heap holes.

[coalesce]: http://svn.savannah.gnu.org/viewvc/avr-libc/trunk/avr-libc/libc/stdlib/malloc.c?revision=2149&view=markup#l217


message:
freeMemory() function from memoryfree library not returning decreased value in arduino UNO

I burned the code written below, I expect that as we declare the local variable in the loop, freeMemory() function should return decreased value. But it remains constant..! please explain why..?  The output is attached :

    #include <MemoryFree.h>
    void setup()
    {
      // put your setup code here, to run once:

      Serial.begin(9600); Serial.println(freeMemory(), DEC);  // print how much RAM is available.
      Serial.println("Lets Start");
    }
    void jack();
    void loop()
    {
        char c=0;
        c++;
        Serial.println("");
        Serial.println("Rajat0");
        Serial.println(freeMemory(), DEC);
        Serial.println("Rajat1");
        int x=0;
        x++;
        Serial.println("Rajat2");
        Serial.println(freeMemory(), DEC);
        Serial.println("Rajat3");
        jack();
        Serial.println("");
        delay(1000);
    }
    void jack()
    {
        Serial.println("jack0");
        int x=0;
        x++;
        Serial.println(freeMemory(), DEC);
        Serial.println("jack1");
    }
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/z4wby.png

body:
You are assuming that, just because you created a variable, it will be stored in memory. That is often not the case.

The compiler is reasonably intelligent. And there are lots of CPU registers in the AVR core. If there is a free register available for a temporary local variable like that, why would it waste time and effort putting it into memory when it can just keep it in a register?

Also, since you don't really *do* anything with the variable, chances are the compiler is just throwing it away.

Marking a variable `volatile` will remove both those problems, and you may see different results.


body:
Function 'jack' also does not show any difference in allocation. Since `jack()` is called only within this one module (known, because the program only consist of one module), and only once, the compiler can replace the function-call with the actual code of the function, saving both the space and time of a call and return.

That optimization is called "inlining" (usually only useful for instructional purposes but learning appears to be the whole point of your sketch). You can suppress the inlining by prefixing both the function and its declaration with `__attribute__ ((noinline))`. (Note that this attribute is specific to the gcc compilers; other compilers may provide a different way to do it, or none at all):

    __attribute__ ((noinline)) void jack();

    ...

    __attribute__ ((noinline)) void jack(){
       ... etc ...
    }


message:
Include in different file make different compiling error

I'm have problem compiling a code.

ardutest.ino:
<!-- language-all: lang-cpp -->

    #include "mylib.h"
    #include <SD.h>

    void setup() {

    }

    void loop() {
      fn();
    }

mylib.h:

    #ifndef mylib_h
    #define mylib_h

    #include "Arduino.h"

    void fn(File &_file);

    #endif

mylib.c:

    #include "mylib.h"

    void fn(File &_file)
    {
      _file = SD.open("LOG.TXT", FILE_WRITE);
      _file.println(42);
      _file.close();
    }

When checking code in Arduino IDE I have this error:

    In file included from sketch/mylib.c:1:0:
    mylib.h:7: error: expected ')' before '&' token
     void fn(File &_file);
              ^
    mylib.c:3: error: expected ')' before '&' token
     void fn(File &_file)
              ^
    Multiple libraries were found for "SD.h"
     Used: /home/mario/Arduino/libraries/SD
     Not used: /home/mario/Programs/arduino/libraries/SD
    exit status 1
    expected ')' before '&' token

But if I put SD.h in mylib.h (other files are the same):

    #ifndef mylib_h
    #define mylib_h

    #include "Arduino.h"
    #include <SD.h>

    void fn(File &_file);

    #endif

I have this error:

    In file included from /home/user/Arduino/libraries/SD/src/utility/Sd2Card.h:26:0,
                     from /home/user/Arduino/libraries/SD/src/utility/SdFat.h:29,
                     from /home/user/Arduino/libraries/SD/src/SD.h:20,
                     from sketch/mylib.h:5,
                     from sketch/mylib.c:1:
    /home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:423:14: error: unknown type name 'pin_map_t'
     static const pin_map_t digitalPinMap[] = {

                  ^
    /home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:447:69: error: 'pin_map_t' undeclared here (not in a function)
     static const uint8_t digitalPinCount = sizeof(digitalPinMap)/sizeof(pin_map_t);

                                                                         ^
    /home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h: In function 'getPinMode':
    /home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:455:32: error: request for member 'ddr' in something not a structure or union
         return (*digitalPinMap[pin].ddr >> digitalPinMap[pin].bit) & 1;

                                    ^
    /home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:455:58: error: request for member 'bit' in something not a structure or union
         return (*digitalPinMap[pin].ddr >> digitalPinMap[pin].bit) & 1;

                                                              ^
    /home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h: In function 'setPinMode':
    /home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:464:26: error: request for member 'ddr' in something not a structure or union
           *digitalPinMap[pin].ddr |= 1 << digitalPinMap[pin].bit;

                              ^
    /home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:464:57: error: request for member 'bit' in something not a structure or union
           *digitalPinMap[pin].ddr |= 1 << digitalPinMap[pin].bit;

                                                             ^
    /home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:466:26: error: request for member 'ddr' in something not a structure or union
           *digitalPinMap[pin].ddr &= ~(1 << digitalPinMap[pin].bit);

                              ^
    /home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:466:59: error: request for member 'bit' in something not a structure or union
           *digitalPinMap[pin].ddr &= ~(1 << digitalPinMap[pin].bit);

                                                               ^
    /home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h: In function 'fastDigitalRead':
    /home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:475:32: error: request for member 'pin' in something not a structure or union
         return (*digitalPinMap[pin].pin >> digitalPinMap[pin].bit) & 1;

                                    ^
    /home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:475:58: error: request for member 'bit' in something not a structure or union
         return (*digitalPinMap[pin].pin >> digitalPinMap[pin].bit) & 1;

                                                              ^
    /home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h: In function 'fastDigitalWrite':
    /home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:484:26: error: request for member 'port' in something not a structure or union
           *digitalPinMap[pin].port |= 1 << digitalPinMap[pin].bit;

                              ^
    /home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:484:58: error: request for member 'bit' in something not a structure or union
           *digitalPinMap[pin].port |= 1 << digitalPinMap[pin].bit;

                                                              ^
    /home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:486:26: error: request for member 'port' in something not a structure or union
           *digitalPinMap[pin].port &= ~(1 << digitalPinMap[pin].bit);

                              ^
    /home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:486:60: error: request for member 'bit' in something not a structure or union
           *digitalPinMap[pin].port &= ~(1 << digitalPinMap[pin].bit);

                                                                ^
    In file included from /home/user/Arduino/libraries/SD/src/utility/SdFat.h:29:0,
                     from /home/user/Arduino/libraries/SD/src/SD.h:20,
                     from sketch/mylib.h:5,
    Multiple libraries were found for "SD.h"
     Used: /home/user/Arduino/libraries/SD
     Not used: /home/user/Programs/arduino/libraries/SD
                     from sketch/mylib.c:1:
    /home/user/Arduino/libraries/SD/src/utility/Sd2Card.h: At top level:
    /home/user/Arduino/libraries/SD/src/utility/Sd2Card.h:70:1: error: initializer element is not constant
     uint8_t const  SD_CHIP_SELECT_PIN = SS;

     ^
    /home/user/Arduino/libraries/SD/src/utility/Sd2Card.h:79:1: error: initializer element is not constant
     uint8_t const  SPI_MOSI_PIN = MOSI;

     ^
    /home/user/Arduino/libraries/SD/src/utility/Sd2Card.h:81:1: error: initializer element is not constant
     uint8_t const  SPI_MISO_PIN = MISO;

     ^
    /home/user/Arduino/libraries/SD/src/utility/Sd2Card.h:83:1: error: initializer element is not constant
     uint8_t const  SPI_SCK_PIN = SCK;

     ^
    /home/user/Arduino/libraries/SD/src/utility/Sd2Card.h:176:1: error: unknown type name 'class'
     class Sd2Card {

     ^
    /home/user/Arduino/libraries/SD/src/utility/Sd2Card.h:176:15: error: expected '=', ',', ';', 'asm' or '__attribute__' before '{' token
     class Sd2Card {

                   ^
    In file included from /home/user/Arduino/libraries/SD/src/utility/SdFat.h:30:0,
                     from /home/user/Arduino/libraries/SD/src/SD.h:20,
                     from sketch/mylib.h:5,
                     from sketch/mylib.c:1:
    /home/user/Arduino/libraries/SD/src/utility/FatStructs.h:405:1: error: initializer element is not constant
     uint8_t const DIR_ATT_FILE_TYPE_MASK = (DIR_ATT_VOLUME_ID | DIR_ATT_DIRECTORY);

     ^
    In file included from /home/user/.arduino15/packages/arduino/hardware/avr/1.6.21/cores/arduino/Print.h:27:0,
                     from /home/user/Arduino/libraries/SD/src/utility/SdFat.h:31,
                     from /home/user/Arduino/libraries/SD/src/SD.h:20,
                     from sketch/mylib.h:5,
                     from sketch/mylib.c:1:
    /home/user/.arduino15/packages/arduino/hardware/avr/1.6.21/cores/arduino/Printable.h:25:1: error: unknown type name 'class'
     class Print;
     ^
    /home/user/.arduino15/packages/arduino/hardware/avr/1.6.21/cores/arduino/Printable.h:33:1: error: unknown type name 'class'
     class Printable
     ^
    /home/user/.arduino15/packages/arduino/hardware/avr/1.6.21/cores/arduino/Printable.h:34:1: error: expected '=', ',', ';', 'asm' or '__attribute__' before '{' token
     {
     ^
    In file included from /home/user/Arduino/libraries/SD/src/utility/SdFat.h:31:0,
                     from /home/user/Arduino/libraries/SD/src/SD.h:20,
                     from sketch/mylib.h:5,
                     from sketch/mylib.c:1:
    /home/user/.arduino15/packages/arduino/hardware/avr/1.6.21/cores/arduino/Print.h:37:1: error: unknown type name 'class'
     class Print
     ^
    /home/user/.arduino15/packages/arduino/hardware/avr/1.6.21/cores/arduino/Print.h:38:1: error: expected '=', ',', ';', 'asm' or '__attribute__' before '{' token
     {
     ^
    In file included from /home/user/Arduino/libraries/SD/src/SD.h:20:0,
                     from sketch/mylib.h:5,
                     from sketch/mylib.c:1:
    /home/user/Arduino/libraries/SD/src/utility/SdFat.h:39:1: error: unknown type name 'class'
     class SdVolume;

     ^
    /home/user/Arduino/libraries/SD/src/utility/SdFat.h:55:1: error: initializer element is not constant
     uint8_t const O_RDONLY = O_READ;

     ^
    /home/user/Arduino/libraries/SD/src/utility/SdFat.h:59:1: error: initializer element is not constant
     uint8_t const O_WRONLY = O_WRITE;

     ^
    /home/user/Arduino/libraries/SD/src/utility/SdFat.h:61:1: error: initializer element is not constant
     uint8_t const O_RDWR = (O_READ | O_WRITE);

     ^
    /home/user/Arduino/libraries/SD/src/utility/SdFat.h:63:1: error: initializer element is not constant
     uint8_t const O_ACCMODE = (O_READ | O_WRITE);

     ^
    /home/user/Arduino/libraries/SD/src/utility/SdFat.h:94:1: error: initializer element is not constant
     uint8_t const FAT_FILE_TYPE_MIN_DIR = FAT_FILE_TYPE_ROOT16;

     ^
    /home/user/Arduino/libraries/SD/src/utility/SdFat.h:137:1: error: unknown type name 'class'
     class SdFile : public Print {

     ^
    /home/user/Arduino/libraries/SD/src/utility/SdFat.h:137:14: error: expected '=', ',', ';', 'asm' or '__attribute__' before ':' token
     class SdFile : public Print {

                  ^
    /home/user/Arduino/libraries/SD/src/utility/SdFat.h:431:1: error: unknown type name 'class'
     class SdVolume {

     ^
    /home/user/Arduino/libraries/SD/src/utility/SdFat.h:431:16: error: expected '=', ',', ';', 'asm' or '__attribute__' before '{' token
     class SdVolume {

                    ^
    In file included from /home/user/Arduino/libraries/SD/src/SD.h:21:0,
                     from sketch/mylib.h:5,
                     from sketch/mylib.c:1:
    /home/user/Arduino/libraries/SD/src/utility/SdFatUtil.h: In function 'FreeRam':
    /home/user/Arduino/libraries/SD/src/utility/SdFatUtil.h:43:7: error: 'reinterpret_cast' undeclared (first use in this function)
       if (reinterpret_cast<int>(__brkval) == 0) {

           ^
    /home/user/Arduino/libraries/SD/src/utility/SdFatUtil.h:43:7: note: each undeclared identifier is reported only once for each function it appears in
    /home/user/Arduino/libraries/SD/src/utility/SdFatUtil.h:43:24: error: expected expression before 'int'
       if (reinterpret_cast<int>(__brkval) == 0) {

                            ^
    /home/user/Arduino/libraries/SD/src/utility/SdFatUtil.h:45:36: error: expected expression before 'int'
         free_memory = reinterpret_cast<int>(&free_memory)

                                        ^
    /home/user/Arduino/libraries/SD/src/utility/SdFatUtil.h:49:36: error: expected expression before 'int'
         free_memory = reinterpret_cast<int>(&free_memory)

                                        ^
    /home/user/Arduino/libraries/SD/src/utility/SdFatUtil.h: In function 'SerialPrint_P':
    /home/user/Arduino/libraries/SD/src/utility/SdFatUtil.h:62:52: error: 'Serial' undeclared (first use in this function)
       for (uint8_t c; (c = pgm_read_byte(str)); str++) Serial.write(c);

                                                        ^
    /home/user/Arduino/libraries/SD/src/utility/SdFatUtil.h: In function 'SerialPrintln_P':
    /home/user/Arduino/libraries/SD/src/utility/SdFatUtil.h:72:3: error: 'Serial' undeclared (first use in this function)
       Serial.println();

       ^
    In file included from sketch/mylib.h:5:0,
                     from sketch/mylib.c:1:
    /home/user/Arduino/libraries/SD/src/SD.h: At top level:
    /home/user/Arduino/libraries/SD/src/SD.h:26:1: error: unknown type name 'namespace'
     namespace SDLib {
     ^
    /home/user/Arduino/libraries/SD/src/SD.h:26:17: error: expected '=', ',', ';', 'asm' or '__attribute__' before '{' token
     namespace SDLib {
                     ^
    /home/user/Arduino/libraries/SD/src/SD.h:119:1: error: unknown type name 'using'
     using namespace SDLib;
     ^
    /home/user/Arduino/libraries/SD/src/SD.h:119:17: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'SDLib'
     using namespace SDLib;
                     ^
    /home/user/Arduino/libraries/SD/src/SD.h:123:14: error: expected '=', ',', ';', 'asm' or '__attribute__' before ':' token
     typedef SDLib::File    SDFile;
                  ^
    /home/user/Arduino/libraries/SD/src/SD.h:124:14: error: expected '=', ',', ';', 'asm' or '__attribute__' before ':' token
     typedef SDLib::SDClass SDFileSystemClass;
                  ^
    In file included from sketch/mylib.c:1:0:
    mylib.h:7: error: expected ')' before '&' token
     void fn(File &_file);
                  ^
    mylib.c:3: error: expected ')' before '&' token
     void fn(File &_file)
                  ^
    exit status 1
    expected ')' before '&' token

If I use SD.h function in mylib, I need this in mylib.h file. Why is it happens?

The first error is about passing object as function argument. I'm following sample I found in others forum, then I don't know why it isn't working.

[SOLVED]
I rename mylib.c to mylib.cpp and solved the problem.

body: SD.h defines `class File`. Without that definition, 'File' is taken to be the name of an untyped argument (which will be assumed to be an int). Given that assumption, '&_file' is unexpected.


body:
Firstly, there are different strategies for organizing header file structure. I don't know which one you follow. Within the popular approach that strives to keep all header files in self-sufficient state, `mylib.h` should include `<SD.h>` since `mylib.h` uses `File` type.

Secondly, when you actually included `<SD.h>` into `mylib.h`, you ran into a different problem. SD library is written as a C++ library. Its header files will not compile as C code. Meanwhile, you are trying to compile `<SD.h>` in C mode by indirectly including it into a `mylib.c` file, which is what causes the errors.

---

This library's header files contain many bizarre coding patterns that might create an impression *as if* someone was trying to make these headers compatible with C code (`static const`? `static inline`? Etc.), but this is an illusion. The code is exclusively C++, not C.


message:
How to change the default Slave Select pin (Digital pin 10) on Arduino UNO R3 for SPI communication?

Currently I am working on an Arduino based project. My project require interfacing 6 servo motors and an SD card module to my Arduino UNO.
The problem is that I need all the six PWM pins for six servos (Including pin 10) which happen to be the default Slave Select Pin for SPI communication. I don't want to use software based PWM on a digital pin. I could not find any resource on how to change the default SS pin to any other pin. Any help in this regard will be highly appreciated. Thanks!

body:
Just declare it and use it:

    byte ssPin = 7; // or any other pin, stay away from 0,1, leave those for Serial()
    byte defaultSS = 10; // 53 on a 2560

    pinMode (ssPin, OUTPUT);
    digitalWrite (ssPIN, HIGH); // typical slave select OFF state
    pinMode (defaultSS, OUTPUT);  // 10 MUST be an output for device to be SPI master (328P)
    SPI.begin(); // default is 4 MHz speed, MSBFIRST
    // takes care of SCK, MISO, MOSI, don't need define/declare those

    digitalWrite (ssPin, LOW);
    SPI.transfer (ledData, 0xAA); // example data going to a device
    digitalWrite (ssPin,  HIGH);


message:
LED does not light when inserted into round Lilypad board

Title: LED does not light when inserted into round Lilypad board.

very simple goal here: i want to plug in a blinking LED [or 10] into a round circuit board [then solder them], then power those LEDs. when i touch the - and + battery wires to the loose LED it lights. as soon as i insert the LED into the Lilypad round prototype board, those same battery wires will not light the LED. of course when i solder the LED in, then touching the battery - and + to two of the outer board contacts, nothing lights. the board is, "LilyPad Prototype Board ProtoBoard by AMX3d - Round Prototype Board for all DIY Electronics project", and the LEDs are, "100pcs 3mm Flat Top Water Clear Fast Rainbow Flash RGB flashing LED Diodes USA". it is like the board thwarts conductivity. thoughts?

board - https://www.amazon.com/gp/product/B01L9B9RSY/ref=oh_aui_detailpage_o03_s00?ie=UTF8&psc=1

LEDs - https://www.ebay.com/itm/121752435838

body:
Your board has every pin directly connected to every other pin.

As it states in the description:

> 10 mil traces connect holes, **cut the ones you do not need** to create a breadboard with infinite possibilities

(Highlighting by me).


message:
Help me determine the power consumption/rating of the circuit below?

![](https://i.stack.imgur.com/ejEmN.jpg)
Please help me determine the circuit's power consumption from the battery and help me outline the steps to calculate?

body:
It's not a simple matter of "calculating the power". Instead you need to:

* Calculate (or obtain) the current consumption of each individual sub-module or component
* Calculate (or obtain) the current consumption of the main MCU for each power state it operates in
* Calculate the current consumption of static items such as voltage dividers and power LED

Then:

For each unit examine the percentage of time it spends in different power states. From that create an hourly average current for the unit.

And finally:

Sum up all the average hourly usages to get a final AH value for the whole circuit.

Most of the current values can be obtained either by calculation (e.g., Ohm's Law for resistive dividers and LEDs, etc), or from the datasheets for the devices you have attached.

Note that this will still only be an approximation, because (amongst other things) you have multiple power sources which will cause different drains on the system depending on which source is being actively used (different monitoring circuitry and components switched it), and that (I assume) is influenced by the weather.


message:
What's the maximum number of keys in Yun Bridge?

The Yun has a [Bridge](https://www.arduino.cc/en/Tutorial/Bridge) for communicating between the Arduino and Linux processors via a key/value hash. The docs say this is actually stored on the Linux side, but it doesn't say what the limit is.

How many key/value pairs can the Bridge store? What are the practical limitations?

body:
The data is just stored in an array within the Python daemon. The ATMega32U4 just sends commands to set / get the values, so there is no limit imposed by the ATMega side of things.

The only limit is the size of the array in Python, and that is restricted by:

* The amount of available memory in Linux, and
* Whether or not you have swap space set up on the Yun

Since both those are very much variable (it depends what processes you have running, what your configuration is, etc) the answer can only really be:

* **Quite a few.**

Putting memory aside for a moment, [an answer to this question on SO](https://stackoverflow.com/questions/855191/how-big-can-a-python-array-get) states:

> According to the source code, the maximum size of a list is PY_SSIZE_T_MAX/sizeof(PyObject*) . On a regular 32bit system, this is (4294967295 / 2) / 4 or 536870912. Therefore the maximum size of a python list on a 32 bit system is 536,870,912 elements.

So you have the smaller of:

* The maximum you can fit in Linux's memory, and
* 536,870,912


message:
Every so often ESP8266 hangs... WifiClient seems to be at fault

This code works fine without any freezes:

    #include <ESP8266WiFi.h>
    #include <Servo.h>
    #include <WiFiClient.h>
    #include <ESP8266WiFiMulti.h>

    Servo turn;

    ESP8266WiFiMulti wifiMulti;

    const char* host = "192.168.1.148";
    WiFiClient client;

    int turnPos = 90;
    unsigned long ts = 0;

    void setup() {
      startWiFi();
      turn.attach(14);
      turn.write(90);
    }

    void loop() {

      if (millis() - ts > 500 && millis() - ts < 1000) {
        turnPos = 160;
      }
      else if (millis() - ts >= 1000) {
        ts = millis();
      }
      else {
        turnPos = 20;
      }

      /*if (client.connected()) {
        }
        else {
        if (!client.connect(host, 3000)) {
        }
        }*/

      turn.write(turnPos);
      yield();
    }

    void startWiFi() {
      wifiMulti.addAP("DVW3201BE8", "###");   // password is filled in on mny version
      while (wifiMulti.run() != WL_CONNECTED) { // Wait for the Wi-Fi to connect: scan for Wi-Fi networks, and connect to the strongest of the networks above
        delay(250);
        Serial.print('.');
      }
    }

While this code (with the wificlient bit commented out) freezes every so often:

    #include <ESP8266WiFi.h>
    #include <Servo.h>
    #include <WiFiClient.h>
    #include <ESP8266WiFiMulti.h>

    Servo turn;

    ESP8266WiFiMulti wifiMulti;

    const char* host = "192.168.1.148";
    WiFiClient client;

    int turnPos = 90;
    unsigned long ts = 0;

    void setup() {
      startWiFi();
      turn.attach(14);
      turn.write(90);
    }

    void loop() {

      if (millis() - ts > 500 && millis() - ts < 1000) {
        turnPos = 160;
      }
      else if (millis() - ts >= 1000) {
        ts = millis();
      }
      else {
        turnPos = 20;
      }

      if (client.connected()) {
        }
        else {
        if (!client.connect(host, 3000)) {
        }
        }

      turn.write(turnPos);
      yield();
    }

    void startWiFi() {
      wifiMulti.addAP("DVW3201BE8", "###");   // password is filled in on mny version
      while (wifiMulti.run() != WL_CONNECTED) { // Wait for the Wi-Fi to connect: scan for Wi-Fi networks, and connect to the strongest of the networks above
        delay(250);
        Serial.print('.');
      }
    }

Only difference is in the working one the WifiClient bit of code is commented out.   How would WifiClient cause this problem?

body:
It is a bug and it was fixed in Arduino esp8266 core package 2.4.2 published 2 days ago.

see first line in ESP8266WiFi section of the [changes list][1]

> 2.4.2 ESP8266WiFi:
> Fix memory leak when reusing WiFiClient object (#4497, #4516, #4549)

  [1]: https://github.com/esp8266/Arduino/releases


message:
Safely powering a relay from same source as attiny/arduino?

My project involves using ATTINY to control a 5v relay (specifically JZC-11F and will be ground triggered) in an automotive setting.

I keep seeing the warnings of powering a relay from the same source as the ATTINY (or arduino), everything I can find says you need a completely separate source.

I'm still working on a 12~v to 5v power circuit that is safe from the issues that arise from being in an automotive setting (load dumps, noisy, reverse polarity protection..etc) but saying I have that figured out and I have a clean 5v source for power, do I have to duplicate that circuit just for the relay? or are there a ways of preventing the relay from eventually shorting out the ATTINY?

Plan B:
What if I scratch the whole 5v relay and set it up to trigger an external standard 12v automotive relay (this is probably more ideal)? Is the ATTINY capable of triggering a 12v relay via ground? if not what are the recommended ways of making this happen?

side note: I'm know code I don't know EE but I'm trying. The end goal is to combine everything onto a custom pcb, so any suggestions about the 12v-5 using an off the shelf car usb adapter or a premade board are unnecessary (seems to be the go-to answer on that subject). I have a separate post regarding that circuit so if at all possible please stick to the relay questions.

body:
> do I have to duplicate that circuit just for the relay?

No, not really, no.

> Is the ATTINY capable of triggering a 12v relay via ground?

The ATTtiny is capable of triggering a transistor - the transistor is capable of triggering a 12V relay.

Unless your relay is incredibly high powered and the coil takes (and generates through back-EMF) massive amounts of current, there really is no problem running it alongside a small microcontroller. Just be sure you have the flyback diode, and maybe a damping capacitor as well to absorb noise.

TBH you're probably going to be getting more noise from contact spark than you are from the relay's coil.


message:
Button Matrix Code and Wiring

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

Bear with me here, I'm new to arduinos, so what I'm saying might only make sense in my own mind.

I'm trying a button matrix and I not completely sure on my wiring and I have a few questions.

 1. Is the diagram correct?
 2. I wire D2 to D3 and set them to output and input respectively. In the code I digital write to D2 a HIGH, will D3 then read high?
 3. What is the best way to read the state of each button? Is there a Library that can simplify it?

I'm sorry if this is all just confused gibberish.

EDIT: I got the idea from this [video][2], which explains some of it, but no code. He however uses an arduino micro.

EDIT #2: I realized I wired the buttons incorrectly.

  [1]: https://i.stack.imgur.com/g6oHI.png
  [2]: https://www.youtube.com/watch?v=Z7Sc4MJ8RPM

body:
@Jot commented to use the [Keypad Library][1]. Which I got to work using the [tutorial][2]. Took a few minutes to set up.

  [1]: http://playground.arduino.cc/Code/Keypad
  [2]: https://playground.arduino.cc/Main/KeypadTutorial


message:
How to convert byte *payload to String

I would like to convert a `byte *payload` to a `String`, because I want to compare the content of `payload` to another `String`.

    void mqttCallbackHandler(char *topic, byte *payload, unsigned int length) {
      String payloadstr = ???
      ...
    }

body:
Consider simply using the returned pointer.

Payload is a pointer of type byte.  You can compare each byte in a string to the byte the pointer is pointing at. Then increment the pointer to the next byte and repeat the process. You don't need to allocate more memory for new string.

If a type string is necessary.  For example, if you were using a complex library method which requires a string to be passed to it, you could copy what the returned pointer is pointing at byte by byte into a locally defined string.


body:
For comparing a byte array to a String object, you could convert the
byte array to another String object, but this involves dynamically
allocating memory for a whole copy of the string. This is memory
unfriendly, and preferably avoided on small microcontrollers.

The cheapest way to achieve what you want is to compare them as
character arrays :

    if (strcmp((char *) payload, theReferenceString.c_str()) == 0) {
        // the strings are equal
    }

`strcmp()` is a standard C function that does the byte by byte
comparison, exactly as suggested by st2000.


body:
Depending on what is setting the message on the topic, `payload` may, or may not be, a NULL-terminated string.  This is why they provide the `length` parameter.

You could consider comparing the data with `memcmp()` which is like `strcmp()` but doesn't look for a NULL termination - instead it takes a length parameter.  This is good if you may have NULL bytes in your payload.

An alternative is `strncmp()` which both looks for a NULL termination and also limits the length using a `length` parameter. Better for payloads you know are strings, but you aren't sure if they have NULL termination or not.

Here is a callback (for PubSubClient on ESP8266) I have in one of my projects which uses `strncmp()`:

    void callback(char *topic, byte *payload, unsigned int length) {
     if (!strcmp(topic, SUBTOPIC)) {
      if (!strncmp((char *)payload, "on", length)) {
       digitalWrite(POWERPIN, HIGH);
       powerState = true;
       client.publish(PUBTOPIC, "on", true);
      } else if (!strncmp((char *)payload, "off", length)) {
       digitalWrite(POWERPIN, LOW);
       powerState = false;
       client.publish(PUBTOPIC, "off", true);
      }
     }
    }

Simply casting your payload to `(char *)` is enough for the functions to take it as a string, and the `length` parameter will prevent looking past the end of the payload if there is no NULL termination.

It's not perfect - a single byte payload of `o` will falsely match the first `on`, but if that is a critical problem I am sure you can find a way to work around it by checking what `length` equals.


body:
This is an old post but probably somebody can use this info:

    void mqtt_callback(char* topic, byte* payload, unsigned int length) {
      String topicStr = topic;
      String recv_payload = String(( char *) payload);

      Serial.println( "mqtt_callback - message arrived - topic [" + topicStr +
                      "] payload [" + recv_payload + "]" );
    }


body:
[Marco's answer][1] worked for me, but worked better with:

    payload[length] = 0;
    String recv_payload = String(( char *) payload);

Therefore, the full code would be:

    void mqtt_callback(char* topic, byte* payload, unsigned int length) {
      String topicStr = topic;
      payload[length] = 0;
      String recv_payload = String(( char *) payload);

      Serial.println( "mqtt_callback - message arrived - topic [" + topicStr +
                      "] payload [" + recv_payload + "]" );
    }

  [1]: https://arduino.stackexchange.com/a/75772/19409


message:
Read frequency of input in digital pins

This is a somewhat theoretical question:
Let's say I have some sensor that sends digital signals to one of Arduino's digital ports.
Now, I don't know the frequency it sends those signals in.
For example, the frequency of the sensor output could be 100Hz, so every 1/100 of a second it varies the voltage (or keeps the old voltage if the next signal is the same as the previous one), but it could just as well be 200Hz.
Would Arduino be able to faithfully read the digital signal regardless of its frequency? Or is there a conventional frequency that digital devices usually use for output?
Wouldn't it be the case that if Arduino expects 100Hz signal, but the signal is 200Hz it would miss half the inputs?
For: (1 0 1 0 0 1...) wouldn't it see: (1 1 0) - that is skip every other input because it's sampling rate would be too slow by half?
Thanks kindly for your help..

body:
100 Hz is pretty trivial. See [my page about timers](http://www.gammon.com.au/timers).

This sketch can detect frequencies up to about 5 MHz:

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

    // Timer and Counter example
    // Author: Nick Gammon
    // Date: 17th January 2012

    // Input: Pin D5

    // these are checked for in the main program
    volatile unsigned long timerCounts;
    volatile boolean counterReady;

    // internal to counting routine
    unsigned long overflowCount;
    unsigned int timerTicks;
    unsigned int timerPeriod;

    void startCounting (unsigned int ms)
      {
      counterReady = false;         // time not up yet
      timerPeriod = ms;             // how many 1 ms counts to do
      timerTicks = 0;               // reset interrupt counter
      overflowCount = 0;            // no overflows yet

      // reset Timer 1 and Timer 2
      TCCR1A = 0;
      TCCR1B = 0;
      TCCR2A = 0;
      TCCR2B = 0;

      // Timer 1 - counts events on pin D5
      TIMSK1 = bit (TOIE1);   // interrupt on Timer 1 overflow

      // Timer 2 - gives us our 1 ms counting interval
      // 16 MHz clock (62.5 ns per tick) - prescaled by 128
      //  counter increments every 8 µs.
      // So we count 125 of them, giving exactly 1000 µs (1 ms)
      TCCR2A = bit (WGM21) ;   // CTC mode
      OCR2A  = 124;            // count up to 125  (zero relative!!!!)

      // Timer 2 - interrupt on match (ie. every 1 ms)
      TIMSK2 = bit (OCIE2A);   // enable Timer2 Interrupt

      TCNT1 = 0;      // Both counters to zero
      TCNT2 = 0;

      // Reset prescalers
      GTCCR = bit (PSRASY);        // reset prescaler now
      // start Timer 2
      TCCR2B =  bit (CS20) | bit (CS22) ;  // prescaler of 128
      // start Timer 1
      // External clock source on T1 pin (D5). Clock on rising edge.
      TCCR1B =  bit (CS10) | bit (CS11) | bit (CS12);
      }  // end of startCounting

    ISR (TIMER1_OVF_vect)
      {
      ++overflowCount;               // count number of Counter1 overflows
      }  // end of TIMER1_OVF_vect

    //******************************************************************
    //  Timer2 Interrupt Service is invoked by hardware Timer 2 every 1 ms = 1000 Hz
    //  16Mhz / 128 / 125 = 1000 Hz

    ISR (TIMER2_COMPA_vect)
      {
      // grab counter value before it changes any more
      unsigned int timer1CounterValue;
      timer1CounterValue = TCNT1;  // see datasheet, page 117 (accessing 16-bit registers)
      unsigned long overflowCopy = overflowCount;

      // see if we have reached timing period
      if (++timerTicks < timerPeriod)
        return;  // not yet

      // if just missed an overflow
      if ((TIFR1 & bit (TOV1)) && timer1CounterValue < 256)
        overflowCopy++;

      // end of gate time, measurement ready

      TCCR1A = 0;    // stop timer 1
      TCCR1B = 0;

      TCCR2A = 0;    // stop timer 2
      TCCR2B = 0;

      TIMSK1 = 0;    // disable Timer1 Interrupt
      TIMSK2 = 0;    // disable Timer2 Interrupt

      // calculate total count
      timerCounts = (overflowCopy << 16) + timer1CounterValue;  // each overflow is 65536 more
      counterReady = true;              // set global flag for end count period
      }  // end of TIMER2_COMPA_vect

    void setup ()
      {
      Serial.begin(115200);
      Serial.println("Frequency Counter");
      } // end of setup

    void loop ()
      {
      // stop Timer 0 interrupts from throwing the count out
      byte oldTCCR0A = TCCR0A;
      byte oldTCCR0B = TCCR0B;
      TCCR0A = 0;    // stop timer 0
      TCCR0B = 0;

      startCounting (500);  // how many ms to count for

      while (!counterReady)
         { }  // loop until count over

      // adjust counts by counting interval to give frequency in Hz
      float frq = (timerCounts *  1000.0) / timerPeriod;

      Serial.print ("Frequency: ");
      Serial.print ((unsigned long) frq);
      Serial.println (" Hz.");

      // restart timer 0
      TCCR0A = oldTCCR0A;
      TCCR0B = oldTCCR0B;

      // let serial stuff finish
      delay(200);
      }   // end of loop

---

> Or is there a conventional frequency that digital devices usually use for output?

No.

> Wouldn't it be the case that if Arduino expects 100Hz signal, but the signal is 200Hz it would miss half the inputs? For: (1 0 1 0 0 1...)

No.

Why would it "expect" a frequency? It isn't a person expecting a chocolate cake on its birthday.

---

> So whatever frequency the sensor sends its data in - be it 100Hz or 5Mhz - Arduino is smart enough to read all the voltage signals faithfully?

I'm not quite sure what you mean by "read all the voltage signals" which seems to imply you want to measure the voltage.

> so every 1/100 of a second it varies the voltage (or keeps the old voltage if the next signal is the same as the previous one)

But then you say:

>  let's assume that the 1 voltage is high enough (but not too high) for Arduino to register a 1, and the 0 voltage is also within the threshold for Arduino to register a zero (say 5V for HIGH and 0.5V for LOW). It's the frequency of the signal I'm concerned with.

The voltage levels for 0 and 1 are documented in the datasheet. For the Atmega328P for *most* pins they are as follows:

[![Low and high voltage levels][1]][1]

You can see that if Vcc is 2.4V or above then LOW is -0.5V to 0.3 * Vcc, which if Vcc is 5V then a LOW is -0.5 to 1.5V.

Similarly a HIGH is 0.6V * Vcc to Vcc + 0.5, so if Vcc is 5V then a HIGH is 3V to 5.5V.

In between 1.5V and 3V then the digital status would be undefined.

So, if your LOW and HIGH are in those voltage ranges, yes you can detect the frequency of the signal.

I'm not sure about the bit where you said "keeps the old voltage if the next signal is the same as the previous one". That seems to imply that if the signals stay the same (eg. for a second) then the voltage won't change at all, and thus the frequency will be zero.

  [1]: https://i.stack.imgur.com/GMe6Q.png


message:
Text send via HC-05 is broken up by first character on the receiving end?

On the receiving end, I have an mit app inventor app which acts like a client.

In arduino, I check for connection status and do a serial write to send the text. The code for that is below:

    #include <SoftwareSerial.h>

    #define D2 2
    #define D3 3
    #define BT_STATE_PIN 4

    SoftwareSerial BTSerial(D3, D2);
    long lastMark;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(38400);
      BTSerial.begin(9600);
      pinMode(BT_STATE_PIN, INPUT);

      int counter = 0;
      lastMark = millis();
    }

    bool isBTConnected() {
      return (digitalRead(BT_STATE_PIN) == HIGH);
    }

    void sendText(char* message) {
      Serial.println("SEND: " + String(message));
      if(isBTConnected()) {
        BTSerial.write(message);
      }
      else {
        Serial.println("did not send");
      }
    }

    int msgCount = 0;
    void loop() {
      long now = millis();

      if(now - lastMark > 2500) {
        msgCount++;
        String msg = "This is a really really long MSG" + String(msgCount);
        sendText(msg.c_str());
        if(msgCount == 5) {
          msgCount = 0;
        }
        lastMark = millis();
      }
    }

This is how the device is wired currently:

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

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

<!-- End schematic -->

On the app inventor side of things, I have a very simple app that connects to the bluetooth module; it listens for anything received, and then just receives the text.

[aia file](https://drive.google.com/open?id=1i7ldprCETYYhN0h5B2-2LvDhyUlQuU1r)

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

Here is a pic showing the issue I am facing currently:

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

Sometimes the breaking up happens randomly at some other place. Hoping someone can help sort this issue.

  [1]: https://i.stack.imgur.com/wFhVR.png
  [2]: https://i.stack.imgur.com/8vom9.jpg

body:
Without having experience in AppInventor, I see the following problem:

In your app you are outputting the received data regularly with a timer in form of distinct messages. This code can naturally only display text, that was already received. You seem to think, that only because you use a single line oft code on Arduino for sending the message data, the data would be send in one big chunk. For Serial that is not the case. Actually the `write()` function only fills the libraries buffer and the actual data will then be send serially (thus the name). There is nothing like a chunk of data or a message on a serial interface, unless you yourself impose this principle on the data stream. All the bytes in the libraries buffer are the same and are being send in the order of the buffer. Moreover Bluetooth does consist of packages of data, but they will be automatically packed; in a way that will not correspond to your messages.

So in the end, arbitrary parts of your message will be received by the phone at arbitrary times, that highly depend on timing conditions. In your code you should constantly receive the data and only display a message, when you have received an `\n` character, which is the delimiter of a message. It is a very common and helpful technique to first receive a full message and then processing it, when the message is complete.


body:
I did something similar (multiBT) using HC-05 and PC BT, with the same App.
Results: all the incoming data from the PC_BT to the phone are right, but with the HC-05 sometimes is chunked as @deostrol show. I think is a bug with the HC-05 firmware.

To correct this, I've implemented StartBegin and StopFinish character in the received string before use.


message:
Ethernet socket impedes adding shields

I just bought a KEYESTUDIO W5500 Ethernet Arduino without realizing that the Ethernet socket on the board impedes adding any additional shields to the device because:

 1. Horizontally the socket runs right up next to the shield connector sockets

 2. Vertically the socket is a good 1/4 inch higher that the shield connector
    sockets

Is there a good solution for extending the shield connector sockets vertically so that they clear this Ethernet socket?

body:
Plug some of these into the Arduino headers to add extra space.

They come in different lengths and can be cut to the required number of pins.

They also come in different pin lengths.

Google `long tailed pin headers`.

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

  [1]: https://i.stack.imgur.com/5poQNm.png


message:
Software Gate on a PWM port

I'm using a PWM port and outputting a freq. Is it possible to pulse the PWM port using software to simulate a pulse gate. For example, I'd like to output a freq of 111hz, but would like to gate that freq at .5-7hz. Is this possible to do all in software without external hardware. I'm using a Teensy board which is similar to an Arduino, but has 3 independent PWM ports. Any ideas on whether this possible?

body:
If you can configure the PWM to run at 111 Hz (I don't know how
this is done on the Teensy), then “gating” it is as simple as turning
the PWM on and off at the desired frequency:

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

    uint32_t half_period;  // half the gating period in microseconds

    void set_gate_frequency(float freq_in_hz)
    {
        half_period = (1e6 / 2) / freq_in_hz;
    }

    void loop()
    {
        static uint32_t last_toggle = 0;
        static bool pwm_is_on = false;
        if (micros() - last_toggle >= half_period) {
            if (pwm_is_on) {
                digitalWrite(PWM_PIN, LOW);
                pwm_is_on = false;
            } else {
                analogWrite(PWM_PIN, 128);  // PWM with 50% duty cycle
                pwm_is_on = true;
            }
            last_toggle += half_period;
        }
    }


message:
How to automatically reset the nrf24l01+ with code?

I have two separate nrf24l01+ connected to two different Arduino UNOs, one as TX and the other as RX. The problem is the connection stops after a while between them.

On the Arduino COM screen I have noticed these things:

**TX Side:** Completely Frozen (Transmission Stops).
**RX Side:** Continuously receives the last data repeatedly.

The problem is solved temporarily when the TX MCU (hence the nrf) is restarted .Sometimes even after restarting the TX MCU the RX stops responding and I have to restart the RX as well. Therefore I am trying to find a way to reset my nrfs automatically using software when this situation occurs.

body:
I found the problem occurs because the transmitter is expecting acknowledgment from the receiver which is getting lost somehow, while transmission and the transmitter still waits for ack for the last transmitted data (which it never gets) so it keeps on transmitting the last packet again and again. I saw on forums that its because of the TX buffer getting full after 3 retries or something. I don't exactly know why it happens.

I first tried resetting just the transmitter through code but it was not enough (as already mentioned in the question). So I now reset both the TX and RX using the below code. I have a separate 1 byte reset-counter in the first byte of the array (you may use a single byte variable) which acts as an id for the packet (you may use the internal PID as well).

The below code resets  the **TX** if **transmission fails** by checking the **return value** of `write` function and resets the **RX** when it **receives the same ack** or packet (with the same reset-counter value) **more than 2 times** (I use a condition to check if the last counter value is different from the current one or not). To reset it using code I use the below algorithm :

 1. **Power Down** the NRF using `powerDown()` function.
 2. **Re-initialize** the nrf for the MCU.
 3. **Power Up** the NRF using `powerUp()` function.

**Note:** I am using TMRH20 RF24 Library.

**TX Code**

    void radio1_init()
    {
      pinMode(9, OUTPUT);
      digitalWrite(9, HIGH);
      pinMode(10, OUTPUT);
      digitalWrite(10, HIGH);
      myRadio1.begin();
      delay(100);
      myRadio1.setChannel(96);
      myRadio1.setPALevel(POWERLEVEL);
      myRadio1.setDataRate(DATARATE);
      myRadio1.setAutoAck(1);
      myRadio1.enableAckPayload();
      myRadio1.enableDynamicPayloads();
      myRadio1.setRetries(2, 10);
      myRadio1.setCRCLength(RF24_CRC_8);
      myRadio1.openWritingPipe( addresses1[0]);
    }

    void loop()
    {
      dataTransmitted[0]++;
      if ( myRadio1.write( &dataTransmitted, sizeof(dataTransmitted)))
      {

        if (myRadio1.isAckPayloadAvailable())
        {
          myRadio1.read(&ack, sizeof(ack));
        }
      }
      else
      {
        myRadio1.powerDown();
        \\Serial.println(" 1 Tx1 problem end");
        radio1_init();
        myRadio1.powerUp();
      }
    }

**RX Code**

    void radio2_init()
    {
      pinMode(9, OUTPUT);
      digitalWrite(9, HIGH);
      pinMode(10, OUTPUT);
      digitalWrite(10, HIGH);
      myRadio2.begin();
      delay(100);
      myRadio2.setChannel(96);
      myRadio2.setPALevel(POWERLEVEL);
      myRadio2.setDataRate(DATARATE);
      myRadio2.setAutoAck(1);
      myRadio2.enableAckPayload();
      myRadio2.enableDynamicPayloads();
      myRadio2.setRetries(10, 10);
      myRadio2.setCRCLength(RF24_CRC_8);
      myRadio2.openReadingPipe(1, addresses2[0]);
      myRadio2.startListening();
    }

    void loop()
    {
          if (myRadio2.available())
          {
            myRadio2.read( &dataReceived, sizeof(dataReceived));
            myRadio2.writeAckPayload(1, &ack2, sizeof(ack2));
            if (prevack2 == dataReceived[0])
            {
              \\Serial.println("RX 2 problem");
              c2++;
            }
            prevack2 = dataReceived[0];
            if (c2 > 2)
            {
              myRadio2.powerDown();
              radio2_init();
              myRadio2.powerUp();
              c2 = 0;
            }
          }
    }


body:
If you use standard arduino pin cables, then they do not provide stable connectivity for NRF24L01+. Try to solder pins instead (not kidding).

Another reason could be that one of your modules has bad power supply. Power it with perfect 3.3 volts (from another power source, not from Arduino), or use "base module" for the NRF24L01+ (connect this "base module" to 5V pin on Arduino)
http://www.yourduino.com/sunshop/index.php?l=product_detail&p=467


body:
If the NRF24L01 truly locks up, as can happen with an inadequate power supply, then the powerDown(), init(), powerUp() method wont work as the NRF wont receive SPI commands.
In this situation, which seems to be the most common form of lockup, a physical power cycle is the only option.


message:
How to determine the source of constants in libraries?

Preamble:

I am trying to figure out how to program and use the timers in the Feather M0 using the Arduino IDE. I have seen a number of examples published, but I'm not one to just blindly copy some code and expect it to work. The issue that I'm having (and it seems to be ubiquitous in Arduino) is that there does not seem to be a concept of dependencies. In order to reference constants, they have to be defined somewhere.

Question:

How can I find the source of the definition of the constants that people keep referring to in their code? For example, in this code [a Arduino Zero, M0 timer example][1], reference is made to `TC_CTRLA_PRESCALER_DIV1` among other constants. Where is this constant defined?

Efforts:

I've searched generally and specifically for these constants. But, as you would imagine in C, it's difficult to find the actual source versus a simple reference to the constant.

I've also tried a search in the installed Arduino IDE with SAMD and Adafruit SAMD libraries installed. For example

    ~/Arduino$ grep -r --include=*.h --include=*.cpp "TC.*_PRESCALER_DIV"

Did not yield anything. I apologize if this is a naive question, but I haven't been able to find a simple, obvious answer. Actually, I haven't been able to find any answer.

  [1]: https://github.com/avandalen/avdweb_SAMDtimer

body:
First of all, the definitions of these constants won't tell you very much. They just represent the registers and bits used in the datasheet of the microcontroller.

If you do want to find their definitions, try looking in `~/.arduino15/`.