message:
What Arduino data type allows decimals?

This probably sounds dumb, but I am not getting any clear answer for this. What data type allows a reasonable amount of decimals?

body:
> At least 2 or 3 [digits], just the type smallest amount above this so I can
> save processing power on my Trinket board

Processors (computers) do not normally store values in [Binary Coded Decimal (BCD)][1] (as in base 10) because such storage wast valuable space.  Rather, processors usually use [Binary numbers][2] (as in base 2).

Most processors deal with binary values in multiples of 8 bits.  So, values are usually represented by 8 bits, 16 bits, 32 bits, ect.  An 8 bit binary number can have 2^8 possible values or 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 or 256. That is to say, an 8 bit binary number can have values between 0 and 255 inclusive.

If your requirement of "reasonable amount of decimals" falls within that range, then the type you are looking for is "uint8_t" or "char".  Both are normally 8 bits in the C / C++ language.  If you need more the next binary number has 16 bits or 2^16 or values between 0 and 65535.  Then the type you are looking for is "uint16_t" or "unsigned int".

  [1]: https://en.wikipedia.org/wiki/Binary-coded_decimal
  [2]: https://en.wikipedia.org/wiki/Binary_number


sender: user

sender: assistant

body:
If you need to represent numbers that are not integers, the simplest
solution is to use floating point variables, also known as “floats”. A
float is declared with the `float` keyword. A numeric constant is
automatically a float if it has a decimal point :

* `42` is an integer (`int` type)
* `42.0` is a float

If you combine an int and a float in an arithmetic operation, the int is
implicitly promoted to float, and the result is a float.

A float gives you a precision of 24 _significant bits_. “Significant”
means that we are counting both the bits _before_ and _after_ the binary
point. Then, a small number will have many fractional bits, whereas a
large number will have only a few, and any number larger than
223 = 8388608 will have _no_ fractional bits at all.

This precision is almost always better that 7 significant decimals and
worse than 8 significant decimals. For example, the following two
numbers are consecutive: any computation that yields a result _in
between_ them will be rounded to either of them (usually the closest):

        binary (24 bits)          decimal
    101010.000000000000000000  42.0
    101010.000000000000000001  42.000003814697265625

The issue with floats is that they are expensive. Unlike a desktop
computer, the Trinket has no hardware support for floats (it's an
ATtiny: it doesn't even have a hardware multiplier!). Then every
computation is done by software. Even the simplest things, like adding
two numbers, can take quite a few CPU cycles and _a lot_ of flash space.
That's why on very small devices people sometimes prefer _fixed point_
arithmetic. In a nutshell, fixed point is all about choosing appropriate
units of measurement in order to achieve the required precision using
only integers. For example, the ADC converter in the Trinket gives you
the voltage readings in units of

    5 V ÷ 1024 = 4.8828125 mV

That unit may seem unpractical, but it allows a reasonable precision
using only integers. If you can avoid converting to volts, you will be
able to write integer-only code which is smaller and faster.

I would suggest you first try using floats, as it's the simplest
solution. If that leads to code with is either too large or too slow,
then try to rewrite with fixed-point (i.e. integer only) arithmetic.


body:
Another option that Edgar doesn't mention (mainly because it's a more esoteric and tricky system to use) is *fixed point* values. These values, also known as *Q* values, are often used in digital signal processing (DSP) since they give predictable resolution and high speed processing.

A Q value is simply an integer where you split the bits within that integer into two portions - the integer portion and the numerator portion.

For instance, you may choose to implement a Q4.11 format. That gives 4 bits of integer value (it can store 0-15) and 11 bits of numerator (that is a decimal resolution of `1/(2^11)` or 0.000488281). The 16th bit (4+11 = 15, in a 16-bit integer there is one more bit to account for) is the implicit sign bit. Some implementations have that, some don't - it's entirely up to you. If you only want positive values you can include the 16th bit in your value to increase resolution or integer size, etc.

You're not limited to 16 bit of course - you could use 8 bit for smaller numbers and lower precision, or 32 bit for bigger numbers and higher precision.

The disadvantage to using Q values compared to using floats is that floats can arbitrarily exchange decimal precision for integer size. With fixed point you have limited yourself to the range of integers you can represent. But that sacrifice can be worth it if you have a limited range in the first place (0-5V, say) and you need extra speed.

To work with fixed point it is first necessary to convert a floating point number to and from your target Q value. This is quite simple - just multiply (or divide to convert from Q to float) the value by the Q value of 1. That is, for a Q4.11 you would use the value of the 12th bit (the first of the integer bits), or 1<<11 (start counting from 0, so the 12th bit is 11).

Once you have your Q values adding and subtracting is just that - exactly as normal, using the `+` and `-` operators. Multiplying and dividing though is slightly more involved, but the resultant code is considerably more efficient. The whole lot can be done using just left and right shifts. For instance, some functions which I use in a small library of mine for Q15 values (more specifically Q0.15), which store values between ±1 with 15 bit resolution, look like:

    typedef int16_t Q15;

    static inline int16_t __satQ15(int32_t x)
    {
        if (x > 0x7FFFL) return 0x7FFF;
        else if (x < -0x8000L) return -0x8000;
        else return (int16_t)x;
    }

    static inline Q15 Q15_mul_Q15(Q15 a, Q15 b) {
        int16_t result;
        int32_t temp;

        temp = (int32_t)a * (int32_t)b; // result type is operand's type
        // Rounding; mid values are rounded up
        temp += (1 << 14);;
        // Correct by dividing by base and saturate result
        result = __satQ15(temp >> 15);
        return result;
    }

    static inline Q15 Q15_div_Q15(Q15 a, Q15 b)
    {
        int16_t result;
        int32_t temp;

        // pre-multiply by the base (Upscale to Q16 so that the result will be in Q8 format)
        temp = (int32_t)a << 15;
        // Rounding: mid values are rounded up (down for negative values).
        if ((temp >= 0 && b >= 0) || (temp < 0 && b < 0))
            temp += b / 2;
        else
            temp -= b / 2;
        result = (int16_t)(temp / b);

        return result;
    }

You can learn more about Q numbers here:

* https://en.wikipedia.org/wiki/Q_(number_format)


message:
SoftwareSerial data not available

Second time I'm asking the same question with no solution, let me elaborate in other way for clarity.

I wrote an Arduino program which uses two serial ports, one is hardware serial port and other is SoftwareSerial port.

No problem with hardware serial port, the problem is with software serial port.

The software serial port's Tx pin works but Rx pin does not work, i.e. `portone.available()` is always zero, nothing in the input buffer of the software serial port.

I'm using Arduino IDE 1.6.12 with an Uno board. Previously I used version 1.6.9 but neither works. Here is the piece of code:

    #include <SoftwareSerial.h>

    String code = "", customer = "";
    bool complete = false;
    byte c = 0, j = 0;
    char customercode[27];
    SoftwareSerial portone(10, 11);
    void setup() {
      Serial.begin(9600);
      portone.begin(115200);
      pinMode(10, INPUT);
      pinMode(11, OUTPUT);
      if (Serial) {
        Serial.print("Connecting");
      }
    }

    void loop() {
      String copy = "";
      char inchar = '0';

      if (Serial.available() > 0) {
        while (Serial.available()) {
          char bytes = (char)Serial.read();
          if (bytes == '1' || bytes == '2' || bytes == '3' || bytes == '4' || bytes == '5' || bytes == '6' || bytes == '7' || bytes == '8' || bytes == '9' || bytes == '0' || bytes == '.' || bytes == '-' && bytes != '#') {
            customercode[c] = bytes;
            c++;
          } else if (bytes == '#') {
            complete = true;
          }
          if (c > 12 && bytes != '#') {
            code += bytes;
          }
        }

        if (c == 13) {
          customer += '+';
          for (byte i = 0; i < 12; i++) {
            customer += customercode[i];
          }
        }
      }
      portone.listen();
      if (portone.available() > 0) {
        portone.println("AT+CMGF=1");
        portone.println("AT+CNMI=2,2,0,0,0");
        portone.flush();

        while (portone.available()) {
          inchar = (char)portone.read();
          copy += inchar;
        }
        delay(1);
        Serial.print(copy);

      } else if (complete == true && customercode != "" && code != "") {
        sending();
      }
      Serial.print(portone.available());
      delay(1000);
    }

body:
Don't call `portone.listen()`.  That method is only necessary when you have created *multiple* `SoftwareSerial` ports.  It specifies which port you are listening to, because only one of them can receive at a time (you can transmit on any of them at any time).  It also *empties the receive buffer* so that data from one `SoftwareSerial` port is not mistakenly returned by another.  In your code, this empties the input buffer before checking `portone.available()`.  Surprise, it's always empty!  ;)

Also, don't set the pin mode of the pins used for the `SoftwareSerial` object.  The pin modes were set during the constructor of `portone`, which happens before `setup`.  You're messing with pins that have been "promised" to that library for its own use and control.

As Edgar suggested, you should consider a more-efficient software serial library.  AltSoftSerial is best, but is only available on certain pins.  My [NeoSWSerial](https://github.com/SlashDevin/NeoSWSerial) library is next best, and works on any two pins, but only at 9600, 19200 and 38400.  Both of those libraries can transmit and receive at the same time, unlike `SoftwareSerial`.  [Here](https://arduino.stackexchange.com/questions/26240#26277) is an answer with all the gory details.

And you really should ditch the `String` class usage.  You obviously know how to use `char` arrays (aka "C strings").  We can't see the `sending()` function, but you can probably just print a few pieces instead of building a complete `String` and printing it:

        portone.print( '+' ); // leading plus sign
        portone.write( (uint8_t *) customerCode, 13 ); // array of bytes, length

It would be better to terminate the character arrays with a zero byte (NUL-termination) in `loop` so they can be used as a standard C string instead of a byte array:

        customerCode[14] = '\0'; // NUL-terminate the C string

Then you can use the standard C string `print` in `sending`:

        portone.print( '+' ); // leading plus sign
        portone.print( customerCode );

Printing the pieces is always more efficient than building a big buffer with all the pieces.  This avoids copying the pieces and needing twice as much RAM.     :P


message:
Low power wifi temperature sensor

I want to make a wifi-enabled temperature sensor and place it inside my HVAC system to measure and push the temperature to a central server, every minute or so.

I have a LoLin NodeMcu v3 unit laying around, and I am wondering if it is possible to use this one - and have it last for many years inside the HVAC system?

I realize the LoLin unit has a onboard wifi chip, I also realize LoLin takes 3v input. Aside from that, I am pretty blank.

Yesterday I tested the LoLin board by programming it with the following code, which lists networks in the vicinity. It worked great:

    #include "ESP8266WiFi.h"

    void setup() {
      Serial.begin(9600);
      // Set WiFi to station mode and disconnect from an AP if it was previously connected
      WiFi.mode(WIFI_STA);
      WiFi.disconnect();
      delay(2000);
      Serial.println("Setup done");
    }

    void loop() {
      Serial.println("scan start");

      int n = WiFi.scanNetworks();// WiFi.scanNetworks will return the number of networks found
      Serial.println("scan done");
      if (n == 0)
        Serial.println("no networks found");
      else
      {
        Serial.print(n);
        Serial.println(" networks found");
        for (int i = 0; i < n; ++i)
        {
          // Print SSID and RSSI for each network found
          Serial.print(i + 1);
          Serial.print(": ");
          Serial.print(WiFi.SSID(i));
          Serial.print(" (");
          Serial.print(WiFi.RSSI(i));
          Serial.print(")");
          Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*");
          delay(10);
        }
      }
      Serial.println("");

      // Wait a bit before scanning again
      delay(5000);
    }

**The actual question**

Is the LoLin board a feasible board for making a low power wifi enabled temperature sensor? Or should I rather make board that communicates with a wall-connected parent unit via radio?

body:
Yes, the NodeMCU can connect to a temperature sensor and forward that on to your WiFi access point to send to the internet.

Yes, the NideMCU can run from batteries.

Can it do it off one battery for many years? Only if that battery contains a small nuclear reactor.

Running something from battery for many years requires incredibly close attention to detail and incredibly tight component specifications, even down to the precise battery chemistry used. It's a very very difficult task for which people are very highly paid.

When you start looking at periods like that you begin to run up against the problem of battery self-discharge. Getting your power consumption down to an absolute minimum is a must, but even then if you have near zero power consumption the battery is still going to go flat by itself. So you have to invest time and effort into selecting a battery technology with a very low self-discharge.

All that is pretty moot though with the NodeMCU since:

* WiFi is a power hungry technology. You can expect hundreds of mA while transmitting, and doing that once a minute for, say, 10 seconds (reconnecting to the WiFi takes time) will give you quite a high average power consumption just from the WiFi
* The NodeMCU is far from optimised WRT power consumption. Linear voltage regulators, poor choice of components for low power consumption, etc, abound.

So yes you can run it from batteries, but be prepared to replace the batteries very often. By "very often" I mean every couple of days.

That means you basically have two options:

1. Don't use the NodeMCU but instead use something designed to be incredibly low power and run for long periods on battery (typically it won't use WiFi but something more efficient like nRF24L01+)
2. Don't use batteries. Hard-wire your NodeMCU into a mains-connected power supply.


message:
Input PUK code, when requested

**Problem**:

I'm working with a **GPRS** module (the same as in the Arduino GSMShield). In some cases the PUK code is requested, and the **PIN** is thus **locked**. For this I wrote some code (which can be seen under "Software"). This code is based on the documentation of "[GSM PIN Management][1]". The only problem is that the module is telling us that **both** the **PIN & PUK** code is **locked**. The tutorials, however, does not provide an example **how** we should **resolve** this issue from the Arduino itself.

EDIT: When the SIM card is inserted in a smartphone. The PUK code is requested. When the PUK code is provided (and a new PIN) the SIM card is back to normal. But adding the PUK code via the GSM lib. doesn't really work, in contrast to using a smartphone to unlock the PIN code.

**Question**:

- Does anybody have an idea how to resolve this issue? And if it can be done?

**Hardware**:

- Atmega328p
- Quectel M95 (as GPRS module)

**Software**:

    PINManager.begin();
    int pin_query = PINManager.isPIN();
    Serial.print(F("Pin Query is: ")); //output: -2
    Serial.println(pin_query);
    if(pin_query == -1)
    {
      #ifdef DEBUG
        Serial.println(F("PUK is requested"));
      #endif

      if(PINManager.checkPUK(PUK_NUMBER, PIN_NUMBER_CORRECT) == 0)
      {
        PINManager.setPINUsed(true); // I also think this must by "false". Both things were tested, none of them worked.

      }
    }

  [1]: https://www.arduino.cc/en/Tutorial/GSMToolsPinManagement

body:
I've resolved the issue by using **AT commands** instead of the GSM library provided through Arduino.

    if(sendGPRSCommand(F("AT+CPIN?"),100).equals("AT+CPIN+CPIN:SIMPUKOK")){
        Serial.println(F("PUK is requested, entering it now"));
        String cmd = "AT+CPIN=\"";
        cmd.concat(PUK_NUMBER);
        cmd.concat("\",\"");
        cmd.concat(PIN_NUMBER);
        cmd.concat("\"");
        sendGPRSCommand(cmd,100);
      }
This code checks if the PUK code is requested, this is the case when the `pin_query` is -1 or -2 (see question). When the PUK code is requested the new PIN (which is still the same pin as the old one) is given in combination with the PUK code.
The AT commands were found in [this manual][1].

  [1]: http://www.quectel.com/UploadImage/Downlad/M95_AT_Commands_Manual_V1.2.pdf


message:
How to keep amperage in serial and parallel?

I have a 2000mA AC adapter and also I have the lights that I show here:

[![LED light][1]][1]

[![LED light connected to an Arduino Uno][2]][2]

Each of these lights consume up to 300mA.

If I make a circuit with 3 lights in serial, ¿will the amperage of each light decrease?

If I make a circuit with 3 lights in parallel, ¿will the amperage of each light decrease?

I am asking it because I don't want the lights to decrease the luminosity. I want the maximum luminosity in each light.

The lights are for growing lettuces. Now I am using a low consumption light but are not efficient:
[![Growing vegetables][3]][3]

  [1]: https://i.stack.imgur.com/iyrO4.jpg
  [2]: https://i.stack.imgur.com/lfdnn.jpg
  [3]: https://i.stack.imgur.com/xhBvB.jpg

body:
You haven't said what the voltage rating of your Power Supply is, but if we assume it is a "constant voltage" regulated supply, then it will attempt to maintain a constant voltage up to the rated current capacity (2000 mA).

If you put your LEDs in series, then the voltage from your power supply is distributed across the LEDs, and is therefore lower on each LED. This would cause your LEDs to be less bright.

If you put your LEDs in parallel, then the voltage remains constant.


body:
The simple answer to that is "No, and stop right now whatever you are doing."

Those LEDs, because of their high current requirements, need a *constant current driver*.

First a little theory:

* LEDs in series sum the voltage, the current stays the same.
* LEDs in parallel with no form of current management split the current unevenly and LEDs start dying (or even exploding when you have high currents involved).

If you don't want any control over the brightness then the simplest constant current driver is to use an LM317 voltage regulator [wired in constant current mode](http://www.bristolwatch.com/ccs/LM317.htm).

It is also possible to make a constant current sink (the same as a constant current source but between the LED and ground instead of positive) [using discrete components](http://confocal-manawatu.pbworks.com/w/page/82281019/Constant-Current Circuits).

If you want control of the brightness then the best solution is to use something like the [CAT4101 PWM LED driver](http://www.onsemi.com/PowerSolutions/product.do?id=CAT4101).

Why don't you use a simple resistor like you would for any other small LED? It's quite simple. Both resistors and LEDs characteristics change with heat. When you are using higher currents like this both the resistor and the LED give off heat (more so the LED than the resistor unless you pick too small a wattage). That means you get changes in the characteristics, which means the current you originally calculated for is now wrong - typically the current increases above what you had originally calculated. More current means more heat. More heat means more current. The result: a cascade. Worst case? The LED dies.


body:
If you put them in series the they require 300mA, but you'd need to have a higher voltage (around 10 Volt).

If you put them in parallel, you could keep the same voltage as a single led (around 3.3 Volt), but you'd require trice the amount of current (i.e. 900mA).

You however **need** to add proper current regulation, of you'll **burn out the leds**. The advantage of having the leds in series, is that you only need a single constant current driver.

You could use resistors, but since these leds require that much current, the leds will have to dissipate a lot of heat. Which is both wasteful, and requires special high wattage resistors.


message:
How to add toggle button for LCD display text and backlight?

I have set up a BMP180 and a DHT11 to display data on an HD44780 20x4 LCD.

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

I want to be able to toggle the altitude from meters to feet, the temperature from Celsius to Fahrenheit, and the pressure from absolute to sea level pressure using a tactile push button.

Here is the software code I have:

    // include the library code:
    #include <LiquidCrystal.h>

    // initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    #include <SFE_BMP180.h>
    #include<dht.h>
    dht DHT;

    #define DHT11_PIN 8 // Second pin, leave 3rd pin unconnected 4th is ground
    #include <SFE_BMP180.h>
    #include <Wire.h>

    // You will need to create an SFE_BMP180 object, here called "pressure":

    SFE_BMP180 pressure;

    #define ALTITUDE 237.0 // Altitude of Phillaur in Punjab, India. in meters

    void setup() {
      lcd.begin(20, 4);
      lcd.setCursor(0, 0); // Zeroth Row
      lcd.print("hello, world!");
      lcd.clear();
      int chk = DHT.read11(DHT11_PIN);
      // Initialize the sensor (it is important to get calibration values stored on the device).
      if (pressure.begin()) {
        lcd.print("BMP180 init Success");
        delay(300);
      } else {
        lcd.print("BMP180 init fail");
        while (1); // Pause forever.
      }
    }

    void loop() {
      char status;
      double T, P, p0, a;
      lcd.clear();
      lcd.setCursor(0,0);
      //TODO Display in Feet as well using toggle
      lcd.print("Altitude: ");
      lcd.print(ALTITUDE, 0);
      lcd.print(" mtrs ");
      status = pressure.startTemperature();
      if (status != 0) {
        // Wait for the measurement to complete:
        delay(status);
        status = pressure.getTemperature(T);
        if (status != 0) {
          // Print out the measurement:
          Serial.print("temperature in deg C, From BMP180: ");
          lcd.setCursor(0, 1);
          lcd.print("Tmpratre: ");
          lcd.print(T, 2);
          lcd.print("'C");
          lcd.setCursor(0, 2);
          lcd.print("Humidity: ");
          lcd.print(DHT.humidity, 1);
          lcd.print("%");
          status = pressure.startPressure(3);
          if (status != 0) {
            // Wait for the measurement to complete:
            delay(status);
            status = pressure.getPressure(P, T);
            if (status != 0) {
              lcd.setCursor(0,3);
              // Print out the measurement:
              lcd.print("Pressure: ");
              lcd.print(P * 0.0295333727, 2);
              lcd.print(" mb");
              p0 = pressure.sealevel(P, ALTITUDE);
              // we're at 234 meters (Phillaur, Pb)
              // TODO: toggle to sea level to absolute pressure
              Serial.print("relative (sea-level) pressure: ");
              Serial.print(p0, 2);
              Serial.print(" mb, ");
              Serial.print(p0 * 0.0295333727, 2);
              Serial.println(" inHg");
              a = pressure.altitude(P, p0);
              Serial.print("computed altitude: ");
              Serial.print(a, 0);
              Serial.print(" meters, ");
              Serial.print(a * 3.28084, 0);
              Serial.println(" feet");
            } else Serial.println("error retrieving pressure measurement\n");
          } else Serial.println("error starting pressure measurement\n");
        } else Serial.println("error retrieving temperature measurement\n");
      } else Serial.println("error starting temperature measurement\n");
      delay(5000);  // Pause for 5 seconds.
    }

  [1]: https://i.stack.imgur.com/YO1aV.jpg

body:
You need to connect the button(s) to available digital inputs of the Arduino. I suggest that you use more than one button based on your description in the question.

The following tutorial describes the circuit needed and the associated code to read that input. All you have to do is duplicate it with a few more buttons on separate (available) digital inputs.

[Arduino button tutorial][1]

[![button wiring][2]][2]

  [1]: https://www.arduino.cc/en/Tutorial/Button
  [2]: https://i.stack.imgur.com/VxP4Z.png


message:
How to set Alarms on the DS3231 easily so the Nano doesn't have to go to sleep with delay statements?

I want my solar array sun tracker to shut down at night then move full east in the morning to catch the first rays.

I know the DS3231 can set alarms but it is not clear from its documentation how to do it with the normal library.

Delay statements are the way I have it periodically check for when to take readings, but I really want it to be able to respond to radio-remote control commands, which don't work during delays.

Q:  Is there an easier way?

body:
Here it is:

https://github.com/sleemanj/DS3231_Simple

Example:  https://github.com/sleemanj/DS3231_Simple/blob/master/examples/z2_Alarms/Alarm/Alarm.ino

This is what I was looking for.

My system needs to be able to respond to radio remote commands while asleep, and the long delay() statements were preventing that.

These alarms solve the problem.


message:
Attiny45 resets when setting digitalOutput to low

I currently try to program an Attiny45 with an Arduino UNO as ISP.

The Arduino is able to program the Attiny45.

However, when I try the blink example, it resets the Attiny, when setting digitalOutput to low
(on any pin)

To further confirm, that it resets only, when setting a pin to low, I wrote this sketch and let it run on the Attiny.

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

    void loop() {
      delay(1000);
      digitalWrite(3, HIGH);
      delay(1000);
      digitalWrite(3, LOW);
      delay(10000);
      digitalWrite(3, HIGH);
      delay(1000);
      digitalWrite(3, LOW);
    }

The LED I connected to pin 3 waits 1 second, and then turns on, but when 1 second passed and it should stay off for 10 seconds, it resets and only waits 1 second.

I tried reburning the bootloader onto the Attiny, which had no effect.

body:
> Including the 220Ω resistor with the LED as in the last step?

...

> My LED can handle 5V, so I used it without, but that cant be the issue

The one thing that "can't be the issue" is indeed the issue! Without a resistor the LED will attempt to conduct a lot of current which will damage both it and the output pin of the processor.

See [The care and feeding of LEDs](http://www.thebox.myzen.co.uk/Tutorial/LEDs.html). From that page:

> LEDs are not like normally electronic devices in that you can’t just apply a voltage to them and they work, they have to be fed the correct voltage and current to keep them happy.

And then:

> There are several web sites and schematics on the web that suggest you can attach an LED directly to an Arduino output pin with no current limiting resistor. They are wrong, and following them will damage your Arduino.

---

So, by not using a resistor, when the output pin goes LOW it attempts to "sink" current, in order to turn on the LED. Since you have no resistor, it sinks as much as the output drivers can handle, dropping the supply voltage inside the Attiny, which then goes below the brownout level, and resets itself.

Please, when following a circuit, don't just omit bits of it, and then post a question about why it doesn't work. At least follow the circuit exactly, and then when you have learned more about electronics, you can start experimenting.


message:
Transistor Switching

I'm hoping that someone will be able to help me. I'm looking to produce a power interrupt for testing. I'm looking to have 28V DC input flowing to an output which I can hook up to a load and then switch on and off using an Arduino. I'm thinking of using an NPN high current transistor, I have built the box and code which runs fine. The issue I am having is the pin output on pin 13 doesn't have enough current to switch the transistor, can anyone recommend a transistor that would be able to take the high current and be switched by the Arduino? If you would like a schematic to help you understand it I can provide one!

Thanks for reading,
Lewis ![enter image description here](https://i.stack.imgur.com/qCifv.jpg)

body:
If you did manage to switch the transistor on, It would only output 4.3V, the rest would be dissipated in the transistor. If you managed to switch 4A this would dissipate 96W - and the transistor would melt.

A MOSFET would be a better option and could be easily switched by the Arduino. (I regularly switch 10A using a MOSFET and Arduino.)

This assumes you can put the MOSFET in the negative lead. If not you should use a P-Channel MOSFET, but you need a more complex circuit to drive it.

Have you considered using a relay module?


message:
Why is my arduino acting like a radio? And is there a way to abuse this?

I am playing around with an arduino and a cheap SDR dongle and I just noticed something strange!

When I play a tune on pin 13 with just a random piece of wire connected to the pin (Using the Melody example from the arduino page: http://www.arduino.cc/en/Tutorial/Melody)
I can pick it up as AM sound on my SDR on exactly 64Mhz even as far as 15meters away through walls with a little gain!!!

What magic is going on here and secondly and maybe most importantly would there be a relatively easy way to pick up the signal using just an arduino and cheapo components?

(Just for educational purposes of course, I know that there is better options depending on what I need to send)

[![64Mhz arduino tone library magic?][1]][1]

I would like any qualified guess as to what is going on, I am genuinely puzzled...

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

body:
I did something like that a while ago. Hardware:

[![Arduino as a radio][1]][1]

Code:

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

    const byte ANTENNA = 9;

    void setup()
      {
      // set up Timer 1
      TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
      TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaler
      OCR1A =  9;       // compare A register value to 10 (zero relative)
      }  // end of setup

    void loop()
      {
      pinMode (ANTENNA, OUTPUT);
      delay (500);
      pinMode (ANTENNA, INPUT);
      delay (300);
      }  // end of loop

The 16 MHz clock is divided by 10 (that is, 1.6 MHz) and that is used to toggle pin 9 at that rate, giving a frequency of 800 KHz, since one toggle turns the output on, and second toggle turns it off.

If you hold the Arduino near an AM radio tuned to around 800 KHz you should hear a hissing toggling on and off (like Morse code) as the carrier is turned on and off for 0.5 / 0.3 second intervals.

>  would there be a relatively easy way to pick up the signal using just an arduino and cheapo components?

I think you might find making a receiver a bit harder than a transmitter.

  [1]: https://i.stack.imgur.com/dNFcd.jpg


body:
I dont think Nick Gammon's answer actually explains clearly enough what is going on - he just made an example of how to do it. Since no-one else on this site has had a go at explaning it-I will-though Im no expert in arduino radio communications.

"What magic is going on here"

Its not magic -you are observing the principle of "electromagnetic induction" and the principle of "resonance".
Its not unique to arduino- basically an Antenna transmits information by making on and off power changes in the electrical current in the wire-as you are doing playing the melody. By the famous Maxwell equations this energy in the wire creates a corresponding invisible waves in the air. A well known circuit in electrical engineering (tank circuit or oscillator circuit) says that there is also a corresponding receiver circuit (which can be a radio) that will change the waves back into sound (by using the principle of electrical resonance).


message:
How do I change the I2C address on the LCD backpack?

The 20 x 4 LCD comes with a I2C backpack.  I know it has A0, A1, A2 to set the address, as shown at the bottom here:  https://tronixlabs.com.au/news/tutorial-serial-i2c-backpack-for-hd44780compatible-lcd-modules-with-arduino/

It points to here:  http://www.nxp.com/products/interface-and-connectivity/interface-and-system-management/i2c-bus-portfolio/i2c-general-purpose-i-o/remote-8-bit-i-o-expander-for-icbus-with-interrupt:PCF8574_74A

My unit shows up as 0x3F.

And even with all this information I can't tell how to change it.

I need to have a second display on the same I2C bus.

Question:  How do I change the address of the second one?

body: As mentioned in the page you linked, jumper together one of the address jumpers. For example, above A0 are two pads. Solder a wire across them (vertically - between the two pads above A0). I am guessing the address is pulled high by a resistor, so that will probably make the new address 0x3E, but you could run the I2C scanner to check that.


message:
How might the SD library be reading phantom files?

I have the Sparkfun CAN Bus shield with integrated SD card writer attached to an Arduino Mega 2560. I can delete a logged file from the SD card using Windows, log more data using the SD library, then look at the logged data in, say, Excel. The new log file will include the logged data from the old, deleted file.

The card is formatted in Windows in FAT32 and the logged file has the same name as the original. It seems like the SD card reader/SD library is able to 'recover' the deleted file by name, open it for writing having read its uncorrupted contents, and continue logging to it, despite it having been 'deleted' in Windows. I know a deleted file doesn't get rid of the data unless it is overwritten, but there seems to be some bug/oversight in how the SD library in card reader or how it interrogates the SD card or FAT32 volume for the existence of the file.

Has anyone come across this before? Is it a bug or am I doing something wrong?

body:
* How large is the file when it is deleted in Windows? I can imagine what you describe happening if there's a bug in the Arduino File System (see below) - but that requires relatively small files (less than 4K or so).
* I assume that the SD card has zero or more "static" files, that don't change; and then the log file, that grows. That is, when the log file is deleted, the newly-freed blocks get re-used again for the new log file?
* I also assume that you're using Windows' "Safe Removal" mechanism - giving it a chance to tidy up the SD Card before you yank it out.

To delete a file in FAT, the file system needs to do two steps:

1. Unlink the used blocks from the File Allocation Table (the eponymous F.A.T.).
  These should be set back to zero - making it hard to accidentally re-use them again unless they're the same blocks again (which, for SD Cards, is unlikely due to wear levelling!)
2. Mark the directory entry as available again.
  This is done by merely overwriting the first character of the directory entry with `0xE5`. When FAT needs a new directory entry, it will use entries with either `0x00` or `0xE5`. If the deleted file is being "resurrected", then a bug could be that it re-uses the directory entry _but doesn't zero the existing contents_, allowing the existing block number and length to be appended to.

Rather than deleting the file in Windows, try renaming it to something else entirely. That way the Arduino will create a new file, and you shouldn't have the problem. If you still do (worse: if the renamed file gets _corrupted_) then it's a caching problem. If you don't, then it's a bug in the file system.


message:
Interfacing Digital clock with Uno

I want to take input from a clock for a specific time and respond to it.

I am taking alarm as input because it will send some signal to a buzzer and I want to decode it through Arduino.

I am using Arduino Uno.

The program I used is as follows:

    int b = 0;

    void setup() {
        pinMode(8, INPUT);
        Serial.begin(9600);
    }

    void loop() {
        b=digitalRead(8);
        Serial.println(b);
        if(digitalRead(8) != 0)
        {
            Serial.println("input in 8");
        }
        else
            Serial.println("not");

        delay(500);
    }

I have removed the buzzer from the clock and connected the terminals to Arduino pin 8 and GND.

But the output is always random (i.e. 0 & 1), no matter if my alarm is on or off.

I cannot find if my program has a flaw or if my approach is just wrong.

body:
It is likely that the alarm clock does not provide any voltage level (I mean `GND`) to the  buzzer when it does not have to ring, the circuit is just left "open" then; it will provide a voltage level (depending on your clock power supply) only when the alarm has to ring.

On the other side, your Arduino pin 8 **must** have a voltage level that can be mapped to a `0` (anything between `GND` and `5V/3`) or a `1` (anything between `2x5V/3` and `5V`).

However, in the absence of alarm, the input is left "dangling" (no voltage level at all). In CMOS technology, leaving an input pin dangling will make it randomly take `0` and `1` levels as you described.

Fortunately, the solution to this problem should be easy: you just have to force a `0` level to pin 8, by connecting it to `GND` through a resistor. I generally use 10K or 15K for that resistor. This is called a "pulldown" resistor:

- when the alarm does not provide any voltage, the input pin level will be "pulled down" to `GND`, ie `0`.
- when the alarm provides a 5V (see important remark below) to the input pin, then it will be seen as `1`.

**IMPORTANT**: you have to make sure that your alarm clock, when ringing, provides a voltage that is not higher than 5V (it would grill your UNO, or more precisely the ATmega328 of your UNO) and is at least ~3V to be "recognized" as `1`.

**NOTE**: it is likely that solving this first issue will not be enough to make your complete program work, because your alarm clock probably does not send a continuous voltage to your buzzer but and alternate one to make it ring, hence you will get successive `1` and `0` at high speed (between 100Hz and 100Hz I would say) in your program. If that is the case please open another question as the solution for that specific issue is disconnected from the current one (random `1` and `0`).


message:
avrdude.conf: programmer type must be written as "id_type"?

I'm trying to compile & run using ino.

At the `ino upload` step I get the following error:

`avrdude: error at /usr/share/arduino/hardware/tools/avrdude.conf:332: programmer type must be written as "id_type"`

Relevant section of `avrdude.conf`:

```
programmer
  id    = "wiring";
  desc  = "Wiring";
  type  = wiring;   # line 332
;
```

I've seen various posts around the internet that suggest I just delete the config & refresh it, but I'd like to find the correct syntax and actually understand & fix the issue.

body:
After looking at the [source repo](http://svn.savannah.nongnu.org/viewvc/trunk/avrdude/avrdude.conf.in?root=avrdude&view=markup) it looks like quotes are now required:

```
  type  = "wiring";
```


message:
Why is my switch not working?

I'm trying to have a common light switch turn a LED on and off.

When I connect the light switch directly to a LED, it works like it should - the LED turns on and off with the switch.

When I connect the light switch back to the board, changing the switch does nothing - I get the exact same signals regardless of whether the switch is on or off.

Why?
How do I make the board recognize whether the switch is on or off?

[![Circuit][1]][1]

The diagram I followed:
[![https://i.stack.imgur.com/pIoMd.png][2]][2]

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

    const int  buttonPin = 2;

    const int ledUt = 13;
    const int ledTest = 12;
    int buttonPushCounter = 0;
    int buttonState = 0;
    int lastButtonState = 0;

    int tilstand = 0;

    int buttonStateForrigeForrige = 0;

    boolean light = false;

    void setup() {
      Serial.println("Hello World");
      Serial.begin(9600);
      pinMode(buttonPin, INPUT);
      pinMode(ledUt, OUTPUT);
      pinMode(ledTest, OUTPUT);

    }

    void loop() {

      digitalWrite(ledTest, HIGH);
      buttonState = digitalRead(buttonPin);
      Serial.println("Sjekk");

      tilstand = LOW;
      if ( buttonState == HIGH ) {
        Serial.println("buttonState HIGH");
        if ( lastButtonState == HIGH ) {
          Serial.println("lastButtonState HIGH");
          tilstand = HIGH;
        } else {
          Serial.println("lastButtonState LOW");
        }
      } else {
        Serial.println("buttonState LOW");
      }

      if (buttonState != lastButtonState) {

        if (buttonState == HIGH) {
          buttonPushCounter++;
          Serial.println("on");
          Serial.println(buttonPushCounter);
        } else {
          Serial.println("off");
        }
      }
      buttonStateForrigeForrige = lastButtonState;
      lastButtonState = buttonState;

      if (tilstand == HIGH) {
        digitalWrite(ledUt, HIGH);
      } else {
        digitalWrite(ledUt, LOW);
      }
      }

  [1]: https://i.stack.imgur.com/24KIU.png
  [2]: https://i.stack.imgur.com/pIoMd.png

body:
See [my page about switches](http://www.gammon.com.au/switches). Judging by your very-hard-to-read diagram, you have just connected the switch to an input pin like this:

[![Switch with floating input][1]][1]

---

That will not give a positive reading either way because it is "floating". You should connect a pull-up or pull-down resistor, like this:

[![Pull-up resistor][2]][2]

Now if the switch is open, it is pulled-up to 5V by the resistor and the input will read `HIGH`. When the switch is closed the switch conducts and "overpowers" the resistor, and it would read `LOW`.

---

An alternative is to use a pull-down resistor like this:

[![Pull-down resistor][3]][3]

That reverses the sense of the switch. When open it will read `LOW` and when closed it will read `HIGH`.

---

I hope you have a resistor in series with the LED.

  [1]: https://i.stack.imgur.com/agJ26.png
  [2]: https://i.stack.imgur.com/pIoMd.png
  [3]: https://i.stack.imgur.com/JZ0wZ.png


body: You can also use `pinMode(buttonPin, INPUT_PULLUP);` instead of `pinMode(buttonPin, INPUT);` in that case the arduino "activates" an internal pull-up resistor.


message:
Problems building an Arduino Micro with through-hole components

So I'm trying to build an Arduino Micro using a bread-board and through-hole components. I'm leaving out the voltage regulator and voltage selector (see schematic at the bottom for reference). I'm powering off of USB, so the `+5V` line is connected to `VUSB`.

I checked over the circuit many times, so I think it's okay. Below is a picture of me trying to use an Arduino Micro to load the bootloader on to the Atmega32U4:

![Arduino Micro circuit](https://i.stack.imgur.com/hGhXd.jpg)

I looked [here](https://learn.sparkfun.com/tutorials/installing-an-arduino-bootloader) and [here](http://murchlabs.com/monday-experiment-bootloading-an-atmega32u4-with-arduino/) as references for trying to load the bootloader, but every time I try it gives me an error. It seems like the MCU is not being recognized. Has anyone tried this before, and successfully done it? I'd like some pointers as to how to achieve this.

EDIT: I've moved the crystal (and 22 pF cap's) closer to pins 16 and 17. The steps I take are:

1. Upload "ArduinoISP" sketch to Arduino Micro (the "programmer").
2. Select "Arduino Micro" as the board to be programmed.
3. Select "Arduino as ISP (Atmega32U4)" as the programmer.
4. Burn bootloader.

Here is the verbose output (compilation and upload):

    Arduino: 1.6.12 (Windows 7), Board: "Arduino/Genuino Micro"

    C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega32u4 -carduino -PCOM5 -b19200 -e -Ulock:w:0x3F:m -Uefuse:w:0xcb:m -Uhfuse:w:0xd8:m -Ulfuse:w:0xff:m

    avrdude: Version 6.3, compiled on Sep 12 2016 at 17:24:16
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

             Using Port                    : COM5
             Using Programmer              : arduino
             Overriding Baud Rate          : 19200
             AVR Part                      : ATmega32U4
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PA0
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
               lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : Arduino
             Description     : Arduino
             Hardware Version: 2
             Firmware Version: 1.18
             Topcard         : Unknown
             Vtarget         : 0.0 V
             Varef           : 0.0 V
             Oscillator      : Off
             SCK period      : 0.1 us

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.00s

    avrdude: Device signature = 0xffffff (probably .reduced_core_tiny) (retrying)

    Reading | ################################################## | 100% 0.00s

    avrdude: Device signature = 0xffffff (probably .reduced_core_tiny) (retrying)

    Error while burning bootloader.
    Reading | ################################################## | 100% 0.00s

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

    avrdude done.  Thank you.

![Arduino Micro schematic](https://i.stack.imgur.com/UPtbA.jpg)

body:
>I select "ArduinoISP" as the programmer. I press "Burn Bootloader". I get the following: avrdude: Error: Could not find USBtiny device (0x2341/0x49) Error while burning bootaloader.

You need to select **Arduino as ISP** from the **Tools > Programmer** menu. [ArduinoISP](https://www.arduino.cc/en/Main/ArduinoISP) is a dedicated in system programmer made by Arduino, confusing because the name of the sketch used with Arduino as ISP is ArduinoISP.

If you're using Windows you'll also likely encounter the issue that ATmega32U4 based boards can't be used for Arduino as ISP. The cause of this is explained at https://petervanhoyweghen.wordpress.com/2012/09/16/arduinoisp-on-the-leonardo as well as a solution. Unfortunately the solution described in that blog post no longer works as-is with recent versions of the Arduino IDE. I have updated the solution to work with recent Arduino IDE versions and added support for installation via Boards Manager here:
https://github.com/per1234/ATmega32U4asISP


message:
NeoPixel setPixelColor works only in for loop

I am working with a NeoPixel RGB led and have gone through various tutorials but I have a question regarding the `setPixelColor()`.

If I do not have my `setPixelColor()` and `show()` inside of a `for` loop it will not work.

This works:

    void holoLight(uint32_t c){
      for(uint16_t i = 0; i<2; i++){
        holo_pxl.setPixelColor(i, c);
        holo_pxl.show();
        delay(2500);
      }
    }

This does not:

    void holoLight(uint32_t c){
        holo_pxl.setPixelColor(1, c);
        holo_pxl.show();
        delay(2500);
    }

I am sure it is something specific to the language or execution but would love some clarifications, thanks =)

body:
I am not sure I fully understand your exact problem but you have to be aware that `holo_pxl.setPixelColor(1, c);` set the color of the **second** LED in a NeoPixel chain, **NOT the first one**.

For the first LED, you have to use `holo_pxl.setPixelColor(0, c);` instead.


message:
What options do I have to wirelessly connect my computer to an arduino?

For my project I have an arduino Uno connected to my robot. I need to control it wirelessly. I have thought of using a bluetooth module , but I need a larger range. Then I thought of using an RF-module like the Xbees and the 2.4 Ghz nRF24L01. However I can't use the Xbees due to budget issues. As for the nRF24L01- I understand that using the trasmitter and receiver modules I can transmit information between 2 arduinos- however I need to transmit from my computer to my remote arduino. I want to achieve this without using a second arduino at the transmitting (computer) end. Is there a way to achieve this?

body:
It is also not very cheap, but you can easy use [wifi shield][1]. The one I sent you is from arduino, but there are chinese analogs which are cheaper. You can use them either to connect your arduino to computer or to connect it to the other devices. Have fun!

  [1]: https://www.arduino.cc/en/Main/ArduinoWiFiShield


body:
How about using wifi?
The esp8266 costs as low as 3$ and has good range.
[here's a quick tutorial][1]
What you'll need to do is send a command to the esp8266 and in turn it'll communicate with the arduino via Serial (or Software Serial) and tell it what to do.

  [1]: https://www.google.com/amp/www.instructables.com/id/ESP8266-Wifi-Tutorial/?amp_page=true


message:
How to connect an RF module directly to a PC without using an arduino?

I know that in xbees i can connect the xbee module directly to my pc using the USB explorer. But I'm using the nRF24L01 RF modules. I want to transmit from my pc, via the RF transmitter to my RF receiver, which is connected to my arduino. How do I connect this RF module directly to my PC?

body:
The nRF24L01+ uses SPI. PCs don't (usually) have an SPI interface. So you will need some piece of hardware to provide the PC with an SPI interface.

That could be an Arduino, or it could be a dedicated SPI dongle, such as one based around the FT2232 chip.

Of course, you then would need to write software to use that SPI interface and work with the nRF24L01+ connected to it, including using the same message format / packet system, which won't be a simple task. So you may be better off just using a small Arduino to do the communication and present you with a simple serial interface for sending / receiving messages. That way you can then use the same nRF24L01+ software that you are using elsewhere in your setup.


message:
How to animate a LED Strip via wifi?

I'm remotely connecting my phone to an arduino MKR1000 via wifi, and sending data via HTTP GET (so to switch on the debug LED, I just need to navigate to http://192.168.1.1/debug/H, for example). Now, I want to be able to remotely send animations to an RGBW led strip.

Ideally, I would have a simple keyframe based protocol such as:
    http://192.168.1.1/anim/(keytime in ms):R,G,B,W+(keytimeinms) etc...

So for example, to animate from white to red in 500ms, I would navigate to:
    http://192.168.1.1/anim/0:255,255,255,255+500:255,0,0,0

Is this the best way to remotely send animations to my arduino? How should I implement this on the arduino side in the most ressource-efficient way possible? I don't even know where to start :/
For the moment, on the arduino side, I've got a keyframe class and an array of those keyframes representing the animation.

body:
Ignacio's comment, “Start with something. Worry about making it efficient after you've figured out how to make it at all”, is good advice.

Note, to make the transition from one keyframe to another more efficient, use a variant of the [Bresenham algorithm](https://en.wikipedia.org/wiki/Bresenham's_line_algorithm).  This allows use of fast integer arithmetic and is intrinsically accurate.  Instead of error accumulating and getting steadily worse (as will happen if you add constant increments), the Bresenham algorithm tracks error and minimizes it.  See, for example, “[Simplified Bresenham's line algorithm: What does it *exactly* do?](https://stackoverflow.com/a/8113883/837847)”.

----------

This edit addresses Paul's question about accumulating error:
>I've added a note to my answer, in which I try to battle the accumulation of error, could you check if my assumption (that the last implementation doesn't accumulate the error) is right?

There can be several sources of error, including accumulation of round-off error; arithmetic overflow errors; time-base errors; and silly errors [it's always easier to poke holes in other people's code!].

To illustrate those error sources and a possible solution, consider the following code snippet:

     0   unsigned long int startTime = millis();
     1.  unsigned int totalTime = 3000, nSteps = 100;
     2.  int msPerStep = round(totalTime/nSteps);
     3.  byte startRed = 100, startGreen = 28, startBlue= 50;
     4.  int deltaRed   = endRed   - startRed;
     5.  int deltaGreen = endGreen - startGreen;
     6.  int deltaBlue  = endBlue  - startBlue;
     7.  byte nowRed=startRed, nowGreen=startGreen, nowBlue=startBlue;
     8.  for(int step= 0; step < nSteps; step++){
     9.     analogWrite(RPin, nowRed   += deltaRed/step);
    10.     analogWrite(GPin, nowGreen += deltaGreen/nSteps);
    11.     nowBlue = startBlue + (deltaBlue/amountOfSteps)*step;
    12.     analogWrite(BPin, nowBlue);
    13.     long int elapsed = millis()-startTime;
    14.     analogWrite(RPin, startRed + (deltaRed*elapsed)/totalTime);
    15.     delay(msPerStep);
    16.  }

First, consider `currentRed += deltaRed/step` expression in line 9.  In the first loop pass it adds an undefined quantity, `deltaRed/0`, to `nowRed`; in the next, it adds `deltaRed/1` to `nowRed`; then `deltaRed/2`; and so forth.

Line 10 corrects the silly error of dividing by `step` instead of `nSteps`.  But there can be significant accumulation of round-off error.  For example, if `deltaGreen` is 199 and `nSteps` is 100, it repeatedly adds 1 instead of 1.99, and ends up with the Green level 99 counts short of being correct.

Line 11 attempts to compensate for that problem by adding a step-proportional amount of `deltaBlue` to `startBlue` at each step.  However, due to the parenthesized order of arithmetic it has exactly the same round-off error problem as line 10 – it adds exactly one unit per step for my example numbers.  To try to avoid this problem, one might write `(deltaBlue*step)/amountOfSteps` in place of `(deltaBlue/amountOfSteps)*step`.  This will do accurate arithmetic except can easily overflow an `int` so should perhaps be written instead as `(deltaBlue*(long int)step)/amountOfSteps`.

Even if line 11 is rewritten to avoid truncation, round-off, and overflow errors, it still is subject to time-base errors.  Like the color numbers, the `delay()` parameter `msPerStep` is subject to accumulation of round-off errors.  During the `for` loop, several hundred milliseconds of error could accumulate, leading to mismatched or jittery color levels.  To avoid that error, instead measure elapsed time (as in line 13) and make color levels proportional to elapsed time (as in line 14).  In addition, one probably should change the `for` loop to a `do { ... } while (elapsed < totalTime)` loop, ie, let the loop run until the right time has passed, rather than some arbitrary number of passes.


body:
*I'm not sure what you have working or what you haven't.
I'm also not sure what you've tried and which problems occured.
However, I'd like to give you atleast a basic answer before I vote for: "Too broad".*

It's actually quite simple (but you can make it difficult).

**Step 1**

Imagine the effect, what are you actually trying to achieve? Fade out the current color and fade in a new one? Or are you trying to shift the color from one to another?

**Step 2**

Find resources online.
You're likely not the first person to have tried this ;D
https://www.arduino.cc/en/Tutorial/ColorCrossfader

**Step 3**

Iteratively and rationally develop your project.
Know what you have and what you need.

You've got these parameters:

 - Current R/G/B values.
 - R/G/B values you wish to shift/fade to.
 - Duration of the fading effect (total time of the animation, total amount of frames for the animation)

Your goal:

Is making an "animation". Changing the colors over time, as an fading effect.

We will simplyfy it by starting with only the R (red) channel, we can add the rest later.

Let's say we want to fade from 100 to 255 in 3 seconds.
We're going to have 155 different levels of brightness over 3 seconds.
Which is roughly 20ms per step.

    for(currentRed; currentRed < setRed; currentRed++){
       analogWrite(redPin,currentRed);
       delay(msPerStep);
    }

But that won't really work for multiple channels...
Just add another channel and find your way out that challenge.
(I added blue, but you could add up to x amount with this code I believe)

    unsigned char currentRed = 100;
    unsigned char currentBlue = 50;
    unsigned char setRed  = 255;
    unsigned char setBlue = 255;
    int differenceRed  = setRed  - currentRed;
    int differenceBlue = setBlue - currentBlue;
    unsigned int totalTime = 3000; //3sec (in ms)
    unsigned int amountOfSteps = 100;
    int msPerStep = round(totalTime/amountOfSteps);

    for(unsigned int step= 0; step < amountOfSteps; step++){
       analogWrite(redPin, currentRed  += differenceRed/step);//We could optionally calculate the difference per step beforehand, to avoid having doing dividing in a loop (may be a tad inefficient this way).
       analogWrite(bluePin,currentBlue += differenceBlue/step);//But well, in the delay you're also just wasting CPU, so who cares? :)
       delay(msPerStep);
    }
    currentRed = setRed;//Compensate for rounding step values
    currentBlue=setBlue;//You may want update the analog pins, though I presume it would be barely visible to a person.

You could get rid of the blocking delay, but well, that's beyond the scope of this answer.

I haven't tested the code, nor the algorithm extensively.
You may check what happens if the setpoint is lower as the current value.

So now you can test the algorithm, finetune/adapt it to your liking and make a function out of it :)

----------

----------

As noted by jwpat7, combining floating point math and integers on Arduino will have quite an error in it. And if you keep applying the same error each step, it will accumulate.

I'm not sure how significant it will be for LED applications, you usually can't see the difference between a few "levels" of brightness.

I've made my own implementation of which I think may battle this problem:

    unsigned char previousRed = 100;
 unsigned char previousBlue= 50;
 unsigned char currentRed = previousRed;
    unsigned char currentBlue = previousBlue;
    unsigned char setRed  = 255;
    unsigned char setBlue = 255;
    unsigned int totalTime = 3000; //3sec (in ms)
    unsigned int amountOfSteps = 100;
    int msPerStep = round(totalTime/amountOfSteps);

    for(unsigned int step= 0; step < amountOfSteps; step++){
  currentRed = previousRed + ((setRed-previousRed)/amountOfSteps)*step;
  currentBlue = previousBlue + ((setBlue-previousBlue)/amountOfSteps)*step;
  analogWrite(redPin, currentRed);
  analogWrite(bluePin,currentBlue);
  delay(msPerStep);//If the algorithm is inefficient, you COULD compensate for it by lowering the msPerStep.
    }
 currentRed=setRed;
 currentBlue=setBlue;

I believe that, by completely recalculating it every step, the error won't accumulate.

This, however, may be a lot more inefficient than what jwpat7 describes. But atleast it's easy to understand.
Since you're throwing most of the cycles away by waiting for the next frame and can barely see the difference between "100 and 102" intensity from PWM, I think it's a viabale option.


message:
Can the EWRF 3022 module be directly connected to the pc totransmit data from the pc wirelessly?

In my project I want to connect my pc to an RF transmitter. The receiver will be connected to an arduino on my robot. However most of the RF modules I looked up couldn't be directly connected to my computer- in all of them I needed to use an arduino on the transmitter end too. Then I came across this:

> [ EWRF 3022][1]

  [1]: http://www.swechtrading.se/zencart/images/datablad/ewrf3022ut.pdf
Can this be directly connected to my computer? If so, how is it done?

body:
If you use a USB to TTL UART adapter, such as an FT232 dongle, then yes you can communicate to it from a PC.

It will not directly connect to a PC though without you getting that extra hardware.


message:
Binary message formatter

I am currently developing an IoT device with arduino and i want to minimise the data payload. First i used json which is not very efficent in fixed messages (the format will always be the same). Then i found something like messagepack which also sounds nice but i think you could do even better with just binary. I hope to find something like that:

I have a message for example:

    #BOOL#INT#INT#FLOAT#BOOL#STRING#

The position of this variables never change so i could represent the message in binary and i could save a lot of bytes. Is there any library which can de/encode such formats and generate messages from given values?

If not i think it would be very useful in further IoT devices!

body: No such library is needed, since basic C++ can handle this on its own. Create a packed struct with the fields, fill the fields with assignment or memory copying, and cast to a `char*` in order to send. Reverse the order of operations in order to receive. Beware the string though, since they need to/should specify a length somewhere.


body:
Passing messages across computers and/or microcontrollers with different architectures can be a real pain ([endianness](https://en.wikipedia.org/wiki/Endianness)...). So do not fall into [NIH](https://en.wikipedia.org/wiki/Not_invented_here) / [reinventing the wheel](https://en.wikipedia.org/wiki/Reinventing_the_wheel) traps but keep standing on the shoulders of giants! Several message [serialization](https://en.wikipedia.org/wiki/Serialization) protocols exist.

- [BSON](https://en.wikipedia.org/wiki/BSON)
- [MessagePack](https://en.wikipedia.org/wiki/MessagePack)
- [Protocol Buffers](https://en.wikipedia.org/wiki/Protocol_Buffers)
- [CBOR (Concise Binary Object Representation)](https://en.wikipedia.org/wiki/CBOR)
- ...

Several implementations of such protocols exist (even for Arduino).

I suggest to have a look in a search engine for such protocols and add `Arduino`.

I've found:

- BSON
  - [ardubson](https://github.com/argandas/ardubson)
- MessagePack
  - [msgpack-mcu](https://github.com/hasegaw/msgpack-mcu)
  - [arduino_msgpack](https://github.com/HEADS-project/arduino_msgpack)
  - [MsgPacketizer](https://github.com/hideakitai/MsgPacketizer)
  - [msgpack-arduino](https://github.com/elliotwoods/msgpack-arduino)
  - ArduinoJSON [serializeMsgPack](https://arduinojson.org/v6/api/msgpack/serializemsgpack/) / [deserializeMsgPack](https://arduinojson.org/v6/api/msgpack/deserializemsgpack/)
- Protocol Buffers
  - [nanopb](https://github.com/nanopb/nanopb)
- CBOR
  - [Arduino-Cbor](https://github.com/jjtara/Library-Arduino-Cbor/)
- ...

PS: You might read https://scottlocklin.wordpress.com/2017/04/02/please-stop-writing-new-serialization-protocols/
and have a look at https://xkcd.com/927/
Just choose a giant compatible with your requirements ;-)

https://en.wikipedia.org/wiki/Comparison_of_data_serialization_formats may help


body:
use a struct organize the data and when transmit the struct, use a char pointer pointing to it so everything is sent in binary format.

you will need to come up with a way to determine when the pointer ends.


body:
A good choice to send sensor data is **CayenneLPP**. LPP stands for **"Low Power Payload"**. It is a sensor type aware encoding that uses as few bytes as possible.

A key feature is that recipient must not be aware of content as it is encoded into message, so you can build a generic gateway using that.

You can read more about CayenneLPP here: https://developers.mydevices.com/cayenne/docs/lora/#lora-cayenne-low-power-payload

It is recommended for using it on TTN to minimize payload weigth.

There is an Arduino library for enconding and decoding. For decoding it outputs JSON object so it is ready to be used in platforms like NodeRed or any python or web based application.

Check it here: https://github.com/ElectronicCats/CayenneLPP


message:
RFID Reader ID12-LA reads every card as ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ

My new RFID reader ID12-LA by SparkFun can recognise an RFID tag, but it can't read its tag number - the Arduino IDE outputs the tag as ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ

Any help on how to convert this into a proper ID would be much appreciated - btw I have tried other baud rates; no difference.

Thanks, Raihaan

Edit - the code I'm using is this:

    #include <SoftwareSerial.h>

    SoftwareSerial rSerial(4,5);

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

    void loop() {
        if (rSerial.available() > 0) {
            int b = rSerial.read();
            Serial.print(b);
            Serial.print(" ");
        }
    }

This now returns `255` 6 times... Any ideas?

Schematic:

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

  [1]: https://i.stack.imgur.com/jXhIP.jpg

body:
If you have one of the regular Arduino models, the hardware UART is connected to pins 0 and 1, which are also used by the USB programmer and in your case obviously your serial monitor, on which you expect to see some output.

Configuring a SoftwareSerial on pins 0 and 1 is probably not going to work at all. If you need the USB programmer to stay connected and the serial monitor for debugging, you have to use different I/O pins and setup your SoftwareSerial accordingly.

I assume that you are aware that the ID12-LA chip only works on the 125 kHz band and is incompatible with common tags running on 13.56 MHz?


body: You created a `SoftwareSerial` connection to read from the module and then you're printing what you just read *to the same module*. You probably want to print to the serial monitor on your PC. You should add `Serial.begin(9600);` to your `setup()` and ensure that all `print()`s are to `Serial` and not `rSerial()`.


message:
Aptotec PN532 shield power consumption

I am currently planning a battery-powered project, where one of the tasks involves reading Desfire EV1 tags. Since the cheap RC522 based NFC shields are reported not to work with the Desfire EV1 tags, I wanted to make an attempt with a PN532 based shield. Due to offering the fastest shipping option, I ordered an [Aptotec PN532 shield][1], although there are many other, and likely cheaper options out there as well. The Aptotec shield seems identical to the [Seeed NFC Shield V2.0][2].

Communicating with the Desfire EV1 tags works as expected, but I am not understanding the shield's power consumption. If I understand the PN532 datasheet correctly, the chip itself should only draw 45µA when in standby mode, some 30mA when active, but not transmitting and additionally up to 150mA more during actual transmission.

After sending an 'InRelease all targets' command to the PN532, the shield however still draws about 50mA, although the PN532 should be in stand by mode. Using the RFConfiguration command to turn the RF field off completely still does not decrease the shield's power consumption. Activating the RF field e.g. by issuing an InListPassiveTarget command, the current draw increases to about 80mA, which matches with my assumption that the PN532 now draws 30mA more than when idle. There seems however to be something else on the shield causing a 'base line' 50mA current draw, which is not caused by powering the PN532 chip.

Does someone know where this power is lost, if it is possible to software-based turn off whatever is causing the power draw or if other PN532 shields show the same behaviour? Since my project must run on a battery, the 50mA unexplained current draw is not acceptable.

  [1]: http://aptotec.de/NFC-Shield
  [2]: http://wiki.seeed.cc/NFC_Shield_V2.0/

body:
After some trial and error, I think I can answer this one myself.

The circuit schematic from the Seeed module is actually broken and the Apotec model is built almost identically. The PN532 chip has an SVDD *output* pin to power an optional security access module for cryptography support. In the Seeed design, this pin is connected to the 3.3V input voltage from the voltage regulator, which is simply wrong and the pin sinks an essential amount of current.


message:
What is a cheap way to interface a USB keyboard to an Arduino Uno?

What is the cheapest way to interface a USB 2.0 keyboard to an Arduino Uno?

The keyboard does not support PS/2 emulation (interfacing a PS/2 keyboard to Arduino is easy). So this means the Arduino will read the USB keyboard's keystrokes - whatever their speed of input is.

If it can be solved using an IC then DIP is preferred as it quicker to work  with for soldering and pluggin into breadboard.

body:
The cheapest way is to get a plain PS/2 (or PS/2-USB convertible) keyboard instead of USB1.1 (I hope you mean the standard LS keyboard, since USB2.0 HS keyboards hardly exist), and interface it to GPIOs in accord with known solutions.

The Arduino Uno is designed around Atmega8u2 and ATmega328P chips, which can act as USB device only, FS and LS. To interface it with a dedicated USB keyboard (which is a USB device), the you need to have the Arduino **as a USB host**. Probably it is possible to emulate some limited hardware host functionality for LS mode (1.5Mbps) over GPIOs, but it will be a remarkable effort.


message:
Arduino Uno and ESP8266 serial monitor issue

I plugged in the Arduino Uno and the ESP8266 following this schema:

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

When I enter "AT" in the serial monitor, I get an "OK". I can also connect to my wifi using typical ESP8266 commands.

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

What doesn't work is passing these commands using an Arduino Script. For example, if I use this script, I don't get an "OK" from the ESP8266.

    void setup() {
      // put your setup code here, to run once:
    Serial.begin(9600);
    }

     void loop() {
      // put your main code here, to run repeatedly:
     Serial.println("AT");
     delay(10000);
       if(Serial.find("OK")){
        Serial.println("OK");
         }
         else{
         Serial.println("NOT OK");
      }
    }

I tried a bunch of different codes,and nothing works. What am I doing wrong?

  [1]: https://i.stack.imgur.com/2ibjr.png
  [2]: https://i.stack.imgur.com/c8l48.png

body:
What you are doing wrong is:

If sending AT commands from PC to ESP and receiving `OK` ,as you said, works - that means you connected TX output from USB --> RS232 IC on the board to **both** RX pin of the ATmega328 and RX pin of the ESP8266 - **not as in your picture**. Similarly, you connected RX input of the USB --> RS232 IC on the board to **both** ATmega328 TX and ESP8266 TX pin of the ESP8266. If communication between PC and ESP works, then you connected TX Arduino pin with TX ESP pin and RX Arduino pin with RX ESP pin and **not** as shown in the picture.

When you send AT command from PC both ATmega328 and ESP8266 are getting the signal from USB --> RS232 IC in their RX pins. As your firmware in the first 10 seconds doesn't read the RS232 data, ATmega328 just ignores the packets sent by PC but ESP8266 receives the packets and responds with `OK`.

Since you shorted RX on ATmega328 and RX on ESP8266 and you shorted TX on ATmega328 and RX on ESP8266, ATmega328 can **not** send the data to ESP and vice versa so there is no `OK`.

In the other case, **if** you connected ATmega328 TX with ESP8266 RX and ATmega328 RX with ESP8266 TX (**as shown in the picture**) then you would have shorted USB --> RS232 IC's TX with ESP's TX and you would have shorted USB --> RS232 IC's RX with ESP's RX.

In that case ATmega328 **might** be able to send `AT` command to both ESP and PC at the same time and ESP would respond but now ESP's TX would be connected to ATmega's RX which is now shorted with USB --> RS232 IC's TX so PC can't receive that packet. However, when ATmega328 responds with `OK`, the signal now goes from ATmega328 TX to USB --> RS232 IC's RX (as always) and you might see the response in serial terminal.

So, you can't get the ESP to respond directly to PC **and** to ATmega328 without interchanging the TX/RX wires. Furthermore, as you may know RS232 is designed for communication between **two** devices, not three - and this is the case where three devices (USB --> RS232 IC, ATmega328 and ESP8266) are connected to the same TX/RX pins at the same time in a rather unusual way. Because, devices are usually connected TX to RX and RX to TX. However, when using the Arduino's onboard USB --> RS232 converter (by removing the microcontroller or holding it under reset) then you have to connect TX to TX and RX to RX. That is because there is one more TX/RX pair in between PC and the RX/TX pins on the board. The output of the USB --> RS232 converter (TX) sends the data to RX pin on ATmega328 (and RX pin on the board) but if you want to send the signal further (to some other device), then the pin marked with RX is going to act as TX.

To summarize:

1. The schematics does **not** correspond to what you have written. Such a connection would not allow to send the AT commands from the PC to ESP and to receive response, meaning you connected the TX/RX the other way round.
2. You can not have both at the same time. You have to decide whether you want to send AT commands from the PC or from microcontroller and then connect the wires accordingly.


message:
very lightweight low power microcontroller with memory?

I have build a couple of projects using arduino.  For a new project I want to log skin surface temperature vs. time (just perhaps a few times per day) and possibly other easy to obtain info such as voltage.

I need to make everything as small and lightweight as possible (since it would be measuring skin temperature on a small mammal), i.e. below 5g, lighter if possible, ideally 3g, including the battery, so that it doesn't upset the 50-100g animal too much.

I read it might be possible to change the arduino pro mini to use less current by getting rid of the voltage regulator? but perhaps it is more sensible to change completely and learn to program another type of microcontroller which someone could recommend? It would need to be possible to operate it directly from a lightweight coin cell or similar lightweight battery. (I'm also not sure how to find a lightweight 3.3V battery for the arduino pro mini, I guess they exist but I can only find 3V batteries so far). If it has onboard memory to save temperature every few hours which could be downloaded later that would be ideal (I would also be interested if anyone has recommendations for memory). I know it's possible to buy an "Ibutton" but if I have time I would like to make my own so that I can add other sensors and obtain more information.

body:
I would personnaly suggest an ATtiny 45/85. It is pretty much a small AVR with 5 GPIOs. You can program it with the Arduino IDE and use the Arduino as ISP. If you can design you own custom PCB, a SMD version of the ATtiny is small, low and compact. The total circuit to make the ATtiny function is also minimal.

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

Also, at a low clock speed (0-4MHz), you can power the ATtiny at a voltage as low as 1.8V. You could probably even run it at 1.5V, but this is not totally recommended. If you want to be safe, a 3V coin cell will be small, flat, and it can last probably many years. It is also a little safer compared to lipos which have many risk, especially if you mount it on an animal that you can't really control.

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

I would also recommend SMD components if possible. It lets all the component be lower and it doesn't hurt or sratch the skin of the person/animal you are monitoring.

  [1]: https://i.stack.imgur.com/mITEX.png
  [2]: https://i.stack.imgur.com/iCzg1.png


body:
I made up a small [torch locator](http://www.gammon.com.au/forum/?id=12769) which used an ATtiny85 powered from a button-cell (CR2032). It looks like this:

[![Torch locator][1]][1]

Other side:

[![Other side][2]][2]

That currently weighs 5.9g. The battery-holder weighs 1.6g so you could save that by making a more light-weight holder (perhaps a bit of plastic for insulation, and soldering directly to the battery). The chip socket weighs at least 0.5g, so you could save that as well by soldering to the processor pins. So we are down to 3.8g.

The ATtiny85 has 512 bytes of EEPROM which you could use to log readings to. I'm not sure about a clock if you are trying to save weight, but if you start it at a known time, you could have a reasonable estimate of the time by using the `millis()` function to find miliiseconds since startup.

I made another one a while ago which flashes an LED every couple of seconds:

[![LED flasher][3]][3]

That is similar. The processor is there (upside down under the chip socket) and the battery is underneath. That weighs 6g. The battery has lasted a couple of years, and that is flashing an LED every couple of seconds!

Instead of the LED you could have a thermistor to read the temperature.

You could program it to take a reading every few hours and save it to EEPROM. Then when instructed (eg. by joining a couple of pins) it could output the readings to another pin (via serial).

You could save more weight by using SMD (surface mounted) devices, and perhaps using a tiny circuit board you could get made up.

---

## Code

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

The code for my torch locator is below. Of interest is the fact that it sleeps most of the time. Also it sleeps during the ADC sampling. Although in my case I am measuring a LDR (light dependent resistor) the code for measuring a thermistor would be similar. You just need to do some calculations at the end to turn the reading into a temperature.

    // ATtiny85 torch detector
    // Author: Nick Gammon
    // Date: 25 February 2015

    // ATMEL ATTINY 25/45/85 / ARDUINO
    // Pin 1 is /RESET
    //
    //                  +-\/-+
    // Ain0 (D 5) PB5  1|    |8  Vcc
    // Ain3 (D 3) PB3  2|    |7  PB2 (D 2) Ain1
    // Ain2 (D 4) PB4  3|    |6  PB1 (D 1) pwm1
    //            GND  4|    |5  PB0 (D 0) pwm0
    //                  +----+

    /*

      Pin 2 (PB3) <-- LDR (GL5539) --> Pin 7 (PB2) <----> 56 k <----> Gnd

      Pin 5 (PB0) <---- LED ---> 100 R <-----> Gnd

    */

    #include <avr/sleep.h>    // Sleep Modes
    #include <avr/power.h>    // Power management
    #include <avr/wdt.h>      // Watchdog timer

    const byte LED = 0;          // pin 5
    const byte LDR_ENABLE = 3;   // pin 2
    const byte LDR_READ = 1;     // Ain1 (PB2) pin 7
    const int LIGHT_THRESHOLD = 200;  // Flash LED when darker than this

     // when ADC completed, take an interrupt
    EMPTY_INTERRUPT (ADC_vect);

    // Take an ADC reading in sleep mode (ADC)
    float getReading (byte port)
      {
      power_adc_enable() ;
      ADCSRA = bit (ADEN) | bit (ADIF);  // enable ADC, turn off any pending interrupt

      // set a2d prescale factor to 128
      // 8 MHz / 128 = 62.5 KHz, inside the desired 50-200 KHz range.

      ADCSRA |= bit (ADPS0) | bit (ADPS1) | bit (ADPS2);

      if (port >= A0)
        port -= A0;

    #if defined(__AVR_ATtiny85__)
      ADMUX = (port & 0x07);  // AVcc
    #else
      ADMUX = bit (REFS0) | (port & 0x07);  // AVcc
    #endif

      noInterrupts ();
      set_sleep_mode (SLEEP_MODE_ADC);    // sleep during sample
      sleep_enable();

      // start the conversion
      ADCSRA |= bit (ADSC) | bit (ADIE);
      interrupts ();
      sleep_cpu ();
      sleep_disable ();

      // reading should be done, but better make sure
      // maybe the timer interrupt fired

      // ADSC is cleared when the conversion finishes
      while (bit_is_set (ADCSRA, ADSC))
        { }

      byte low  = ADCL;
      byte high = ADCH;

      ADCSRA = 0;  // disable ADC
      power_adc_disable();

      return (high << 8) | low;

      }  // end of getReading

    // watchdog interrupt
    ISR (WDT_vect)
    {
       wdt_disable();  // disable watchdog
    }  // end of WDT_vect

    #if defined(__AVR_ATtiny85__)
      #define watchdogRegister WDTCR
    #else
      #define watchdogRegister WDTCSR
    #endif

    void setup ()
      {
      wdt_reset();
      pinMode (LED, OUTPUT);
      pinMode (LDR_ENABLE, OUTPUT);
      ADCSRA = 0;            // turn off ADC
      power_all_disable ();  // power off ADC, Timer 0 and 1, serial interface
      }  // end of setup

    void loop ()
      {
      // power up the LDR, take a reading
      digitalWrite (LDR_ENABLE, HIGH);
      int value = getReading (LDR_READ);
      // power off the LDR
      digitalWrite (LDR_ENABLE, LOW);

      // if it's dark, flash the LED for 2 mS
      if (value < LIGHT_THRESHOLD)
        {
        power_timer0_enable ();
        delay (1);  // let timer reach a known point
        digitalWrite (LED, HIGH);
        delay (2);
        digitalWrite (LED, LOW);
        power_timer0_disable ();
        }

      goToSleep ();
      }  // end of loop

    void goToSleep ()
      {
      set_sleep_mode (SLEEP_MODE_PWR_DOWN);
      noInterrupts ();       // timed sequence coming up

      // pat the dog
      wdt_reset();

      // clear various "reset" flags
      MCUSR = 0;
      // allow changes, disable reset, clear existing interrupt
      watchdogRegister = bit (WDCE) | bit (WDE) | bit (WDIF);
      // set interrupt mode and an interval (WDE must be changed from 1 to 0 here)
      watchdogRegister = bit (WDIE) | bit (WDP2) | bit (WDP1) | bit (WDP0);    // set WDIE, and 2 seconds delay

      sleep_enable ();       // ready to sleep
      interrupts ();         // interrupts are required now
      sleep_cpu ();          // sleep
      sleep_disable ();      // precaution
      }  // end of goToSleep

  [1]: https://i.stack.imgur.com/64WDN.jpg
  [2]: https://i.stack.imgur.com/39zxB.jpg
  [3]: https://i.stack.imgur.com/3ng6T.jpg


message:
Using an Arduino as a crystal oscillator

I want to overclock my [Game Boy Advance SP][1]. It has a built-in 4 MHz crystal, and I was able to temporarily replace it with an 8 MHz crystal to see if I was able to overclock it, which I was :).

However I'm wondering if it's possible to emulate/simulate a crystal using an Arduino? Like instead of a crystal soldered to the Game Boy, two output pins from the Arduino? If not, is there a such thing as a variable oscillator? Like a crystal with a potentiometer to change the frequency when the potentiometer is adjusted?

  [1]: https://en.wikipedia.org/wiki/Game_Boy_Advance_SP

body:
You want to use the Uno? You can set up a timer to output varying frequencies and output them on a pin. I have [a page about timers](http://www.gammon.com.au/timers) which might help. The fastest you can get with a 16 MHz processor is 8 MHz output however you can get other frequencies by changing the timer parameters.

The ATtiny85 can output higher frequencies if you use the PLL clock option, I think you can then adjust the resulting frequency.

>  If not, is there a such thing as a variable oscillator?

Adafruit make a [Clock Generator Breakout Board - 8KHz to 160MHz](https://www.adafruit.com/products/2045). You connect that via I2C to your Arduino and then program assorted frequencies as a clock output. That uses the Si5351A clock generator chip.

---

Example code to output 8 MHz on a Uno or Mega2560:

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

    #ifdef __AVR_ATmega2560__
      const byte CLOCKOUT = 11;  // Mega 2560
    #else
      const byte CLOCKOUT = 9;   // Uno, Duemilanove, etc.
    #endif

    void setup ()
      {
      // set up 8 MHz timer on CLOCKOUT (OC1A)
      pinMode (CLOCKOUT, OUTPUT);
      // set up Timer 1
      TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
      TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaling
      OCR1A =  0;       // output every cycle
      }  // end of setup

    void loop ()
      {
      // whatever
      }  // end of loop

To output 4 MHz change OCR1A to 1 rather than 0.


body:
A crystal oscillator connection to a microcontroller typically consists of two pins - an output "driving" pin, and an input "amplifying" pin. The crystal sits between the two pins (basically between the input and the output of the amplifier) and the amplifier oscillates at the frequency of the crystal.

In general you can bypass the crystal itself and just provide a clock signal on the input pin (often labelled OSC1 or OSCI) and ignore the output pin since it isn't needed to drive a crystal.

Some microcontrollers provide a special "EC" mode (External Clock) which disables the amplifier and just expects a clock signal.


body:
Using the Arduino platform as a signal generator (oscillator) results in too high a granularity factor.  Software that has been suggested can only change between 8 and 4 MHz but not output anything between those two frequencies.

It would be better to use some sort of DDS or Frequency Synthesizer circuit
that can be adjusted incrementally with a granularity of 1 Hz or better.
My suggestion would be to use the Arduino to control a modern synthesis IC
like the S15351a.  This combination can output any frequency from 3KHz to
160 MHz in 1 Hz steps.  The device is inexpensive and has 3 outputs which
can be adjusted independently.  Google "Si5351a Arduino" to find some
circuit suggestions.
<https://www.qrp-labs.com/progrock.html>


message:
Coding problem (gesture sensor)

Hi I am using an Arduino Mega 2560 with two sparkfun zx gesture sensors, two servos, 4 rgb leds strips and 4 light switches.

With the sensor, the code relies on interrupts, which interfere with the bahaviour of the servo and leds.

My knowledge of coding is limited so I am unsure of how to work around this, I think I have to introduce some new code.
[interrupts leds and servos][1]
However, I am unsure of how to introduce it.

Any help would be appreciated.

  [1]: https://learn.adafruit.com/neopixels-and-servos/overview

body:
>With the sensor, the code relies on interrupts, which interfere with the bahaviour of the servo and leds.

The best solution for this problem would be to use objects and the `millis()` function.

[Here][1] is a great tutorial about objects and why do we use them with the `millis()` function. I wont explain it because it it too long and this tutorial is simply better.

I would also suggest to see the `blinkWithOutDelay` example code from the Arduino IDE. It is probably the first step you have to take to learn how to use the `millis()` function.

  [1]: https://learn.adafruit.com/multi-tasking-the-arduino-part-1/overview


body:
Driving servos and LEDs from a hardware PWM may help. They will maintain a steady state even if there are interrupts. They may be a little less responsive to changes if there are interrupts.

Are you doing too much when the sensor interrupts? Typically a sensor makes multiple measurements and may be filters the results. When it is ready it interrupts. In the interrupt it should do as little as possible. Typically sending a message via global to a polling function that is not running in an interrupt. For example it may set a flag and the poling function reads the result. Reading the result in the interrupt would be bad.