message:
Can't drive long NeoPixel strips with Due or Duemilanove?

I spent a significant part of today developing a sprite movement library for a 30-pixel NeoPixel strip using my Arduino Duemilanove (ATmega 168). It works like a charm. However, if I change `N_LEDS` to a significantly higher value, the program seems not to run. I can't get it to run on the Duemilanove for a strip of longer than 50.

In fact, (see the below code) a relatively high `N_LEDS` value won't even allow the test patterns to run as defined in `setup()`. This leads me to believe that inexplicably the constructor for `Adafruit_Neopixel` is failing.

A friend of mine (who has the ultimate application for this) is hoping to drive a strand of 750 LEDs using this code on an Arduino Due. I can't imagine memory would be an issue with the Due, so what's going on here?

Headers:

    #include <Adafruit_NeoPixel.h>

    #define PIN    6
    #define N_LEDS 30      // <-- If this number is > ~50, nothing happens
    #define MAXSPRITES 5
    #define MIN_UPDATE_INTERVAL_IN_MS  15
    #define MAX_UPDATE_INTERVAL_IN_MS  40
    #define SENSOR_TIMEOUT_IN_MS  2000
    #define SCANNER_WIDTH  9

Strip declaration:

    Adafruit_NeoPixel strip = Adafruit_NeoPixel(N_LEDS, PIN, NEO_GRB + NEO_KHZ800);

`setup()` and `loop()`:

    void setup() {
        randomSeed(analogRead(0));

        strip.begin();

        darkenStrip();

        manager = new SpriteManager();
        manager->Add(new TestPatternSprite(0, 0xff0000));
        manager->Add(new TestPatternSprite(5, 0x00ff00));
        manager->Add(new TestPatternSprite(10, 0x0000ff));
    }

    loop() {
        ...
    }

Are there any coding mistakes in the above that wouldn't allow us to run this code on the Due? Or is this a known limitation?

body:
Your Duemilanove only has 1k of RAM. That's not much. Each pixel takes 3 bytes of RAM (R/G/B). So (say) 60 pixels would be 180 bytes. That's less than 1k, but there would be other uses of RAM in your sketch.

750 LEDs sounds like pushing it for the low-RAM Arduinos.

You might want to look at [NeoPixels Revealed: How to (not need to) generate precisely timed signals](http://wp.josh.com/2014/05/13/ws2812-neopixels-are-not-so-finicky-once-you-get-to-know-them/) The author managed to drive over 1000 NeoPixels with a Duemilanove.

I'm not sure if that applies to your exact type of NeoPixels, but it is worth considering.


sender: user

message:
LCD-Display showing wrong numbers

Hy guys,

I am having an issue with my new LCD16x2 display. I connected a potentiometer and read the values. The values are properly read and send to Serial. I also display the values on the display. I am having no issues when increasing the values, but when I go down again at a certain point the displays doesn't display the correct value anymore, but on the Serial I can still see the right readings.

I suppose this has something to do with the display still storing previous values for this digit in the buffer and when I go down the values are not properly reset. But I don't wan't to clear the whole buffer, since then the whole thing just blinks every iteration.

Here's my code

    // ESC_Calibration.ino
    #include <Wire.h>
    #include <Adafruit_MCP23017.h>
    #include <Adafruit_RGBLCDShield.h>
    #include <Servo.h>

    #define WHITE 0x7

    Servo firstESC;
    Servo secondESC;
    int throttlePin = 2;
    int firstESCPin = 2;
    int secondESCPin = 3;

    Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

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

     lcd.begin(16, 2);
     lcd.setBacklight(WHITE);
     lcd.setCursor(0, 0);
     lcd.print("throttle:");

     firstESC.attach(firstESCPin);
     secondESC.attach(secondESCPin);
    }

    void loop() {
     int throttle = analogRead(throttlePin);
     throttle = map(throttle, 0, 1023, 0, 179);

     lcd.setCursor(0, 1);
            Serial.println(throttle);
            lcd.setCursor(0, 1);
     lcd.print(throttle);

     firstESC.write(throttle);
     secondESC.write(throttle);

     delay(500);
    }

Does anyone have a suggestion how to improve this and fix it, so it'll display the right readings, but doesn't blink?

Thanks for your help in advance! :-)

sender: assistant

body:
As you have surmised, the problem is that the LCD retains what was there before and you need to clear it away.

That means, as the numbers increase you get, say,

    4
    10
    48
    89
    194
    309

etc.

When they go down though, because the LCD remembers what was there, only the characters you print will be replaced:

    309 (309)
    194 (194)
    894 (89 - the 4 remains from before)
    484 (48 - the 4 remains from before)
    104 (10 - the 4 remains from before)
    404 (4 - the 04 remains from before)

Also, as you have noticed, clearing the whole screen is not very nice since it makes it flash.

To combat that it is important that you only overwrite the characters that you need to overwrite and leave those that want to stay.  There's two common ways of doing this:

1. Append enough spaces after the number to force an overwrite:
````
    lcd.print(throttle);
    lcd.print("   "); // 3 spaces should be enough for 3 extra digits
````

2. Format the data with `snprintf()`:
````
    char temp[5]; // enough room for 4 numbers and one NULL character
    snprintf(temp, 5, "M", throttle); // M = 4 digits, right aligned
    lcd.print(temp);
````

The latter method, though it is more complex and uses more resources, can be preferred because it creates a much nicer output with the numbers properly right-aligned.  Also arbitrarily adding spaces after the number could overwrite things you want to keep.

You could also achieve a similar result doing it manually:

    if (throttle < 10) lcd.print(" "); // 0-9 add one space
    if (throttle < 100) lcd.print(" "); // 0-99 add one space
    if (throttle < 1000) lcd.print(" "); // 0-999 add one space
    lcd.print(throttle);

Just like with cats, there's many ways to skin this problem...


message:
Smart Chess-board (possibly using RFIDs?)

I'd like to make a chess-board with the ability to detect the position of each piece.

The solution that occurs to me would be to put an RFID reader under each square and put RFID tags on the bottoms of each piece.

However, apart from the obvious cost (64 readers!) I'm concerned that:

1. Maybe RFID readers are too large for the squares of an ordinary chessboard
2. RFID reader range is too large, so a reader might pick up pieces on neighbouring squares
3. How the hell would I connect 64 readers anyway? Could an Arduino handle it?

So, questions.

Is this just stupid? And is there a better technology to use for this kind of application?

If RFIDs are basically a sane solution, what are the issues/suggestions? E.g. which RFID readers should I go for? (Based on size, energy, convenience for this application). What boards would let me handle this number of them?

body: As I read your post an idea came to me that must be obvious in its simplicity.  Since a chess board has pieces already on it we can simply use hall-effect sensors (dirt cheap) under each square and each piece has a magnet at its base.  Since pieces on a chess board move from one square to another and the initial position of all pieces is known/constant, the detection of a move would be that a piece is lifted from the board (hall effect sensor detects a magnetic field removal) and a piece being placed on a square would be detected by a hall effect senor addition of a magnetic field.  We wouldn't know which piece is placed on a square but we can calculate it by remembering what piece was lifted and it can only be the piece that was placed.


message:
Breadboard Arduino not loading sketches

I have put together a breadboard version of the arduino by following the tutorial on arduino's main website https://www.arduino.cc/en/Main/Standalone.

I have done everything exactly how that tutorial explains it and have double checked my work to ensure I didn't mess up a connection somehow. I have a usb mini breadout board that I am connecting from the breadboard to my computer and the pin outs are as follows:

- GND -> Breadboard GND
- 5v -> Breadboard + rail
- TXO -> IC pin 2
- RXI -> IC pin 3
- GND (GRN) -> IC pin 1 through .1μF cap

When I go to the arduino IDE and select the arduino duemilanove setting and upload a sketch I come out with this error:

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

I am using a pre-bootloaded atmega328 chip and have switched it out with two others to make sure it wasn't the switch, but that didn't help either.

Any ideas on what might be the problem?

body:
1. Make sure you have a 16Mhz crystal attached to your board at the XTAL locations properly.

2. If you dont have one already, connect a 0.1uf capacitor (ceramic or metal film) to the reset pin for auto reset capabilities.

3. The `avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00` issue is probably due to reset problems, where the arduino is not communicating to the computer. However, there are other possible reasons for this error. http://forum.arduino.cc/index.php?topic=28223.0

4. Double check that TX on the arduino is connected to Rx on the computer and Rx on the arduino is connected to Tx on the computer

If problems keep persisting, post more information so we can help you more.


body:
To expand upon what was previously mentioned in comments, there are a number of things that need to be done before you can program an ATmega via a serial  connection:

 - you need to have a bootloader flashed on the chip

 - you need to provide a clock source (internal or external) matching the fuse settings and the rate expected by the bootloader

 - your programming software must use the same baud rate as the bootloader is expecting

 - you need to have reset the chip recently enough before starting the upload that the bootloader has not timed out - either manually or via a small capacitor to your logic level serial connection's DTR or RTS line

You commented that your chip came from Sparkfun and was sold as having a bootloader.  The programmed ATmega328p's they list claim to have the Uno's bootloader, so most likely these need to be programmed at 115200 baud like an Uno.  You instead said that you had selected the Duemilanove setting, which would mean you were trying to use a baud rate of 57600.


message:
Attiny88 programming with Arduino

I want to program Attiny88 with Arduino IDE 1.6.5. I chose Attiny88  because it's the cheapest Attiny (as low as $0.5) and at the same time has 28 pins. I found a library that support Attiny88 (https://github.com/TCWORLD/ATTinyCore) but it seams it does not support IDE 1.6.5 and generates errors when I burn bootloader or during ISP.

Is there any library to program Attiny88 with Arduino 1.6.5?

body:
Finally I found ATTinyCore library. I have tested it with a blink sketch. Just download the zip file. Unzip and copy  Attinycore-master directory into "program files/Arduino/hardware/arduino/avr" directory. Restart the IDEA. Select ATTiny x8 Series from the boards menu, and select the specific chip (48 or 88), clock speed, and BOD level from the appropriate menus that will appear in the tools menu after selecting ATTiny x8 series as the board.

https://github.com/SpenceKonde/ATTinyCore


body:
I went through the same problem finding the cores for the attiny 88 and found this

http://forum.arduino.cc/index.php?topic=320742.0

https://arduino.stackexchange.com/questions/13011/programming-attiny88-attiny828-with-arduino

However, I have not yet found the core for the attiny88 at 12mhz (http://co.mouser.com/ProductDetail/Atmel/ATTINY88-AU/?qs=sGAEpiMZZMvqv2n3s2xjscfa4zIkTHJI8r77%2bczQD%2bE=)


message:
Cannot convert 'String' to 'uint8_t {aka unsigned char}' in initialization

Hey all I am trying to convert a string into a uint8_t with the following code:

    String data = "#255101987";
    String tmp1 = data.substring(1, 3);

    uint8_t first  = (String)tmp1;

I am getting the error of:

>cannot convert 'String' to 'uint8_t {aka unsigned char}' in initialization

Any help would be great as I thought adding **(String)** in front of the varible would solve the issue but it hasn't as you can tell.

body:
    uint8_t first  = atoi (tmp1.substring(1, 3).c_str ());

Or even:

    String data = "#255101987";
    uint8_t first  = atoi (data.substring(1, 3).c_str ());


message:
How to read AC Voltage in arduino uno with 12V adaptor and usb cable.?

i want to ON-OFF two lights(white and red), one from main power source(white light) and one from ups(battery). When main power is present, white light should be ON and red should be off. And when main power fails, red should be ON and White should be OFF.
I have Arduino, usb cable, external power supplier(adapter of 12V).

Can any one please suggest me how do i proceed for this ??

body:
If your battery voltage is lower than 12 but sufficiently high to power the arduino (let's say 9V), you could put a white LED on the 12V line and a red LED on the battery line, like this:

             WHITE       RED
      _______|>|_________|<|________
     |             |                |
    _|_          Arduino           _|_
     - 12V         |                -   Battery
     |_____________|________________|

This should work, as long as the LEDs can withstand the reverse voltage.
And you do not need to drive them from the Arduino.
If you still want to know the status fro mthe Arduino (mains or battery) you can sample the voltage level across the Arduino.


message:
Capacitive Sensor gets stuck

I want to use CapacitiveSensor library in order to make my own aluminum keys piano. I have seen many videos online showing projects like the one I'm trying to do, but for some reason mine doesn't work.

Here's my cuircit:
![enter image description here][1]

Here's my code:

    #include <CapacitiveSensor.h>

    CapacitiveSensor   cs_7_6 = CapacitiveSensor(7,6);  // 10M resistor between pins 7 & 6, pin 6 is sensor pin

    void setup()
    {
       //cs_7_6.set_CS_AutocaL_Millis(0xFFFFFFFF);     // turn off autocalibrate on channel 1 - just as an example
       Serial.begin(9600);
    }

    void loop()
    {
        long start = millis();
        long total1 =  cs_7_6.capacitiveSensor(5);

        Serial.print(millis() - start);        // check on performance in milliseconds
        Serial.print("\t");                    // tab character for debug windown spacing

        Serial.print(total1);                  // print sensor output 1
        Serial.println("\t");

        delay(10);                             // arbitrary delay to limit data to serial port
    }

This happens whenever I touch the aluminum foil:

![enter image description here][2]

First nothing happens (for ~1 sec), then it prints -2 as the capacity value, and when I release my finger from the foil it prints a very high value.

Anyone knows the reason for it? I'm searching for an answer for a long time and still can't find a solution...

  [1]: https://i.stack.imgur.com/zq7rx.png
  [2]: https://i.stack.imgur.com/foltu.png

body:
The problem is that you're touching the foil.

The "capacitive sensing" used in that library is crude at best.

If you read [the Arduino Playground page for the Capacitive Sensing Library](http://playground.arduino.cc/Main/CapacitiveSensor?from=Main.CapSense) it discusses a lot of the problems with the library, including grounding.  Make sure that the Arduino is properly grounded, or provide your own ground plane under the foil sensors.

Also they talk about the value of resistor and the sensitivity.  With a 10MΩ resistor you get sensing at (supposedly) 4-6cm from the foil.  That's the value you're seeing as you remove your finger.  While you're touching the foil it's just having a complete brain haemorrhage and can't work out what is going on (completely unable to charge the pin since you are leeching off all the current).  For "absolute touch" it recommends no more than 1MΩ.

Of course, as I mentioned, that method is rather crude.  To do it properly you need to:

1. Discharge an analog input pin through a MOSFET to ground (low impedance).
2. Apply a constant current (typically 50µA is used but varies depending on ADC characteristics) to the analog input for a fixed amount of time.
3. Remove the current and measure the voltage on the ADC input.
4. Repeat.

More modern MCUs have this kind of functionality built in, in the form of a "CTMU" - *Charge Time Measurement Unit*.  If you want to have anything more than "there's someone vaguely in the vicinity of the sensor" then I would suggest switching to a more modern MCU and doing it properly, or employing a specific CTMU chip as an external device.

Also, the sensor should be comprised of three parts - a ground plane, a sensor plane (connected to the ADC) and a dielectric layer between them.  The sensor should also be insulated from direct touch.


message:
Highly sensitive light sensor to calculate number of times each color LED blinks

I am working on a project and got stuck on a point, and I hope somebody will guide me. I have a hardware device which has different color LEDs (green, red and yellow) and I have to calculate how many times each color LED glows for each mode of operation.

The LEDs that are connected to the device are pretty small and will blink only for a couple of seconds, ao I am looking for a very sensitive light sensor.

So what kind of light sensor do I have to use with Arduino UNO to achieve this?

Should I go for BH1750 or do you have any other suggestion?

Thanks in advance.

body:
Like the OP wrote, you can use very simple sensors, like a phototransistor.
Even simpler, if you can somehow isolate each pair LED-phototransistor, you don't even need to care about the color of the led, just use some bluetac to stick one phototransistor on top of each LED and only measure the brightness.

**edit:**

A quick check on ebay shows the 3DU5C as good candidate: it has a metallic container, so it is more directional than one with full plastic body.

3DU5C [ebay link][1]  and  [datasheet][2]

It is shown to have a peak response at 880nm (red light), so you might not be able to use it directly as digital input for the other 2 colors you want to monitor and instead have to treat it as analog reading.

OTOH if you use them all as analog inputs, you will not have to add the resistor that would be required for binary mode.

  [1]: http://www.ebay.com/itm/3DU5C-Silicon-Phototransistor-Transistor-2-feet-Metal-Package-/251556003565?pt=LH_DefaultDomain_0&hash=item3a91e7feed
  [2]: http://www.uctronics.com/download/3DU5C_spec.pdf


message:
Arduino C++ library syntax

I am looking at modifying the H3LI331DL I2C library posted by Seed Studio for communicating with the H3LI331DL accelerometer. The library hardcodes the address for the accelerometer in the header file. My end goal is to make the library require a slave address input argument so I can talk to 2 accelerometers on the same I2C bus. The chip has a pin that sets the LSB of its address.

Now onto the question. The library's .h file has the following statement:

`#define H3LIS331DL_MEMS_I2C_ADDRESS     0x18//0x32`

Is the 0x32 simply commented out or am I missing something here?

Thanks,

Emach

body: It is indeed commented out. SeeedStudio is a great company but their code (including code prettifying) is pretty sloppy, and sometimes a little dumbfounding.


message:
RC servo misbehave using arduino and MPU6050

I am a beginner.. I am trying to control RC servo using Arduino based of data from MPU6050.
I am using library I2Cdev to communicate with gyro and to get yaw, pitch and roll. I am using example script which I have modified to control servo based on received data.

    mpu.dmpGetQuaternion(&q, fifoBuffer);
    mpu.dmpGetGravity(&gravity, &q);
    mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

    Serial.print("ypr\t");
    Serial.print(ypr[0] * 180 / M_PI);
    Serial.print("\t");
    Serial.print(ypr[1] * 180 / M_PI);
    Serial.print("\t");
    Serial.println(ypr[2] * 180 / M_PI);

    pitch_angle = (ypr[1] * 180 / M_PI) + 90;
    roll_angle = (ypr[2] * 180 / M_PI) + 90;

    Serial.print(pitch_angle);
    Serial.print("\t");
    Serial.println(roll_angle);

    pitchServo.write((int)(pitch_angle));
    rollServo.write((int)(roll_angle));

Without servo being connected everything works well.
But after I plug in servo after few second being still (it seems to even follow movement of gyro) it starts to shake and then probably whole Arduino stops working (serial transmission of data stops) and Arduino has to be restarted.

    100 95
    ypr 12.21 10.51 5.49
    100 95
    ypr 12.23 10.31 5.48
    100 95
    ypr 12.25 10.15 5.45
    100 95
    ypr 12.27 10.02 5.45
    100 95
    ypr -13.31 30.81 55.76
    120 145
    ypr 20.53 -21.36 -52.59
    68 37
    ypr 64.96 35.38 10.25
    125 100

I tried to plug two 100 nF capacitors across power and ground of the servo and I tried to connect servo in to different power source than Arduino.

**EDIT:**
Servo is not fixed with MPU6050 so there shouldn't be any resonance at least on the mechanical base.
Wiring is very simple:

![enter image description here][1]

Any idea? Thanks

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

body:
So a couple of ideas.

1) you need to be real careful with the MPU and overflows. You do not show all your code, but you must check for overflows, and ignore the data if one has occurred. I see in your print a stray negative value, that tells me you are not skipping bad data.

2) I dont know how 'tight' your loop is. You need to service the MPU a lot. In fact the sample you used, uses an interrupt to do so. I think the default update rate is about 100 times per second.  That may be too fast to make large changes in servo positions.  You will need to think about moving slower from point A to B if the difference is more than the servo can handle at that speed.

3) You are adding 90. With the numbers you have shown that is probably ok, but in your final code you need to be careful you do not exceed a servos range, 0 to 180.  the map() function is probably something you will want to use, instead of just adding 90.

4) My guess is that since it works for a second or 2, it is indeed over flowing data, and then goes to heck. Especially since you do not skip errors.

5) it takes the 6050 30 seconds or so to settle - so you will see large gyro drift (including PitchRollYaw) until it does. Probably not what your code is expecting.


body:
At the end two pull-up resistors and one capacitor solved the problem.

I followed instruction here:

http://www.instructables.com/id/Brushless-Gimbal-with-Arduino/step3/Using-the-Accelerometer-and-Gyro/

Now it works well.. Thank you all.


message:
Error compiling code (tv-b gone)

I have been getting started with the Arduino and found a great project online called [TV-B-Gone](http://www.righto.com/2009/12/tv-b-gone-for-arduino.html). It includes some code which I cannot compile. Yes I have included `main.h` and `worldcodes.cpp`.

    /*
    TV-B-Gone for Arduino version 0.001
     Ported to Arduino by Ken Shirriff, Dec 3, 2009
     http://arcfn.com

     The original code is:
     TV-B-Gone Firmware version 1.2
     for use with ATtiny85v and v1.2 hardware
     (c) Mitch Altman + Limor Fried 2009
     Last edits, August 16 2009

     With some code from:
     Kevin Timmerman & Damien Good 7-Dec-07

     Distributed under Creative Commons 2.5 -- Attib & Share Alike

     This is the 'universal' code designed for v1.2 - it will select EU or NA
     depending on a pulldown resistor on pin B1 !
     */

    #include "main.h"

    void xmitCodeElement(uint16_t ontime, uint16_t offtime, uint8_t PWM_code );
    void flashslowLEDx( uint8_t num_blinks );
    void quickflashLEDx( uint8_t x );
    void tvbgone_sleep( void );
    void delay_ten_us(uint16_t us);
    void quickflashLED( void );
    uint8_t read_bits(uint8_t count);

    #define putstring_nl(s) Serial.println(s)
    #define putstring(s) Serial.print(s)
    #define putnum_ud(n) Serial.print(n, DEC)
    #define putnum_uh(n) Serial.print(n, HEX)

    /*
    This project transmits a bunch of TV POWER codes, one right after the other,
     with a pause in between each.  (To have a visible indication that it is
     transmitting, it also pulses a visible LED once each time a POWER code is
     transmitted.)  That is all TV-B-Gone does.  The tricky part of TV-B-Gone
     was collecting all of the POWER codes, and getting rid of the duplicates and
     near-duplicates (because if there is a duplicate, then one POWER code will
     turn a TV off, and the duplicate will turn it on again (which we certainly
     do not want).  I have compiled the most popular codes with the
     duplicates eliminated, both for North America (which is the same as Asia, as
     far as POWER codes are concerned -- even though much of Asia USES PAL video)
     and for Europe (which works for Australia, New Zealand, the Middle East, and
     other parts of the world that use PAL video).

     Before creating a TV-B-Gone Kit, I originally started this project by hacking
     the MiniPOV kit.  This presents a limitation, based on the size of
     the Atmel ATtiny2313 internal flash memory, which is 2KB.  With 2KB we can only
     fit about 7 POWER codes into the firmware's database of POWER codes.  However,
     the more codes the better! Which is why we chose the ATtiny85 for the
     TV-B-Gone Kit.

     This version of the firmware has the most popular 100+ POWER codes for
     North America and 100+ POWER codes for Europe. You can select which region
     to use by soldering a 10K pulldown resistor.
     */

    /*
    This project is a good example of how to use the AVR chip timers.
     */

    /*
    The hardware for this project uses an Arduino:
     Connect an IR LED to pin 3.
     Connect a visible LED to pin 13 (or use builtin LED in some Arduinos).
     Connect a pushbutton between pin 1 and ground.
     Pin 0 is floating for North America, or wired to ground for Europe.
     */

    extern PGM_P *NApowerCodes[] PROGMEM;
    extern PGM_P *EUpowerCodes[] PROGMEM;
    extern uint8_t num_NAcodes, num_EUcodes;

    /* This function is the 'workhorse' of transmitting IR codes.
     Given the on and off times, it turns on the PWM output on and off
     to generate one 'pair' from a long code. Each code has ~50 pairs! */
    void xmitCodeElement(uint16_t ontime, uint16_t offtime, uint8_t PWM_code )
    {
      TCNT2 = 0;
      if(PWM_code) {
        pinMode(IRLED, OUTPUT);
        // Fast PWM, setting top limit, divide by 8
        // Output to pin 3
        TCCR2A = _BV(COM2A0) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
        TCCR2B = _BV(WGM22) | _BV(CS21);
      }
      else {
        // However some codes dont use PWM in which case we just turn the IR
        // LED on for the period of time.
        digitalWrite(IRLED, HIGH);
      }

      // Now we wait, allowing the PWM hardware to pulse out the carrier
      // frequency for the specified 'on' time
      delay_ten_us(ontime);

      // Now we have to turn it off so disable the PWM output
      TCCR2A = 0;
      TCCR2B = 0;
      // And make sure that the IR LED is off too (since the PWM may have
      // been stopped while the LED is on!)
      digitalWrite(IRLED, LOW);

      // Now we wait for the specified 'off' time
      delay_ten_us(offtime);
    }

    /* This is kind of a strange but very useful helper function
     Because we are using compression, we index to the timer table
     not with a full 8-bit byte (which is wasteful) but 2 or 3 bits.
     Once code_ptr is set up to point to the right part of memory,
     this function will let us read 'count' bits at a time which
     it does by reading a byte into 'bits_r' and then buffering it. */

    uint8_t bitsleft_r = 0;
    uint8_t bits_r=0;
    PGM_P code_ptr;

    // we cant read more than 8 bits at a time so dont try!
    uint8_t read_bits(uint8_t count)
    {
      uint8_t i;
      uint8_t tmp=0;

      // we need to read back count bytes
      for (i=0; i<count; i++) {
        // check if the 8-bit buffer we have has run out
        if (bitsleft_r == 0) {
          // in which case we read a new byte in
          bits_r = pgm_read_byte(code_ptr++);
          // and reset the buffer size (8 bites in a byte)
          bitsleft_r = 8;
        }
        // remove one bit
        bitsleft_r--;
        // and shift it off of the end of 'bits_r'
        tmp |= (((bits_r >> (bitsleft_r)) & 1) << (count-1-i));
      }
      // return the selected bits in the LSB part of tmp
      return tmp;
    }

    /*
    The C compiler creates code that will transfer all constants into RAM when
     the microcontroller resets.  Since this firmware has a table (powerCodes)
     that is too large to transfer into RAM, the C compiler needs to be told to
     keep it in program memory space.  This is accomplished by the macro PROGMEM
     (this is used in the definition for powerCodes).  Since the C compiler assumes
     that constants are in RAM, rather than in program memory, when accessing
     powerCodes, we need to use the pgm_read_word() and pgm_read_byte macros, and
     we need to use powerCodes as an address.  This is done with PGM_P, defined
     below.
     For example, when we start a new powerCode, we first point to it with the
     following statement:
     PGM_P thecode_p = pgm_read_word(powerCodes+i);
     The next read from the powerCode is a byte that indicates the carrier
     frequency, read as follows:
     const uint8_t freq = pgm_read_byte(code_ptr++);
     After that is a byte that tells us how many 'onTime/offTime' pairs we have:
     const uint8_t numpairs = pgm_read_byte(code_ptr++);
     The next byte tells us the compression method. Since we are going to use a
     timing table to keep track of how to pulse the LED, and the tables are
     pretty short (usually only 4-8 entries), we can index into the table with only
     2 to 4 bits. Once we know the bit-packing-size we can decode the pairs
     const uint8_t bitcompression = pgm_read_byte(code_ptr++);
     Subsequent reads from the powerCode are n bits (same as the packing size)
     that index into another table in ROM that actually stores the on/off times
     const PGM_P time_ptr = (PGM_P)pgm_read_word(code_ptr);
     */

    uint16_t ontime, offtime;
    uint8_t i,j, Loop;
    uint8_t region = US;     // by default our code is U

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

      TCCR2A = 0;
      TCCR2B = 0;

      digitalWrite(LED, LOW);
      digitalWrite(IRLED, LOW);
      pinMode(LED, OUTPUT);
      pinMode(IRLED, OUTPUT);
      pinMode(REGIONSWITCH, INPUT);
      pinMode(TRIGGER, INPUT);
      digitalWrite(REGIONSWITCH, HIGH); //Pull-up
      digitalWrite(TRIGGER, HIGH);

      delay_ten_us(5000);            // Let everything settle for a bit

      // determine region
      if (digitalRead(REGIONSWITCH)) {
        region = US; // US
        DEBUGP(putstring_nl("US"));
      }
      else {
        region = EU;
        DEBUGP(putstring_nl("EU"));
      }

      // Tell the user what region we're in  - 3 is US 4 is EU
      quickflashLEDx(3+region);

      // Indicate how big our database is
      DEBUGP(putstring("\n\rNA Codesize: ");
      putnum_ud(num_NAcodes);
      );
      DEBUGP(putstring("\n\rEU Codesize: ");
      putnum_ud(num_EUcodes);
      );
    }

    void sendAllCodes() {
      // We may have different number of codes in either database
      if (region == US) {
        j = num_NAcodes;
      }
      else {
        j = num_EUcodes;
      }

      // for every POWER code in our collection
      for (i=0 ; i < j; i++) {
        PGM_P data_ptr;

        // print out the code # we are about to transmit
        DEBUGP(putstring("\n\r\n\rCode #: ");
        putnum_ud(i));

        // point to next POWER code, from the right database
        if (region == US) {
          data_ptr = (PGM_P)pgm_read_word(NApowerCodes+i);
        }
        else {
          data_ptr = (PGM_P)pgm_read_word(EUpowerCodes+i);
        }

        // print out the address in ROM memory we're reading
        DEBUGP(putstring("\n\rAddr: ");
        putnum_uh((uint16_t)data_ptr));

        // Read the carrier frequency from the first byte of code structure
        const uint8_t freq = pgm_read_byte(data_ptr++);
        // set OCR for Timer1 to output this POWER code's carrier frequency
        OCR2A = freq;
        OCR2B = freq / 3; // 33% duty cycle

        // Print out the frequency of the carrier and the PWM settings
        DEBUGP(putstring("\n\rOCR1: ");
        putnum_ud(freq);
        );
        DEBUGP(uint16_t x = (freq+1) * 2;
        putstring("\n\rFreq: ");
        putnum_ud(F_CPU/x);
        );

        // Get the number of pairs, the second byte from the code struct
        const uint8_t numpairs = pgm_read_byte(data_ptr++);
        DEBUGP(putstring("\n\rOn/off pairs: ");
        putnum_ud(numpairs));

        // Get the number of bits we use to index into the timer table
        // This is the third byte of the structure
        const uint8_t bitcompression = pgm_read_byte(data_ptr++);
        DEBUGP(putstring("\n\rCompression: ");
        putnum_ud(bitcompression);
        putstring("\n\r"));

        // Get pointer (address in memory) to pulse-times table
        // The address is 16-bits (2 byte, 1 word)
        PGM_P time_ptr = (PGM_P)pgm_read_word(data_ptr);
        data_ptr+=2;
        code_ptr = (PGM_P)pgm_read_word(data_ptr);

        // Transmit all codeElements for this POWER code
        // (a codeElement is an onTime and an offTime)
        // transmitting onTime means pulsing the IR emitters at the carrier
        // frequency for the length of time specified in onTime
        // transmitting offTime means no output from the IR emitters for the
        // length of time specified in offTime

    #if 0

        // print out all of the pulse pairs
        for (uint8_t k=0; k<numpairs; k++) {
          uint8_t ti;
          ti = (read_bits(bitcompression)) * 4;
          // read the onTime and offTime from the program memory
          ontime = pgm_read_word(time_ptr+ti);
          offtime = pgm_read_word(time_ptr+ti+2);
          DEBUGP(putstring("\n\rti = ");
          putnum_ud(ti>>2);
          putstring("\tPair = ");
          putnum_ud(ontime));
          DEBUGP(putstring("\t");
          putnum_ud(offtime));
        }
        continue;
    #endif

        // For EACH pair in this code....
        cli();
        for (uint8_t k=0; k<numpairs; k++) {
          uint16_t ti;

          // Read the next 'n' bits as indicated by the compression variable
          // The multiply by 4 because there are 2 timing numbers per pair
          // and each timing number is one word long, so 4 bytes total!
          ti = (read_bits(bitcompression)) * 4;

          // read the onTime and offTime from the program memory
          ontime = pgm_read_word(time_ptr+ti);  // read word 1 - ontime
          offtime = pgm_read_word(time_ptr+ti+2);  // read word 2 - offtime
          // transmit this codeElement (ontime and offtime)
          xmitCodeElement(ontime, offtime, (freq!=0));
        }
        sei();

        //Flush remaining bits, so that next code starts
        //with a fresh set of 8 bits.
        bitsleft_r=0;

        // delay 250 milliseconds before transmitting next POWER code
        //delay_ten_us(25000);
        delay_ten_us(10000);

        // visible indication that a code has been output.
        quickflashLED();
      }
      while (Loop == 1);

      // flash the visible LED on PB0  4 times to indicate that we're done
      delay_ten_us(65500); // wait maxtime
      delay_ten_us(65500); // wait maxtime
      quickflashLEDx(4);

    }

    void loop() {
      if (digitalRead(TRIGGER) == 0) {
        sendAllCodes();
      }
    }

    /****************************** LED AND DELAY FUNCTIONS ********/

    // This function delays the specified number of 10 microseconds
    // it is 'hardcoded' and is calibrated by adjusting DELAY_CNT
    // in main.h Unless you are changing the crystal from 8mhz, dont
    // mess with this.
    void delay_ten_us(uint16_t us) {
      uint8_t timer;
      while (us != 0) {
        // for 8MHz we want to delay 80 cycles per 10 microseconds
        // this code is tweaked to give about that amount.
        for (timer=0; timer <= DELAY_CNT; timer++) {
          NOP;
          NOP;
        }
        NOP;
        us--;
      }
    }

    // This function quickly pulses the visible LED (connected to PB0, pin 5)
    // This will indicate to the user that a code is being transmitted
    void quickflashLED( void ) {
      digitalWrite(LED, HIGH);
      delay_ten_us(30);       // 30 millisec delay
      digitalWrite(LED, LOW);
    }

    // This function just flashes the visible LED a couple times, used to
    // tell the user what region is selected
    void quickflashLEDx( uint8_t x ) {
      quickflashLED();
      while(--x) {
        delay_ten_us(DELAY);  // 150 millisec delay between flahes
        quickflashLED();
      }
    }

When I try compile and upload to my Arduino Mega 2560, I get this error

    In file included from main.h:9:0,
                     from TVB.pde:21:
    TVB:78: error: variable 'NApowerCodes' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
    TVB:79: error: variable 'EUpowerCodes' must be const in order to be put into read-only section by means of '__attribute__((progmem))'
    variable 'NApowerCodes' must be const in order to be put into read-only section by means of '__attribute__((progmem))'

Is there any way I can fix this?

body:
Try:

    extern  PGM_P * const NApowerCodes[] PROGMEM;
    extern  PGM_P * const EUpowerCodes[] PROGMEM;

The definition of PGM_P is:

    #define PGM_P const char *

which gives "const const" and gives "error: duplicate 'const'". But it is the variable that should be const.

Cheers!


message:
How to add .h file in library

I am trying to make an ultrasonic distance meter using Arduino. For this I added the ultrasonic library. But on compiling it shows this error "ultrasonic.h
not available". Please tell me how to add this .h file.

body:
In you Arduino Sketch folder there is a folder called **Libraries**, create a folder there and put your header file in that folder and restart the Arduino IDE.

For example (PC):

    Documents/Arduino/Libraries/ultrasonic/ultrasonic.h

You can now use it in all your projects.

If you only want to use with a particular sketch, place in in the same folder as you  sketch and restart Arduino IDE.


message:
2 way communication between Arduino with XBee and Computer

I have an Arduino Uno with a Wireless SD Shield and XBee S1 and a PC with another XBee S1 connected to it. What I'm after is for me to be able to send a message from my computer and receive a message back from the Arduino (For now let's just say if the Arduino receives a "1" I want it to send an "A" back)
Here is the code I have been practicing with (courtesy of SparkFun)

<!-- language: c -->

    #include <SoftwareSerial.h>
    SoftwareSerial XBee(0, 1); // RX, TX

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

    void loop() {
      if (Serial.available()) {
        XBee.write(Serial.read());
      }
      if (XBee.available()) {
        Serial.write(XBee.read());
      }
    }

(I have changed the pins from 2,3 to 0,1 as the latter is on the Arduino itself)
I have set my Xbees up and have been able to get them to talk to each other when both connected to separate PC's, but I am having trouble getting the Arduino to send information to the other XBee. When I try and send data from the Arduino IDE both RX and TX Led's flash.
Could anyone steer me in the right direction?

body: You don't need to declare an extra (software) serial port because the wireless shield connects the Arduino TX and RX on pins 0 and 1 directly to the TX and RX of the Xbee. So, Serial.available, Serial.read and Serial.write directly addresses the xbee. Just leave out the software serial from your code and it should work.


body: Pin 0 and 1 are the Hardware Serial of Arduino you cannot use it as the software serial and I also used that code once use pin 2 and 3 its issue regarding the configuration of your XBEE? Check your XBEE configuration XCTU


message:
How to reset arduino Mega 2560 code automatically?

I am working on the temperature project using arduino to collect temperature. But sometimes arduino hang there so I have to unplug cord and plug it back in to restart the arduino. I do not when it is going to hang up again. So I decide to do some research on the internet but no luck for that. Here is [the article][1] I read about resetting arduino code with watchdog timer library.(unfortunately, it only work for arduino uno) If someone has any idea how to reset arduino mega 2560 code. Please help !!

  [1]: http://sysmagazine.com/posts/189744/

body:
You could also use an external circuit to reset the arduino when 'heartbeat' pulses are missed. You can even detect when a reset has occured and report accordingly. See [here][1] for an example

  [1]: https://github.com/Bra1nK/HomeMonitor/tree/master/External Watchdog


body:
avr-libc already has the appropriate functions created for you. Just include [`<avr/wdt.h>`](http://www.nongnu.org/avr-libc/user-manual/group__avr__watchdog.html).

Sample usage

    #include <avr/wdt.h>

    void setup()
    {
       wdt_enable(WDTO_8S);
       ...
    }

    void loop()
    {
       wdt_reset();// make sure this gets called at least once every 8 seconds!
       ...
    }


body:
I tried Gerben's suggestion with a display:

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

    #include <avr/wdt.h>

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();
      Serial.println (F("Code starting ..."));
      wdt_enable(WDTO_8S);
      }  // end of setup

    void loop()
    {
    //   wdt_reset();// make sure this gets called at least once every 8 seconds!
    }

That does indeed print "Code starting ..." every 8 seconds or so.

> But sometimes arduino hang there so I have to unplug cord and plug it back in to restart the arduino.

You are better off working out **why**. There is probably a bug. Fix the bug rather than just restarting the Arduino.


message:
How to directly solder wires to protoshield to connect them to Arduino pins

I bought an assembled Arduino Uno protoshield version 5, similar to this:

![enter image description here][1]

I bought it because I would like to solder wires from Arduino IOs, and I was quite disappointed with the impossibility to do so, since the solder points are already taken by the female headers, which are not connected to anything (there are not tracks coming from then to other islands, which I find quite dumb).

I am considering to remove (by desoldering) the headers, so I can access the holes for soldering wires (instead of plugging them to headers), but before doing so, I ask:

> Is there a good way to solder wires so they are electrically connected to the Arduino IO pins?

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

body: For the signals, get some AWG30 wire and solder them underneath to the female header pads. For power, get some AWG22 or AWG24 wire and solder them to the top of the male header pads.


body:
Other boards bring the header pins to prototype area pins, as I do here
<http://www.crossroadsfencing.com/BobuinoRev17/UnoScrewSheild2016.jpg>
[![enter image description here][1]][1]

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


body:
It looks like you are missing the solder-less breadboard piece for your shield. The shield I bought came with one, and some 2 sided sticky "foam tape" to affix it to the circuit board.

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

If you use the shield with the solder-less breadboard, then it would be not be feasible to stack another shield on top of it because of the height of the components and jumper wires plugged into it.

I tested my shield and found the same thing you did, the header pins are not connected to any of the connection points on the board. That is dumb indeed.

As CrossRoads mentioned in his answer, there are other options, such as screw terminal shields. They sell them for $2.43 USD on aliexpress.com [Screw Terminal Shield][2].

  [1]: https://i.stack.imgur.com/9m6gJ.png
  [2]: https://www.aliexpress.com/item/Free-shipping-Proto-Screw-Shield-Assembled-prototype-terminal-expansion-board-for-Arduino/32382374867.html?spm=2114.search0104.3.86.acbb5c137Lx2Jl&ws_ab_test=searchweb0_0,searchweb201602_3_10152_10151_10065_10344_10068_10130_10342_10547_10343_10340_10548_10341_10696_10084_10083_10618_10139_10307_5711215_10313_10059_10534_100031_10103_10624_10623_443_10622_5711315_10621_10620_5722415,searchweb201603_37,ppcSwitch_5&algo_expid=ec60efcb-f288-4925-ac2c-2672760191ae-12&algo_pvid=ec60efcb-f288-4925-ac2c-2672760191ae&transAbTest=ae803_4&priceBeautifyAB=0


message:
What is the best way to make a good but simple line follower?

I am new in this site, and like you can see I want to do a line follower, not a clumsy and slow line follower, but a fast and "fancy".
I investigated about the PID method, but can someone explain me in simple words what is it.
Thanks for your answers.

body:
Did you check wikipedia, for example?

I doubt it is possible to describe a PID controller in simpler words than those used by [the article][1].

The [pseudocode][2] is quite simple and should be also very good for understanding the concept, when applied to a digital system.

See also the [limitations][3] of PID controllers.

  [1]: https://en.wikipedia.org/wiki/PID_controller
  [2]: https://en.wikipedia.org/wiki/PID_controller#Pseudocode
  [3]: https://en.wikipedia.org/wiki/PID_controller#Limitations_of_PID_control


message:
Velocity from Sensor Data - Best Approach?

I am attempting to develop a control system based upon rocket velocity. My first step is attempting to properly filter my sensor data in order to calculate velocity.

What is the best approach to get accurate, smooth, and fast data to my control logic?

Would I benefit from combining accelerometer and barometric data? If so, how?

----------

Background:

I am currently only using a BMP180 barometer to get altitude and then calculating velocity from the last altitude measurement. I am operating the BMP180 on ultra low power to increase the sample rate, but that comes at a cost of a RMS noise of around 0.5 meters.

Using 1D Kalman filtering I can get it smoothed out somewhat (tried on both velocity and altitude), but it is still not anywhere near as smooth as I need for my control system. It also lags behind the data far too much when I get it smoothed.

I have attached an example of what I have done with Kalman filtering. The original data is from a Featherweight Raven altimeter. I used the reported altitude data to calculate velocity (standard deltX/deltT) for each iteration, filtered it, and compared it with the Raven's own calculated velocity from it's accelerometer. The altitude data is at 20 Hz which is about what I am achieving with my Arduino setup right now.

![Kalman Filtering Result][1]

Thanks!

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

body:
Welcome to the world of signal processing! (Starting off with a Kalman filter, though, is not very welcoming).

The first few things to address are in regard to the barometer:

(1) Inevitably, it's going to be noisy, and barometers in particular are known to be noisy. Considering the unfiltered data you posted, I'd say it's reasonable. The spikes are completely normal, especially being that your calculating the derivative from the barometer data. If you want to try to smooth the barometer data *before* passing it to the Kalman filter, you could apply a nth order low pass filter to the sampled data. This, of course, would add more lag to your calculations - it's really a trade off.

(2) Looking at the unfiltered data and the velocity calculated from the Raven, it appears that there might be an issue. Starting at time 0, the unfiltered data and the Raven data is nearly identical. Once the rocket reaches 180ft/s, though, the filtered data appears to diverge. After it passes the global maxima and hits 180ft/s again, the two data outputs start to converge. This makes me suspect that your sampling rate may be too low. A hard-core, by the book, DSP engineer will probably start crying when he reads this, but consider this: at a velocity of 180ft/s with a sample rate of 20S/s, each sample corresponds to a change in position of 9ft. So, at best, you have a resolution of 9ft per second. This can pose at least two problems. (1) The barometer has to continuously update temperature and pressure readings in order to calculate an accurate altitude. I only glanced at the datasheet, but it seems like the temperature (and I think one other parameter) is updated at a slower rate than the pressure sampling - that is, there's an oversampling factor for the pressure measurement. Hence, your calculation may start to diverge from reality. And as the rocket's velocity increases, this problem may be exacerbated. Of course, temperature changes at rate of about 9.8C/1000m, so it may not be that significant of an issue. Just wanted to throw it out there.  (2) Again, at 180ft/s with a 20Hz sampling rate, you basically have a resolution of 9ft/S. This isn't necessarily bad, but one thing to keep in mind is that a Kalman filter is predictive; it predicts the state of the system 1/20 of a second into the future. If your underlying model is off, this could lead to slower convergence and larger corrections that would make the filtered data look "jerky."

Just one more thing before we get into the filter...

It's worth considering how you're implementing this on the Arduino. There shouldn't be any issues with computation time that could result in significant lag. If your only sampling the altitude at 20Hz and then feeding it to the filter at the same speed, you should be good to go. The only issue I can foresee is if you're using the Arduino Libraries. If you are, you'll probably run into bottlenecks and missed deadlines.

Anyway, the primary issue you're having - in my opinion - is not related to computational speed or hardware issues. Instead, I suspect it's your implementation of the filter.

One thing that stood out to me were your values of R and Q. R is the measurement noise covariance, and Q is the process noise covariance. Covariance ranges between [-1, 1]. Your Q = 5. I quickly scanned the link you provided, so I might have missed a simplification they did. I've seen in some cases that the covariance is simplified to a proportional expectation value and left unnormalized, similar to what's seen in Gram matrices.

Regardless, here's some insight that may be useful:

The Kalman filter is *very* much dependent on how you model your system.

To illustrate this, let's consider an example analogous to your rocket. (I came across this example at some point, but I don't recall the source):

Say you want to measure the water level in a bucket, but you have a sensor that gives you noisy data. And of course, to filter the data, you decide to use a 1-D Kalman filter.

We assume that we have a pretty accurate model of our system, so we'll let Q = 0.001. We iterate through the filter, and we may get data that looks like this:
![enter image description here][1]

The filter works fairly well.

But what if our model happened to be off - that is, it doesn't reflect what's really happening?

In the image above, the water level was constant. In reality, perhaps the tank was filling at a constant rate. What happens now if we use the same filter?

![enter image description here][2]

Clearly, the filter is diverging. The lag, as you call it, isn't really lag or a delay in the sense that the computation is slow. (In some ways it is a delay, but only in the mathematical sense that the filter is slowly converging). The "lag" effect we're seeing is due to our model. In essence, the filter we designed thinks our model is so good (as indicated by our low Q) that it gives greater weight to our model of the system. As you probably guessed, one way we can fix this problem is by increasing Q. So, let Q = 0.1:

![enter image description here][3]

You can keep increasing Q, and when Q = 1, your filtered data should actually match your measurement data.

This, though, really ins't the best way. Ideally, you need to start with a relatively accurate model. Q can be thought of as a measure of the error in your model, and you want to minimize error. At this point, you'll inevitable need to start work with matrices. This won't increase "lag." In fact, it should help your filtered data converge quicker.

There is one more thing to note. Kalman filters prefer linear data (speaking generally here). Look what happens when you feed in nonlinear data:

![enter image description here][4]

To accurately and effectively apply a Kalman filter to non-linear data without such pronounced "lag",  you need to use what is known as an extended Kalman filter - which basically linearizes your data.

Before you go down that route, which would probably be overkill, I would suggest improving your model used in your Kalman filter to better reflect it's true state. This means ditching the simplified filter you found and going into the matrix math.

In any case, I hope this helped. Feel free to ask any questions.

(Another method just crossed my mind that may be a simpler approach than a Kalman filter. I'll add it tomorrow).

  [1]: https://i.stack.imgur.com/yOcHi.png
  [2]: https://i.stack.imgur.com/gTe6Z.png
  [3]: https://i.stack.imgur.com/40nDO.png
  [4]: https://i.stack.imgur.com/WMnJH.png


body: You can use Excel to smooth out data and do graphs if you need to. That's what I use myself. Easiest way is to create a table and type formula to make average from range of numbers, smoother data needs a bigger range of numbers.


message:
How to read/write variables persistenly on Arduino Due (no EEPROM/shield)?

I am relatively new to Arduino and I am currently writing some code to control a relay board. The on/off times are provided by the user at run-time and should be stored persistently (EEPROM or flash) in case of power-down.

On my Uno I worked with the EEPROMex library and that worked well. Now I have a Due which doesnt have any EEPROM and I am struggling how to store variables persistently. Specifically, I dont know how to access whatever I wrote to the flash memory previously. In the example below the content of test[] is obviously overwritten on every restart.

    PROGMEM int test[] = {1, 2, 3, 123, 23};

    void test()
    {
      Serial.println((long)test);
      for (int i = 0; i < 5; i++)
      {
        Serial.println(test[i]++);
      }
    }

I noticed that the address does not change during re-starts, so I I tried reading/writing beyond index 4. This out-of-bounds read/write worked, I guess since I am anyway not storing anything else. Interestingly even this memory which is out of the array is overwritten on power-up.

So: How do I store on unser input data (variables) persistenly on an Arduino due without using any shields?

body:
I really hope that somebody knows differently, but I'm fairly sure that the answer is that you can't directly save runtime data back to the Arduino Due board.  I've looked into this myself and have only found answers saying "wire up an external EEPROM" or similar.  Whilst it seems that it should be technically possible to write into unused (or pre-reserved) areas of the program memory, I suspect that the CPU has to be put into a special mode to do this, which is very probably only possible from the bootloader when flashing a new program to it.

I've chosen to go with FRAM chips for data storage. [Link to mine.][1]  They are difficult to wire up - the only ones I found were in surface mount packages (although some hobby retailers sell them mounted to little boards with header pins), but they are very cheap, very durable (you can write to them a great number of times before they wear out), operate at high speeds and you can read/write single bytes from/to them.  Other storage chips often require you to write whole "pages" of data at a time which can mean reading in the existing data, modifying it, then writing it back.

Additional comments:
In your original question, you state that the contents of your PROGMEM located array must be restored on restarts.  I don't think this is the case.  That would suggest that the contents are stored elsewhere and code is in place to overwrite them, however it could be the case that they are copied into working RAM, which would mean that the PROGMEM macro is not actually doing anything on the Due - which may well be the case.

Modify your code to change one of the values of the array (within the bounds of the array!) and then print its value out again after changing it.  If the value printed has changed then this means that PROGMEM is not actually doing what it is supposed to do on the Due, which would be a real shame.

  [1]: http://uk.rs-online.com/web/p/fram-memory-chips/7332240/


body:
Without an external device you won't be able to store data permanently. So it might not be a full shield, but you'll have to add SOMETHING. Depending on how much data you need you might use components that have EEPROM as a side feature. For instance, as explained [here][1], the DS1337 RTC module has 56 spare bytes of EEPROM^H^H^H^H^H^H Non-Volatile RAM available. I know, it sure isn't much, BUT it might be enough for your needs, depending on how much you need to store.

And of course it provides you with DateTime capabilities, wich could come in handy.

Aside from this, there are EEPROM chips mounted on a small board, with DIP switches to set the I2C address, which would be very discrete, and could store a large amount of data. See [this one][2] for instance.

  [1]: https://kongduino.wordpress.com/2014/01/19/rtc_spare_memory/
  [2]: http://www.emartee.com/product/41949/Arduino-EEPROM-Shield-With-512K-AT24C512


body:
This library called DueFlashStorage was created by Sebnil and is in the Arduino Library Database Tool!

It basically takes the EEPROM functionality and applies it to the Flash storage on the DUE. The only drawback is that the flash memory gets erased every time you upload a new (or new version of a) sketch.

For my application that works but for other applications that might not be what you want!

[Click here to go to the GitHub for it called DueFlashStorage][1]

  [1]: https://github.com/sebnil/DueFlashStorage


message:
Why is this returning the wrong answer?

Why does this print output -3? xpos can be any value.

    void loop() {
    xPos = analogRead(xPin);
    yPos = analogRead(yPin);
    pwm = xPos*(255/1023);
    Serial.println(pwm);

    }

body:
The problem is that `(255/1023)` is being treated as an integer calculation, meaning the result gets truncated to 0. You can make the compiler promote it to a floating-point calculation by explicitly making at least one of the values floating-point. For example:

    pwm = xPos*(255.0f/1023.0f);


body:
The previous answer correctly suggested writing

    pwm = xPos*(255.0f/1023.0f);

in place of the original form `pwm = xPos*(255/1023);`.  But because 255/1023 - 1/4 = -1/1364 which is fairly small (ie it differs by 1 part in 1364), just saying

    pwm = xPos/4;

will usually give the correct result or nearly so.

Note, the following python program shows that this result is exact 514 times as xPos ranges from 0 to 1023, and is one too large 510 times, which for many processes being controlled by PWM signals is close enough.

    #!/usr/bin/env python
    c = [0]*8
    for i in range(1024):
        vf = int(i*255.0/1023.0)
        vi = i/4
        d = vi-vf
        c[d+3] += 1
        #print '{:5} {:5} {:5} {:5}'.format(i, d, vi, vf)
    print c


message:
Serial3.available loop issue

I am trying to read information coming from an Atlas Scientific FLO30 chip.

The following code works fine in an individual sketch:

    String inputstring = "";                                                       //a string to hold incoming data from the PC
    String sensorstring = "";                                                      //a string to hold the data from the Atlas Scientific product
    String LPM="";
    float LPM_INT;

    boolean input_stringcomplete = false;                                          //have we received all the data from the PC
    boolean sensor_stringcomplete = false;                                         //have we received all the data from the Atlas Scientific product
    #define CIRC_PUMP_PIN 10 // circulation pump pin - high when on, low when off

    unsigned long previousMillis = 0;        // will store last time LED was updated

    // constants won't change :
    const long interval = 1000;

      void setup(){                                                                //set up the hardware
         Serial.begin(9600);                                                       //set baud rate for the hardware serial port_0 to 9600
         Serial3.begin(38400);                                                      //set baud rate for software serial port_3 to 9600
         inputstring.reserve(5);                                                   //set aside some bytes for receiving data from the PC
         sensorstring.reserve(30);                                                 //set aside some bytes for receiving data from Atlas Scientific product
         pinMode(CIRC_PUMP_PIN,OUTPUT);
         digitalWrite(CIRC_PUMP_PIN,HIGH);

    void loop(){

    unsigned long currentMillis = millis();

      if(currentMillis - previousMillis >= interval) {
        // save the last time you blinked the LED
        previousMillis = currentMillis;

                if(Serial3.available()>0){
                  while(sensor_stringcomplete==false){
            char inchar = (char)Serial3.read();                              //get the char we just received
                  sensorstring += inchar;                                          //add it to the inputString
                  Serial.println("adding to string");
                if(inchar == '\r') {sensor_stringcomplete = true;}               //if the incoming character is a <CR>, set the flag
                 }
                }

     if (sensor_stringcomplete){                                                   //if a string from the Atlas Scientific product has been received in its entierty
          Serial.println(sensorstring);                                            //send that string to to the PC's serial monitor
          byte n = sensorstring.length();
          LPM = sensorstring.substring(n-8,n);
          Serial.print("This is the extracted part ");
          Serial.println(LPM);
          LPM_INT=LPM.toFloat();
          Serial.print("Now in float ");
          Serial.println(LPM_INT);
          LPM="";
          sensorstring = "";                                                       //clear the string:
          sensor_stringcomplete = false;                                           //reset the flag used to tell if we have received a completed string from the Atlas Scientific product
          }

          if(sensor_stringcomplete==false){
           Serial.println("Skipping");

          }
      }

          }

however when I try to integrate the code with another master sketch, the Arduino seems to jam or lockup when it enters the following part of the code, which is called periodically from the main void loop():

        if(Serial3.available()>0){
          while(sensor_stringcomplete==false){
    char inchar = (char)Serial3.read();                              //get the char we just received
          sensorstring += inchar;                                          //add it to the inputString
          Serial.println("adding to string");
        if(inchar == '\r') {sensor_stringcomplete = true;}               //if the incoming character is a <CR>, set the flag
         }
            }

 All the code is the same and I do not understand why the Arduino locks up. I intially thought it was a problem with memory as the master code is singificantly bigger but the line  "sensorstring = "";  " and "sensorstring.reserve(30) " should take care of this? Besides it cannot even get one reading from the sensor.

Can anyone give insight as to why this might be?

body:
Firstly, don't use String.  It's wasteful of memory and the dynamic aspects of it don't sit well on a tiny resource-starved 8-bit microcontroller.

Secondly, your method of reading from the serial is flawed right from the start.

    if(Serial3.available()>0){

... If there is at least 1 character available ...

    while(sensor_stringcomplete==false){
        char inchar = (char)Serial3.read(); //get the char we just received
        sensorstring += inchar;     //add it to the inputString
        Serial.println("adding to string");
        if(inchar == '\r') {sensor_stringcomplete = true;} //if the incoming character is a <CR>, set the flag
    }

... read characters until I get the end of string character regardless of if those characters are even available.

In order to read the data from the serial port you have to ensure that the data is actually available.  Just waiting for the first character to arrive and then reading (much faster than the serial is able to receive) other characters is doomed to failure.

I have discussed this at great length in a blog article, including how to perform non-blocking string reads that will not interfere with the rest of your program: http://hacking.majenko.co.uk/reading-serial-on-the-arduino

It even mentions your specific situation since it is something that is so commonly done wrong.


message:
A question about the possible limits of an Arduino Uno

I've searched the web but could not find a straightforward answer to my query.

I am building a control board for one of my models and this time have decided to also include a computer interface, so I have incorporated an Arduino Uno into my project instead of just analog circuits. I'm not an electronics expert of any sort but I manage by applying basic logic and a lot of trial and error.

Anyway, I have a single Arduino. It is operating the following:

An LCD display,
a 4 button operation panel I made using an LS148 ic,
an L293 operating 2 small motors,
a servo,
a dark sensor,
a temperature sensor,
and it also does serial communication.

Everything is working great, but slow (or so it appears to me).

If i push a button it takes the board about a second to pick up on the signal while an external LED indicator shows the circuit using the LS148 is working as it should. (I basically chained the 1-4 inputs and checking the truth table on the board to determine which button was pressed). Or pick up on a signal sent from the dark sensor for example. It appears as if the whole code in the Arduino runs at a cycle of once per second. Also sending instructions from the computer.

When I disable the LCD code everything works fast(er) and so goes when I remove other parts. So my question is, have I overloaded it?

I am on the verge of ordering another board (which I am going to do anyway), but in this case it is purely due to my belief that if I connect the LCD with the whole display code onto one board and the rest of the sensors and chips to another it will solve my problem.

I haven't figured out yet if it's possible to link the two boards or how to do that, but once I'll get to that bridge I'll cross it as well.

Thanks for your advice.

body:
A lot of Arduino code is written either generally inefficiently, or written in completely the wrong way.

For instance, take the LCD code.  Commands have to be sent at the right speed with the proper delays in there for things to happen.  LCDs are actually quite slow devices to communicate with, and as a result the LCD code has a large number of delays in it.

Nothing else can happen while there's a delay() running.

Many other things will introduce their own delays.  Put them all together and you have a slow system.

No, you're not overloading it, you're slowing it down on purpose, and all those small slow-downs add up to one big grind.

There are other ways of doing these things, of course, which are far more friendly to the chip - things that don't require delays of any form.

For a start there is the millis() function which tells you the time.  Using that to know when to do things, instead of sitting waiting for them to happen, allows you to do so much more at once.

It's like boiling an egg.  Do you put the egg in boiling water and sit there staring at it for 3 minutes (or however long you like your egg cooking), or do you set the timer on your oven to alert you in 3 minutes time so you can go and do the ironing while the egg is boiling?

It's the same with Arduino programming.  Note the time, then check that time against the current time to see if the required time has passed.

Of course, with things like the LCD library, changing it to work that way would be quite a lot of effort.

There are also hardware timers.  These allow you to run small snippets of code at regular periods.  Great for managing things like servos or other motors where you only want to be changing the state or speed of them say 10 times per second. Instead of updating them all the time, just set a desired speed / position variable and let the timer interrupt update the actual motor at a lower rate.

There are two key phrases to take away here:

* Non-blocking.  That is basically writing routines that never wait for something to complete, but can check to see if it's time for something to happen.
* Asynchronous programming.  This is using things like timers to make things happen "outside" your main loop.


message:
Beginner here, trying to start learning arduino, which starter kit should I buy?

I'm really interested in arduino but I don't know much about it. I want to buy a starter kit to play with, but when I searched it on amazon, there are couple unofficial starter kit and a more expensive official one. So, can some one tell me the major difference between the unofficial starter kit and official starter kit? And which one would you recommend me to buy? Thank you!

Sorry, bonus question: why is the start kit([$89][1]) in arduino website is much cheaper than the official starter kit in amazon([$120][2])?

  [1]: http://store-usa.arduino.cc/products/arduino-starter-kit
  [2]: http://www.amazon.ca/Arduino-Starter-Official-170-page-Projects/dp/B009UKZV0A/ref=sr_1_1?ie=UTF8&qid=1435770992&sr=8-1&keywords=arduino starter kit

body:
I tend to recommend the [oomlout ARDX starter kit][1] to students at the university I work at as it is relatively low cost, widely available, and doesn't have too much cheap filler components that you don't use...

  [1]: http://oomlout.co.uk/collections/arduino/products/arduino-starter-kit-ardx


body:
You could do worse than a cheap [37-in-1 Sensor Kit](http://www.ebay.com/sch/i.html?_nkw=37-in-1+sensor+kit) from eBay and any Arduino board of your choice.

Also some [Dupont Jumpers](http://www.ebay.com/sch/i.html?_nkw=dupont+jumper+wire) are essential.  Get a selection of M/M, M/F and F/F.


message:
Sensing horizontal tilt

I'm building a digital gear shift knob, which would display current gear (1-5, R) and based on readings from OBD-II change color when gear shifting is required, to save on fuel consumption.

I need a way to detect the current gear - PID 0D (current gear) is not availiable in this car. I was thinking about doing it based on the horizontal tilt of the gear stick, since there are 6 positions plus a neutral gear:

        1   3   5
         \  |  /
          --0--
        /   |  \
       2    4   R

Is there a sensor I could use? Or perhaps it'd be possible to build one, e.g. using 6 of these ball switches: https://www.adafruit.com/products/173
There is however a space constraint since everything needs to fit inside a gear knob, therefore I'd prefer a nice single package.

body: You could also sense the position of the stick where it enters the floor with hall sensors... 1-5 and reverse would have sensors, neutral would be when none of the other gears are detected.


body:
Many vehicles with manual transmission use two push rods or cables to transmit gear selection to the gearbox. It may be easier to detect the position of those rods/cables than to attempt to filter out the g-forces involved in a moving vehicle.

Alternatively, you could use the ratio of vehicle speed to engine revs (if you can retrieve these from OBDII in your vehicle). Given that these two are directly related when a specific gear is selected and the clutch is engaged, a simple division should give you a ratio you could use to decide which gear is selected.


body:
Your stick goes into the chassis at some point.
Why not detect the position down there?
But to be sure to save fuel, you'd need to know the rpm/speed and especially the load of the engine. If you are going at a high gear and low speed you won't save fuel either, so the knob is not the right place to detect the gear in question.
Go for OBD, get the ratio of speed and rpm and get the load or injection quantities. If you go up the hill and select too high a gear, you won't be happy either.


message:
Remove Bootloader on Arduinos

I am trying to move from arduinos to AVR C. Would somebody know how to remove the arduino bootloader from the microcontroller? Is there a different process for the different atmega microcontrollers like the 32u4, 328, or 2560?

Thanks.

body: You don't "remove" the bootloader, you just ignore it.  When you program your new code with the hardware programmer of your choice it will just overwrite the bootloader code with your software's startup code.


message:
LED too dim when connected to digital output pin

I am making an attempt to put LED headlights in an RC car I am building. I want the headlights to turn on when I click circle on a PlayStation 4 Dual Shock controller.  I currently have it working except the LED is very dim and not near as bright as if I just power it from the 5v pin on the arduino board.  Since I want it to only turn on when circle is pressed I have it connected to digital pin 7.  Here is my code.  Any help would be much appreciated!

    /*
     Example sketch for the PS4 Bluetooth library - developed by Kristian Lauszus
     For more information visit my blog: http://blog.tkjelectronics.dk/ or
     send me an e-mail:  kristianl@tkjelectronics.com
     */

    #include <PS4BT.h>
    #include <usbhub.h>
    #include <Servo.h>

    // Satisfy the IDE, which needs to see the include statment in the ino too.
    #ifdef dobogusinclude
    #include <spi4teensy3.h>
    #include <SPI.h>
    #endif

    USB Usb;
    //USBHub Hub1(&Usb); // Some dongles have a hub inside
    BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
    Servo servo1;
    Servo servo2;

    /* You can create the instance of the PS4BT class in two ways */
    // This will start an inquiry and then pair with the PS4 controller - you only have to do this once
    // You will need to hold down the PS and Share button at the same time, the PS4 controller will then start to blink rapidly indicating that it is in paring mode
    PS4BT PS4(&Btd, PAIR);

    // After that you can simply create the instance like so and then press the PS button on the device
    //PS4BT PS4(&Btd);

    const int headlights = 7;
    bool printAngle, printTouch;
    uint8_t oldL2Value, oldR2Value;

    void setup()
    {
      Serial.begin(115200);
    #if !defined(__MIPSEL__)
      while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
    #endif
      if (Usb.Init() == -1)
      {
        Serial.print(F("\r\nOSC did not start"));
        while (1); // Halt
      }
      Serial.print(F("\r\nPS4 Bluetooth Library Started"));

      pinMode (3, OUTPUT);
      pinMode (5, OUTPUT);
      servo1.attach (3);
      servo2.attach (5);
    }
    void loop()
    {
      Usb.Task();

      if (PS4.connected())
      {
        servo1.write(map(PS4.getAnalogHat(RightHatX), 0, 255, 50, 0));
        servo2.write(map(PS4.getAnalogButton(R2), 0, 255, 90, 0));
      }
      else
      {
        servo1.write (25);
        servo2.write (90);
      }

      if (PS4.getAnalogHat(LeftHatX) > 137 || PS4.getAnalogHat(LeftHatX) < 117 || PS4.getAnalogHat(LeftHatY) > 137 || PS4.getAnalogHat(LeftHatY) < 117 || PS4.getAnalogHat(RightHatX) > 137 || PS4.getAnalogHat(RightHatX) < 117 || PS4.getAnalogHat(RightHatY) > 137 || PS4.getAnalogHat(RightHatY) < 117)
      {
          Serial.print(F("\r\nLeftHatX: "));
          Serial.print(PS4.getAnalogHat(LeftHatX));
          Serial.print(F("\tLeftHatY: "));
          Serial.print(PS4.getAnalogHat(LeftHatY));
          Serial.print(F("\tRightHatX: "));
          Serial.print(PS4.getAnalogHat(RightHatX));
          Serial.print(F("\tRightHatY: "));
          Serial.print(PS4.getAnalogHat(RightHatY));
      }

        if (PS4.getButtonClick(PS)) {
          Serial.print(F("\r\nPS"));
          PS4.disconnect();
        }

        else {
            if (PS4.getButtonClick(CIRCLE)) {
            Serial.print(F("\r\nCircle"));
            digitalWrite(headlights, HIGH);
            }

          if (PS4.getButtonClick(CROSS)) {
            Serial.print(F("\r\nCross"));
            digitalWrite(headlights, LOW);
          }

          if (PS4.getButtonClick(TRIANGLE)) {
            Serial.print(F("\r\nTraingle"));
            PS4.setRumbleOn(RumbleLow);
          }

          if (PS4.getButtonClick(SQUARE)) {
            Serial.print(F("\r\nSquare"));
            PS4.setLedFlash(0, 0); // Turn off blinking
          }

          if (PS4.getButtonClick(UP)) {
            Serial.print(F("\r\nUp"));
            PS4.setLed(Red);
          } if (PS4.getButtonClick(RIGHT)) {
            Serial.print(F("\r\nRight"));
            PS4.setLed(Blue);
          } if (PS4.getButtonClick(DOWN)) {
            Serial.print(F("\r\nDown"));
            PS4.setLed(Yellow);
          } if (PS4.getButtonClick(LEFT)) {
            Serial.print(F("\r\nLeft"));
            PS4.setLed(Green);
          }

          if (PS4.getButtonClick(L1))
            Serial.print(F("\r\nL1"));
          if (PS4.getButtonClick(L3))
            Serial.print(F("\r\nL3"));
          if (PS4.getButtonClick(R1))
            Serial.print(F("\r\nR1"));
          if (PS4.getButtonClick(R3))
            Serial.print(F("\r\nR3"));

          if (PS4.getButtonClick(SHARE))
            Serial.print(F("\r\nShare"));
          if (PS4.getButtonClick(OPTIONS)) {
            Serial.print(F("\r\nOptions"));
            printAngle = !printAngle;
          }
          if (PS4.getButtonClick(TOUCHPAD)) {
            Serial.print(F("\r\nTouchpad"));
            printTouch = !printTouch;
          }
         }
        }

body: You forgot to set `headlights` as an output, meaning that you're attempting to power the LED through the 20k-50kohm input pullup.


message:
avrdude: stk500v2_getsync(): timeout communicating with programmer error

When I try to upload I get this error. I cannot upload the program into my Arduino Mega ADK board. I tried putting the drivers agiain too, but it does not work.

    avrdude: stk500v2_getsync(): timeout communicating with programmer

Is it the problem with the hardware or the system?
Please help me. Thank you :)

body:
I get this problem sometimes with some of my boards. I usually solve the problem following these steps:

 - Set the compiler on debug/verbose mode to see what's happening
 - Launch compilation/upload
 - When the compile phase is done, and the upload process is about to start, press the reset button on the board

Usually that takes care of the problem.


body:
What @dda says in his answer are good points.

Removing the board USB for a few seconds, then re-plugging and re-selecting the COM port in the IDE usually fixes it.  Sometimes when you un-plug and re-plug the board it changes COM ports.

Also if you have a short-circuit wired to your arduino sometimes it becomes non-responsive in this manner.


message:
Attiny45 wake by Software Serial

I would like to wake Attiny45 from sleep by Serial communication. RX is connected to pin 7 (D2). When I try to use PCINT0_vect routine, I get an error "multiple definition of `__vector_2'" so it looks like Software Serial already uses "ISR (PCINT0_vect)" and pin change interrupt.

So my question is, will incomming communication wake Attiny from sleep?

Is there a possibility to change CLKPR when Attiny starts receiving? For example I set clock divider to 256 for the majority of time and when it starts receiving it changes back to 1.

I was thinking of something like this:

    void loop() {
     if (SWSerial.available()>0) {
       noInterrupts ();
       CLKPR = bit (CLKPCE);
       CLKPR = clock_div_1;
       interrupts ();
     }
    //other code here
    }

I don't mind loosing some bytes, but I need to low Idle current as much as possible.
Thank you.

body:
# Question #1: Can a change on pin 7 wake from sleep?

Yes. The lowest power mode for this chip is `Power-down`, and you can wake from this state with a pin change interrupt. Assuming that the soft-serial code you are using already enables interrupts on the pin for its own purposes, then you should just be able to sleep and the part will wake on the next pin generated interrupt.

Depending on what compiler/libraries you are using, something like this...

    include <avr/sleep.h>

    ...

    set_sleep_mode(SLEEP_MODE_PWR_DOWN);
    sleep_enable();
    sleep_cpu();
    //We will only reach this line after an interrupt has occured

...should work. Note that an interrupt when waking from sleep takes longer than when already running, so you'll need to check your soft serial library to see if it will possibly garble the first bit received- it will depend on how they do their timing.

If you really want the lowest power possible, you could write your own soft serial code that drops the processor to idle in between serial bit transitions. Depending on how much time you will be spending actually receiving data this could drop overall power consumption dramatically.

For low baud rates, I could imagine writing serial receive code that woke on an interrupt from the start bit, and used the timer running at a very low clock speed to wake up in the middle of each data bit and very quickly sample and shift the bit in before going idle again. Done right, this could dramatically drop the power used while receiving.

# Question #2: Is there a possibility to change CLKPR when Attiny starts receiving?

Yes. You can change the prescaler any time, but note that...

1. The clock is not running at all during `power-down` mode, so there is no reason to scale back before going to sleep - it will just mean that it takes you longer to wake up when a change happens.

2. Sometimes scaling back the clock can actually use more power, especially when sleeping is envolved. A processor running 1/2 as fast uses more than 1/2 as much power, so it is often more power efficient to wake up at full speed, do what you have to do as fast as possible, and then get back to sleep.

The best option for you will depend on factors like how often will you be receiving data compared to waiting for data, and how much work you wan to put into getting optimal power usage. This chip can be *extremely* power efficient, but it can take work to take advantage of it.


message:
Digital pin input stays high after receiving a high signal

I don't know why but when a pin set to input mode receives a high signal, then a low signal, it stays high for a seemingly random amount of time.

<!-- language-all: lang-C++ -->

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
    int thermPin = A5;
    int relayPin = 9;
    int upButton = 10;
    int downButton = 11;
    int rawVoltage;
    float mv;
    float desiredTemp = 20.5;
    float currentTemp = 20;
    long newSetTime = millis();
    long oldSetTime = newSetTime;
    long newUpPushTime = millis();
    long newDownPushTime = millis();
    long oldUpPushTime = millis();
    long oldDownPushTime = millis();
    int mainDelay = 600;
    int flashDelay = 600;
    boolean isSetting = true;

    void drawCurrentTemp(){
      lcd.setCursor(0, 1);
      lcd.print(currentTemp);
    }

    void drawDesiredTemp(){
      lcd.setCursor(12, 1);
      lcd.print(desiredTemp);
    }

    void drawMainScreen(){
      lcd.clear();
      lcd.setCursor(0, 0);
      lcd.print("TEMP");
      lcd.setCursor(12, 0);
      lcd.print("SET");
      drawCurrentTemp();
      drawDesiredTemp();
    }
    String setString = "SET";
    void flashSet(){
      if(newSetTime - oldSetTime > flashDelay) {
        if(setString == "SET"){
          setString = "   ";
        }else{
          setString = "SET";
        }
        lcd.setCursor(12, 0);
        lcd.print(setString);
        oldSetTime = millis();
      }
    }

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      lcd.begin(16, 2);
      lcd.clear();
      pinMode(relayPin, OUTPUT);
      pinMode(upButton, INPUT);
      pinMode(downButton, INPUT);
      drawMainScreen();
    }

    void checkInput(){
      if(digitalRead(upButton) == HIGH){
        newUpPushTime = millis();
      } else {
        oldUpPushTime = millis();
      }
      if(digitalRead(downButton) == HIGH){
        newDownPushTime = millis();
      } else {
        oldDownPushTime = millis();
      }
      long upButtonTimePushed = newUpPushTime - oldUpPushTime;
      long downButtonTimePushed = newDownPushTime - oldDownPushTime;
      if(upButtonTimePushed > 1000 && downButtonTimePushed > 1000) {
        oldDownPushTime = millis();
        oldUpPushTime = millis();
        if(!isSetting){
          isSetting = true;
        } else {
          isSetting = false;
          drawMainScreen();
        }
      }
      if(isSetting){
        if(digitalRead(upButton) == HIGH) {
          desiredTemp +=0.5;
        } else if(digitalRead(downButton) == HIGH) {
          desiredTemp -=0.5;
        }
        drawDesiredTemp();
      }
    }

    void loop() {
      newSetTime = millis();
      if(isSetting) {
        flashSet();
      }
      checkInput();
      Serial.println(digitalRead(upButton));
    }

body:
*Comment by Glen Cashen turned into an answer*:

I just found out about the pullup resistors and how exactly the INPUT works it's all fixed now thanks :)

I just made them:

     pinMode(pin, INPUT_PULLUP);


body:
I ran across this post and thought that a more in depth explanation should be given on why when using digital inputs that more times than not you will need to use the pull-up resistors.

When you define one of the pins to be a input the chip measures the voltage on the pins, if the voltage measures more than half of the VCC voltage the input is off. What happens if you don't use a Pull-up Resistor the chip will measure a seemingly random voltage. This is because of interference from other electronics, radio waves etc.

So what happens when you use a high resistance Resistor (10 - 100 ohms) it forces the voltage to remain high if the pin is not grounded since there is voltage being applied. But when you ground the pin using a Button or whatever the pin is kept under the halfway mark around 0V.

As you mentioned using the code:

    pinMode(PIN, INPUT_PULLUP);

enables the internal Pull-Up Resistors in the chip by setting the Pin to a High state like you would defining it as a output. The code above is a newer way of writing:

    pinMode(PIN, INPUT);
    digitalWrite(PIN, HIGH);

Now there is another reason for seemingly random input signals, which is called "Button Bounce". What happens here is when a User presses the Button there might be a very small time that the Button actually connects then disconnects then finally reconnects. This is because of when the contacts of the Switch come together sometimes they don't connect perfectly, one side of the Switch might connect then be disconnected as the connecting plate levels out before finally connecting as it should.

Below is a Snapshot I found from http://www.gammon.com.au, it shows a bounce from a Osillicope showing the actual Button Bounce:

[![Button Bounce][1]][1]

To make sure that the user is actually pressing the button use a delay and recheck the Button again to see if it is still pressed. I find that a 500 - 700 microsecond delay works great. I provided a quick example on how to catch a Button Bounce (https://www.arduino.cc):

    // constants won't change. They're used here to
    // set pin numbers:
    const int buttonPin = 2;    // the number of the pushbutton pin
    const int ledPin = 13;      // the number of the LED pin

    // Variables will change:
    int ledState = HIGH;         // the current state of the output pin
    int buttonState;             // the current reading from the input pin
    int lastButtonState = LOW;   // the previous reading from the input pin

    // the following variables are long's because the time, measured in miliseconds,
    // will quickly become a bigger number than can be stored in an int.
    long lastDebounceTime = 0;  // the last time the output pin was toggled
    long debounceDelay = 50;    // the debounce time; increase if the output flickers

    void setup() {
      pinMode(buttonPin, INPUT);
      pinMode(ledPin, OUTPUT);

      // set initial LED state
      digitalWrite(ledPin, ledState);
    }

    void loop() {
      // read the state of the switch into a local variable:
      int reading = digitalRead(buttonPin);

      // check to see if you just pressed the button
      // (i.e. the input went from LOW to HIGH),  and you've waited
      // long enough since the last press to ignore any noise:

      // If the switch changed, due to noise or pressing:
      if (reading != lastButtonState) {
        // reset the debouncing timer
        lastDebounceTime = millis();
      }

      if ((millis() - lastDebounceTime) > debounceDelay) {
        // whatever the reading is at, it's been there for longer
        // than the debounce delay, so take it as the actual current state:

        // if the button state has changed:
        if (reading != buttonState) {
          buttonState = reading;

          // only toggle the LED if the new button state is HIGH
          if (buttonState == HIGH) {
            ledState = !ledState;
          }
        }
      }

      // set the LED:
      digitalWrite(ledPin, ledState);

      // save the reading.  Next time through the loop,
      // it'll be the lastButtonState:
      lastButtonState = reading;
    }

I hope that this explanation will help others out saving them from banging their heads against the wall trying to figure out where these phantom signals are coming from.

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


message:
How do I turn a number of pins to high and then off after 5 seconds based on a serial command

I have an Arduino sketch where I'm sending commands over serial, and as a result turning pins from low to high. What I'm looking to do is have those pins turn high for 5 seconds and then turn back to low. I was looking for a time or scheduling library for Arduino that allows multiple timers at once and lets you pass a parameter (at least I think that's what I need).

In other words, I would like to implement a "doAfter" method and pass the function it is calling a pin number.

body:
Have you tried the `delay()` function? Try putting this in the `loop()` function for pin 3.

    digitalWrite(3, HIGH);
    delay(1000); // time in milliseconds as parameter
    digitalWrite(3, LOW);


body:
You can use the [Timer library][1] to achieve this:

    #include "Timer.h"
    [...]
    digitalWrite(3, HIGH);
    int afterEvent = t.after(5000, doAfter);
    [...]
    void doAfter() {
      digitalWrite(3, LOW);
    }

As you can see, you cannot pass a parameter to the timer, just a callback. I suggest that you implement either a bunch of `doAfter` functions, from `doAfter3` to doAfter9` for instance, and call the right one in the callback.

There are probably other timer libraries, but this one is simple and complete enough for your needs.

  [1]: http://playground.arduino.cc/Code/Timer


message:
Scroll LCD display connected to an Arduino Uno

I want to make some characters scroll left without affecting the first positions in each row of my LCD 16x2 screen. I have this code inside the loop so far:

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

    lcd .clear();
    lcd.setCursor(17, 0);
    for (int i = 15; i > 0; i--) {
      lcd.print("x");
      lcd.scrollDisplayLeft();
      if (digitalRead(switchPin) == HIGH) {
        lcd.setCursor(0, 0);
        lcd.write(5);
      } else {
        lcd.setCursor(0, 1);
        lcd.write(5);
      };
      lcd.setCursor(17, 0);
      delay(500);
    }
    lcd.noAutoscroll();

I think it should work, but the character *x* just moves left by one position, whereas the character in the first position, either in the first or second row doesn't appear at all.

body:
I would do the following (beware - not tested):

    lcd.clear();
    lcd.setCursor(15, 0);
    lcd.print("x");
    for (int i = 0; i < 15; i++) {
        lcd.setCursor(0, digitalRead(switchPin) == LOW);
        lcd.print("5");
        delay(500);
        lcd.scrollDisplayLeft();
    }


message:
Use a PIR Sensor to detect the movements of a paper

I need to detect when a paper comes out from a laser printer and count the number of printed papers. For that I hope to use a PIR sensor to detect the movement of the paper from the printer. Is it possible to detect the movement of a paper using a PIR sensor? Please be kind enough to help me.

body:
If the paper is hot when it comes out of the printer, possibly.  Could be unreliable though.

Better would be to place a photo-interrupter (or IR LED and IR Photodiode) in the path of the paper to detect a break in an infra-red beam.


body:
The solution from the OP with the photo-interruptor is probably the most standard one.

However it might be worth checking if you can get away with a light sensor: assuming that the paper is mostly of different colour than the background, the paper should change the current passing through the photodiode.

Alternatively, you could use a proximity sensor, aimed at a location on the path of the paper, where there is typically nothing.

These 2 solutions are trying to avoid having to place something on both sides of the paper. If that doesn't bother you, then I'd recommend the OP's solution.


message:
What maximum length of wire can I use to connect a push button to an Arduino?

I am trying to get 8 stop buttons to cause an Arduino UNO to activate a single relay!

The stop buttons have been placed 30' to 250' away from the Arduino uno board.

Q: How far can you go with 5v and still get signal back?

Q: Is there a way to boost the signal?

body:
> Q: how far can you go with 5v and still get signal back?

That depends on two main factors:

1. The gauge of the wire
2. The noise in the environment

Assuming a low-noise (where noise is negligible) environment, we will first look at the wire.

All wire has an inherent resistance to it.  The thicker the wire, the lower the resistance.  This table has good information about the resistance of different gauges of wire: http://www.powerstream.com/Wire_Size.htm

Given a typical arrangement where the internal pullup resistor of the Arduino's IO pin is used to create an "active low" arrangement (`pinMode(x, INPUT_PULLUP`) the equivalent circuit can be seen as this:

![enter image description here][1]

Given that the "Input Logic Low" (VIL) level of an input pin (according to the [ATMega328P Datasheet](http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf) (Table 30-1) is 0.3Vcc, and Vcc is 5V, the input low level would therefore be 1.5V.  The voltage present at the IO pin has to be below 1.5V in order for the input to be seen as a LOW.

The circuit, when the button is pressed, can be simplified to this:

![enter image description here][2]

That is a simple voltage divider.  The formula for calculating Vout is (R2/(R1+R2))*Vin.  We know that the Vout limit is 1.5, and Vin is 5V.  Also that R1 is approximately 50KΩ (very approximately).  So we can rearrange the formula to:

R2 = R1(1/((Vin/Vout)-1))

Substituting our known values we have:

R2 = 50,000 × ( 1 / ((5 / 1.5) - 1)) = 21428.57Ω

So the total resistance of the wire permissible is around 20KΩ assuming the internal pullup resistor is 50KΩ (note: it could be as low as 10KΩ or as much as 70KΩ).

Divide that value by 2, since the wire has to run twice the distance (once there and once back again) and you get a total resistance of around 10KΩ for one leg of the journey.

Now assume a wire gauge of 24AWG.  That has a resistance of 84.1976Ω/km.  So we can work out that 10,000 / 84.1976 = 118.77km.

So with 24AWG wire you could theoretically have your button about 100km away from the Arduino and *just about* have it still register properly.

But of course that's with no noise, and there *will* be noise - especially over that kind of distance.

The noise will basically make the voltage seen at the input vary randomly around the theoretical value.  Those wires act like great big antennae, and they pick up all sorts of stray EMI.  The longer the wires the more noise there will be, and consequently the lower the voltage you will need to aim for (or higher voltage if using a pull-down arrangement - just turn the whole thing upside down) to keep the logic level below (or above) the right threshold value.

> Q: is their away to boost the signal?

Yes, you can use a higher voltage.  There is nothing to say that you have to interface your button directly with the Arduino.  There are many ways of having your button switch a higher voltage on and off and use that to trigger the Arduino.  The simplest (and also the safest) may be to use an opto-coupler.  Use your button(s) to switch a 12V power supply on and off, and that then passes through a suitable resistor to power the LED in the opto-coupler.  That then switches on the built-in transistor to turn on the IO pin.

![enter image description here][3]

Another option may be to use a reliable communication bus with a small microcontroller at each stop-button point (maybe something like RS-485), though that may be overkill for this kind of application.

  [1]: https://i.stack.imgur.com/FfPf6.png
  [2]: https://i.stack.imgur.com/9tIPx.png
  [3]: https://i.stack.imgur.com/Sib2l.png


body:
Majenko's answer is probably the safest option. There is, however,
something simpler that you can try:

* Use a strong pull-up (or pull-down). Something around 1 kΩ will
  make it quite difficult for the noise to pull your signal low, at the
  cost of increased current consumption.
* Connect each push button to the Arduino using a twisted pair of copper
  wires. This will minimize the inductive pickup effect.