body:
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?

title: Error compiling code (tv-b gone)

Answers: 1

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!


body:
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.

title: How to add .h file in library

Answers: 1

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.


body:
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?

title: 2 way communication between Arduino with XBee and Computer

Answers: 2

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


body:
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/

title: How to reset arduino Mega 2560 code automatically?

Answers: 3

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.


body:
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

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

Answers: 3

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


body:
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.

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

Answers: 1

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


body:
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

title: Velocity from Sensor Data - Best Approach?

Answers: 2

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.


body:
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?

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

Answers: 3

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


body:
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);

    }

title: Why is this returning the wrong answer?

Answers: 2

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


body:
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?

title: Serial3.available loop issue

Answers: 1

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.


body:
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.

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

Answers: 1

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.


body:
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

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

Answers: 2

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.


body:
More specifically, can I use an Arduino Due to have an interface that can plug in/out of a USB port on a computer, connect it to an SD card or similar via a sd card logging shield, and have it present itself as a flash drive to the computer?

Why do I want this as opposed to a normal flash drive? I would like the Arduino to also have access to the contents of the sd card when the computer interface is not plugged in (or rather controllable via the Arduino which device has access to the card, the Arduino or the computer), without the need to remove/disconnect the cable

title: Can I use an Arduino Due as a flash drive?

Answers: 0


body:
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.

title: Sensing horizontal tilt

Answers: 3

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.


body:
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.

title: Remove Bootloader on Arduinos

Answers: 1

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.


body:
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;
          }
         }
        }

title: LED too dim when connected to digital output pin

Answers: 1

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


body:
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 :)

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

Answers: 2

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.


body:
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.

title: Attiny45 wake by Software Serial

Answers: 1

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.


body:
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));
    }

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

Answers: 2

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


body:
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.

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

Answers: 2

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


body:
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.

title: Scroll LCD display connected to an Arduino Uno

Answers: 1

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();
    }


body: 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.

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

Answers: 2

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.


body:
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?

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

Answers: 2

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.


body:
I am new to Arduino, and I am working through the "Arduino Projects book," with the Arduino Uno. I am working on project 5, "the mood cue." It is basically a potentiometer-controlled servo. I am certain that I have the code for it correct, and certain that I have all the wiring correct. I have the potentiometer value and the angle at which the potentiometer is turned printed on the serial monitor.

I upload the code, and the serial monitor begins printing correctly, changing when I twist the potentiometer. But the servo doesn't move. It lets off a faint buzzing sound, and that is it.

Does anyone know what the problem is? I don't know what I have done wrong. Do you think my servo is broken?

Here is my code:

    #include <Servo.h>
    Servo myServo;
    int const potPin = A0;
    int potVal;
    int angle;

    void setup() {
      myServo. attach(9);
      Serial.begin (9600);
    }

    void loop() {
      potVal = analogRead(potPin);
      Serial.print ("potVal:");
      Serial.print (potVal);
      angle = map(potVal, 0, 1023, 0, 179);
      Serial.print ("angle:");
      Serial.print (angle);
      myServo.write (angle);
      delay(15);
    }

Here is my wiring:
file:///C:/Users/matth_000/Downloads/Arduino PotServ.jpg

title: Why is my "mood cue" not working?

Answers: 4

body:
The classic way of wiring up motors, including servos, is to provide them with separate power. The image below should clarify this:

![Wiring for servo motor][1]

The batteries (in this case) have the sole function of providing power to the servo motor. The "data" pin however goes to the Arduino.

The Arduino itself is powered by the USB cable in this example.

The **important** point is the blue wire - the shared ground wire. Both the Arduino and the servo (and batteries) must have a common ground.

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

body:
If you're using the components that came in the starter kit, the servo is wired differently in the book than it is in the actual kit.

Make sure the red wire on the servo is connected to the power, the black to the ground and the white to the data. The specs are also written on the side of the servo motor.

In the project book, the wires went into these rows on the breadboard:

26. GND
27. 5V
28. Signal

Whereas for me that meant it was:

26. GND
27. Signal
28. 5V

Hope this helps!

body: I'm new to arduino and I had the same problem of the servo buzzing but not moving.  I found the reason was the servo wires came in a different order than what was written in the book.  After correctly connecting the 5v, GND, and Signal by moving a few wires on the bread board things worked as planed.  Hoped this helps.

body:
At first, I had similar behavior with the servo motor in this project. The servo buzzed and either did not move or made very slight erratic movements.

**The problem in my case was that I had wrongly placed the wire that is supposed to connect the potentiometer to pin A0.**

Here's how my board looked *after* I corrected the problem:

![my mood cue circuit](https://i.stack.imgur.com/4ZQbC.jpg)


body:
I am Creating a laptop controlled robot using an arduino nano using the [instructbles][1]. I have tried running the code but it is throwing back lots off error and the main one is "expected primary expression before "<" token"

as well as various other error. if anyone could take a look and try help me out i would be grateful thank you!

    #include <NewPing.h>

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(11, 8, 7, 4, 3, 2);
    float temp =1;
    int temppin = A0;
    int r_motor_n = 9; //PWM control Right Motor +
    int r_motor_p = 10; //PWM control Right Motor -
    int l_motor_p = 6; //PWM control Left Motor -
    int l_motor_n = 5; //PWM control Left Motor +
    int f_light = A3;
    int b_light = A4;
    int horn = 12;
    int n_light = 13;
    int speedy = 255;
    int incomingByte = 0; // for incoming serial data
    #define TRIGGER A2 // Arduino pin tied to trigger pin on the ultrasonic sensor.
    #define ECHO A1 // Arduino pin tied to echo pin on the ultrasonic sensor.
    #define MAX 400 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
    NewPing sonar(TRIGGER, ECHO, MAX); // NewPing setup of pins and maximum distance.
    void setup()
    {
    pinMode(r_motor_n, OUTPUT); //Set control pins to be outputs
    pinMode(r_motor_p, OUTPUT);
    pinMode(l_motor_p, OUTPUT);
    pinMode(l_motor_n, OUTPUT);
    pinMode(f_light, OUTPUT);
    pinMode(b_light, OUTPUT);
    pinMode(n_light, OUTPUT);
    pinMode(horn, OUTPUT);
    digitalWrite(r_motor_n, LOW); //set both motors off for start-up
    digitalWrite(r_motor_p, LOW);
    digitalWrite(l_motor_p, LOW);
    digitalWrite(l_motor_n, LOW);
    Serial.begin(9600);
    Serial.println("Start");
    lcd.begin(16,2);
    lcd.clear();
    lcd.print("     Hello      ");
    lcd.setCursor(0,1);
    lcd.print("   I'm Robot   ");
    delay(3000);
    }
    void loop()
    {</liquidcrystal.h></newping.h>

if (Serial.available() > 0)
    {
    incomingByte = Serial.read();
    }

switch(incomingByte)
    {

case 'S': // control to stop the robot
    digitalWrite(r_motor_n, LOW);
    digitalWrite(r_motor_p, LOW);
    digitalWrite(l_motor_p, LOW);
    digitalWrite(l_motor_n, LOW);
    Serial.println("Stop");
    lcd.clear();
    lcd.print("Stop");
    incomingByte='*';
    break;

case 'R': //control for right
    analogWrite(r_motor_n, speedy);
    digitalWrite(r_motor_p, LOW);
    analogWrite(l_motor_p, speedy);
    digitalWrite(l_motor_n, LOW);
    Serial.println("right");
    lcd.clear();
    lcd.print("Right");
    incomingByte='*';
    break;

case 'L': //control for left
    digitalWrite(r_motor_n, LOW);
    analogWrite(r_motor_p, speedy);
    digitalWrite(l_motor_p, LOW);
    analogWrite(l_motor_n, speedy);
    Serial.println("left");
    lcd.clear();
    lcd.print("Left");
    incomingByte='*';
    break;

case 'F': //control for forward
    analogWrite(r_motor_n, speedy);
    digitalWrite(r_motor_p, LOW);
    digitalWrite(l_motor_p, LOW);
    analogWrite(l_motor_n, speedy);
    Serial.println("forward");
    lcd.clear();
    lcd.print("Forward");
    incomingByte='*';
    break;

case 'B': //control for backward
    digitalWrite(r_motor_n, LOW);
    analogWrite(r_motor_p, speedy);
    analogWrite(l_motor_p, speedy);
    digitalWrite(l_motor_n, LOW);
    Serial.println("backwards");
    lcd.clear();
    lcd.print("Backward");
    incomingByte='*';
    break;

case 'f': //control for stop
    digitalWrite(r_motor_n, LOW);
    digitalWrite(r_motor_p, LOW);
    digitalWrite(l_motor_p, LOW);
    digitalWrite(l_motor_n, LOW);
    Serial.println("Stop");
    lcd.clear();
    lcd.print("Stop");
    incomingByte='*';
    break;

case 'd': // control for right
    analogWrite(r_motor_n, speedy);
    digitalWrite(r_motor_p, LOW);
    analogWrite(l_motor_p, speedy);
    digitalWrite(l_motor_n, LOW);
    Serial.println("right");
    lcd.clear();
    lcd.print("Right");
    incomingByte='*';
    break;

case 'a': // control for left
    digitalWrite(r_motor_n, LOW);
    analogWrite(r_motor_p, speedy);
    digitalWrite(l_motor_p, LOW);
    analogWrite(l_motor_n, speedy);
    Serial.println("left");
    lcd.clear();
    lcd.print("Left");
    incomingByte='*';
    break;

case 'w': // control for forward
    analogWrite(r_motor_n, speedy);
    digitalWrite(r_motor_p, LOW);
    digitalWrite(l_motor_p, LOW);
    analogWrite(l_motor_n, speedy);
    Serial.println("forward");
    lcd.clear();
    lcd.print("Forward");
    incomingByte='*';
    break;

case 's': // control for backward
    digitalWrite(r_motor_n, LOW);
    analogWrite(r_motor_p, speedy);
    analogWrite(l_motor_p, speedy);
    digitalWrite(l_motor_n, LOW);
    Serial.println("backwards");
    lcd.clear();
    lcd.print("Backward");
    incomingByte='*';
    break;

case 'J': // front lights on
    digitalWrite(f_light, HIGH);
    Serial.println("front lights on");
    incomingByte='*';
    break;

case 'j':
    digitalWrite(f_light, LOW); // off
    Serial.println("front lights off");
    incomingByte='*';
    break;

case 'K':
    digitalWrite(b_light, HIGH); // back lights on
    Serial.println("back lights on");
    incomingByte='*';
    break;

case 'k':
    digitalWrite(b_light, LOW); // off
    Serial.println("back lights off");
    incomingByte='*';
    break;

case 'G':
    digitalWrite(n_light, HIGH); // neon lights on
    Serial.println("neon lights on");
    incomingByte='*';
    break;

case 'g':
    digitalWrite(n_light, LOW); off
    Serial.println("neon lights off");
    incomingByte='*';
    break;

case 'H':
    digitalWrite(horn, HIGH); // horn on
    Serial.println("horn on");
    incomingByte='*';
    break;

case 'h':
    digitalWrite(horn, LOW); off
    Serial.println("horn off");
    incomingByte='*';
    break;

case 'O': // PWM speed values
    speedy = 0 ;
    Serial.println("speed= 0");
    lcd.clear();
    lcd.print("Speed=0");
    incomingByte='*';
    break;

case '1':
    speedy = 155;
    Serial.println("speed= 10");
    lcd.clear();
    lcd.print("Speed=10");
    incomingByte='*';
    break;

case '2':
    speedy = 165;
    Serial.println("speed= 20");
    lcd.clear();
    lcd.print("Speed=20");
    incomingByte='*';
    break;

case '3':
    speedy = 175;
    Serial.println("speed= 30");
    lcd.clear();
    lcd.print("Speed =30");
    incomingByte='*';
    break;

case '4':
    speedy = 185;
    Serial.println("speed= 40");
    lcd.clear();
    lcd.print("Speed=40");
    incomingByte='*';
    break;

case '5':
    speedy = 195;
    Serial.println("speed= 50");
    lcd.clear();
    lcd.print("Speed=50");
    incomingByte='*';
    break;

case '6':
    speedy = 205;
    Serial.println("speed= 60");
    lcd.clear();
    lcd.print("Speed=60");
    incomingByte='*';
    break;

case '7':
    speedy = 215;
    Serial.println("speed= 70");
    lcd.clear();
    lcd.print("Speed=70");
    incomingByte='*';
    break;

case '8':
    speedy = 225;
    Serial.println("speed= 80");
    lcd.clear();
    lcd.print("Speed=80");
    incomingByte='*';
    break;

case '9':
    speedy = 235;
    Serial.println("speed= 90");
    lcd.clear();
    lcd.print("Speed=90");
    incomingByte='*';
    break;

case 'q':
    speedy = 255;
    Serial.println("speed= 100");
    lcd.clear();
    lcd.print("Speed=100");
    incomingByte='*';
    break;

case 'p':
    delay(50);  // display temp. and distance
    unsigned int uS = sonar.ping();
    Serial.print("Distance: ");
    Serial.print(uS / US_ROUNDTRIP_CM);
    Serial.println("cm");
    lcd.clear();
    lcd.print("Distance: ");
    lcd.print(uS / US_ROUNDTRIP_CM);
    lcd.print("cm");
    lcd.setCursor(0,1);
    temp = analogRead(temppin);
    temp = temp * 0.48828125;
    Serial.print("Temperature = ");
    Serial.print(temp);
    Serial.print("*C");
    Serial.println();
    lcd.print("Temp. = ");
    lcd.print(temp);
    lcd.print("*C");
    delay(1000);
    incomingByte='*';
    break;

delay(5000);
    }
    }

  [1]: http://www.instructables.com/id/Laptop-Controlled-Robot-v20/#step0

title: Error in code saying "expected primary expression before "<" token" and other errors

Answers: 1

body:
your code is ridden with html tags, like

`</p> <p>` or `</liquidcrystal.h></newping.h>`

Try removing them all, but it would be better if you could copy it from a plain ASCII source.

And when reporting a compiler bug, it's always good to paste it exactly as it is shown (it would have listed also line and possibly column where the error was detected)


body:
I am trying to write some code to make it easy to add different buttons to a touch screen. I need each object to be a different object of class 'touchButton'. I'd like to be able to run a `touchButton.Draw` function, which in turn will run LCD library commands. Is there a way I could do that? Here is my source code:

TouchScreen.ino:

    #include "touchButton.h"
    #include <UTFT.h>
    #include <UTouch.h>
    #include <avr/pgmspace.h>
    UTFT    myGLCD(ITDB32S, 38, 39, 40, 41);
    UTouch  myTouch( 6, 5, 4, 3, 2);
    extern uint8_t SmallFont[];

    void setup() {
      myGLCD.InitLCD();
      myGLCD.setFont(SmallFont);
      myGLCD.clrScr();
      myTouch.InitTouch();
      myTouch.setPrecision(PREC_MEDIUM);
      myGLCD.fillScr(51, 51, 51);
      //what I want to be able to do:
      //touchButton Button1 (10, 10, 20, 20, 'p');
      //Button1.Draw();
    }

    void loop() {
    }

touchButton.h

    #ifndef touchButton_h
    #define touchButton_h
    #include "Arduino.h"
    class touchButton {
      public:
        touchButton(int x, int y, int xs, int ys, char use);
        void Draw();
        int x1;
        int y1;
        int xsize;
        int ysize;
        char use;
        boolean toggle = false;
    };
    #endif

touchButton.cpp

      #include "Arduino.h"
      #include "touchButton.h"
      touchButton::touchButton(int x, int y, int xs, int ys, char myuse) {
        x1 = x;
        y1 = y;
        xsize = xs;
        ysize = ys;
        use = myuse;
      }

      void touchButton::Draw() {
        switch (use) {
          case 'p':
          //this is what I would like to have called from the main file.
          //myGLCD.drawRoundRect(x1, y1, x1+xsize, y1+ysize);
            break;

           default:
            break;
        }
      }

title: How can I reference an object from another file?

Answers: 4

body:
I'm not 100% certain I understand what you mean. It's clear that you understand object-oriented code and some of the murkier aspects of c++, judging from what you wrote.

I apologize if you already know this (and I'm guessing you do) or if this is completely off base, but your code should already work. That is, you defined your class in your header, implemented it in the .cpp file, and then instantiated it in the .ino file. If you want to operate on it in another file, you could declare the variable as an "extern" data type, which is rather dangerous, or pass it as a reference to a function in another file.

However, I don't believe this is what you mean. From reading your code, I feel that you're asking how you can execute function "x" from another object every time you create a button.

If this is the case, it's definitely possible. myGLCD looks like it's an object (can't read it at the moment), which is good. What you can do is declare your touchLCD class as a derived class of whomever myGLCD belongs to -adding the appropriate header of course:

    #include <Parent Class Name.h>

    class touchLCD : public <Parent Class Name>.

If the functions you want are public or protected, then you can access them without restriction. Here you have a few options. The easiest would probably be calling the function from within the constructor. If you don't have access to the desired function, you'll have to define your class as a friend class.

Hope this helps.

body:
The best way is to provide the myGLCD object as a parameter to the constructor:

    touchButton::touchButton(UTFT &glcddev, int x, int y, int xs, int ys, char myuse) {
      x1 = x;
      y1 = y;
      xsize = xs;
      ysize = ys;
      use = myuse;
      glcd = &glcddev;
    }

Then in your header you provide a:

    private:
      UTFT *glcd;

Your library code then uses the glcd pointer to the object:

    glcd->drawRoundedRectangle(...);

Note the use of `->` since `glcd` is a *pointer* to the object (as created by the `&` operator when it was assigned in the constructor).

Of course, as Miagma mentions, you need to ensure that anywhere that references any UTFT functions or objects has the UTFT.h header included or it won't know what you're talking about.

You can also do the same with the UTouch class - pass that object as a parameter, then each widget can have its own routine to deal with the touch events.

You can see all this kind of thing in action in the same context in the Widget class of my DisplayCore system for chipKIT boards:

  * https://github.com/MajenkoLibraries/DisplayCore/blob/master/DisplayCore/DisplayCore.h#L464
  * https://github.com/MajenkoLibraries/DisplayCore/blob/master/DisplayCore/DisplayCore.cpp#L1587

body:
You are asking a question that can be considered as the classical:

"is a" vs. "has a"

If you want, you can find more details [here][1].

On this specific case, I sort of agree with Majenko, that proposes to pass the address of the LCD object to each button, but I would prefer a different implementation where the pointer is stored in a static field shared by all the instances of touchButton, because you are always referring to the same object. That will of course change if you have more than 1 LCD.

  [1]: http://www.researchgate.net/post/What_is_a_difference_in_Is-a_and_has-a_relationship_of_inheritance_of_c

body:
The simplest solution (ignoring possible improvements) is to add the following to touchButton.cpp.

    #include "Arduino.h"
    #include "touchButton.h"

    // Extern reference to the LCD instance
    #include <UTFT.h>
    extern UTFT myGLCD;

    touchButton::touchButton(int x, int y, int xs, int ys, char myuse) {
      x1 = x;
      y1 = y;
      xsize = xs;
      ysize = ys;
      use = myuse;
    }

    void touchButton::Draw() {
      switch (use) {
        case 'p':
          myGLCD.drawRoundRect(x1, y1, x1+xsize, y1+ysize);
        break;

       default:
        break;
      }
    }

There are several improvements such as passing the UTFT instance reference as parameter, moving myGLCD to a separate .h/.cpp file, etc.

An example of "extern" object reference may be found in [HardwareSerial.h][1].

Cheers!

  [1]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/HardwareSerial.h#L143


body:
I am assisting some friends on an Arduino Uno project, and we've noticed that when using some earlier versions of the Arduino IDE (In this case 1.0.5), the sketch behaves as desired. However, when using 1.6.5, the program behaves differently. The sketch in question is here:

https://github.com/CymaSpace/Programs---Sketches/tree/master/Tim Gorbunov/a3 with monosetting/a3

I have noticed that when enabling verbose compilation output, the size of the compiled binary is different between the two different IDE versions. There are also some warnings in the older IDE that are not present in the newer version. There is at least one other version before 1.6.5 that is behaving the same way as 1.0.5 (it's a later version but at the moment I don't know which, I will see if I can find out and post it here later).

Any idea why the two sketches might be behaving differently and how to go about troubleshooting the problem? This occurred on both a windows and mac computer. Thanks!

title: Arduino sketch behaves differently depending on version of Arduino IDE

Answers: 1

body:
> There are also some warnings in the older IDE that are not present in
> the newer version.

It is a **huge** mistake to disregards those warnings, especially:

> warning: array subscript is above array bounds

You declared an array `int useColor[2]`. Its length is 2 and its indices
can be either 0 or 1. Yet you are using `useColor[2]`, which is out of
bounds and likely to corrupt memory.

From the language point of view, this is called _undefined behavior_,
which means that _anything_ can happen. In particular, it could very
well happen that the program behaves as you expect... which seems to be
the case with IDE 1.0.5. Simply changing the compiler version, or event
the compiler settings, can change the behavior.


body:
I am building a small-scale watering system to water my plants, controlled by Arduino. I have designed most of the project except for how to switch water between multiple pipes.

A little more background:

I want to be able to use a servo motor to control the amount of water that is sent to each plant (based on pot size and plant type). The motor needs to be able to switch input (a 1/2 inch pipe carrying water) to a set of outputs (similarly sized pipes all going to different plants). I am not able to find something off the shelf that does this. So, I am about to 3D print something. Is there something available that I can use instead?

title: Outlet switcher using servo motor

Answers: 2

body:
To me it would seem simpler to use a faucet for each line, each faucet controlled by a motor.
Then you can even water the plants in parallel.

Even better, why not using submersion pumps, like those used in water tanks? Here too, you can control them in parallel.
The amount of time you keep a motor running is proportional tothe amount of water delivered.

body:
As JRobert mentioned in a comment, you could use a [solenoid valve](http://www.ebay.com/sch/i.html?_odkw=solenoid+valve&_osacat=0&_from=R40&_trksid=p2045573.m570.l1313.TR0.TRC0.H0.TRS0&_nkw=solenoid+valve&_sacat=0), some of which you can get for about $5.

If you want to water one line at a time, get Normally Closed, one per line. Naturally, since most of them are 12v DC, you can't directly power them from your Arduino. You'll need some power transistors or some relays, and a 12v supply capable of steadily powering the solenoid.


body:
Using Visual Studio to program my Arduino. I want to add additional compiler switches and include paths.

How can this be done?

title: How do I add additional compiler switches in Visual Studio

Answers: 1

body:
Use the ExtraFlags in the project properties. The flags can be specified for the currently selected configuration or for all builds of the current project.

The feature was released in the 15.06 version of the [Visual Micro][1] Arduino plugin for Visual Studio.

This [guide][2] shows how to access the project properties

  [1]: http://www.visualmicro.com
  [2]: http://www.visualmicro.com/page/User-Guide.aspx?doc=Project-Properties-Reference.html