message:
Change code so motion sensor prints time instead of a button

I have the code below. At the moment there is a proximity sensor that makes a speaker play happy birthday when it is set off. I also have an LCD shield attached and when one of the buttons on LCD screens interface is pressed, the time that it was when the button was pressed prints on the screen. I need to get it so that when the proximity sensor is set off it plays the sound on the speaker and then prints the time which is was set off on the screen.

    /*--------------------------------------------------------------------------------------
     Includes
     --------------------------------------------------------------------------------------*/
    #include <Wire.h>
    #include <LiquidCrystal.h>   // include LCD library

    int timer = 1000;
    int C = 262;
    int D = 294;
    int E = 330;
    int F = 349;
    int G = 392;
    int A = 440;
    int B = 494;
    int Bflat = 466;
    int Chigh = 523;

    const int analogPin = A1;    // pin that the sensor is attached to
    const int threshold = 400;

    /*--------------------------------------------------------------------------------------
     Defines
     --------------------------------------------------------------------------------------*/
    // Pins in use
    #define MILLIS_OVERFLOW 34359738
    #define BUTTON_ADC_PIN           A0  // A0 is the button ADC input
    #define LCD_BACKLIGHT_PIN         3  // D3 controls LCD backlight
    // ADC readings expected for the 5 buttons on the ADC input
    #define RIGHT_10BIT_ADC           0  // right
    #define UP_10BIT_ADC            145  // up
    #define DOWN_10BIT_ADC          329  // down
    #define LEFT_10BIT_ADC          505  // left
    #define SELECT_10BIT_ADC        741  // right
    #define BUTTONHYSTERESIS         10  // hysteresis for valid button sensing     window
    //return values for ReadButtons()
    #define BUTTON_NONE               0  //
    #define BUTTON_RIGHT              1  //
    #define BUTTON_UP                 2  //
    #define BUTTON_DOWN               3  //
    #define BUTTON_LEFT               4  //
    #define BUTTON_SELECT             5  //
    //some example macros with friendly labels for LCD backlight/pin control,     tested and can be swapped into the example code as you like
    #define LCD_BACKLIGHT_OFF()     digitalWrite( LCD_BACKLIGHT_PIN, LOW )
    #define LCD_BACKLIGHT_ON()      digitalWrite( LCD_BACKLIGHT_PIN, HIGH )
    #define LCD_BACKLIGHT(state)    { if( state ){digitalWrite(     LCD_BACKLIGHT_PIN, HIGH );}else{digitalWrite( LCD_BACKLIGHT_PIN, LOW );} }
    /*--------------------------------------------------------------------------------------
     Variables
     --------------------------------------------------------------------------------------*/
    unsigned long currentMillis, previousMillis, elapsedMillis;
    int seconds = 0, minutes = 34, hours = 8;

    byte buttonJustPressed  = false;         //this will be true after a        ReadButtons() call if triggered
    byte buttonJustReleased = false;         //this will be true after a     ReadButtons() call if triggered
    byte buttonWas          = BUTTON_NONE;   //used by ReadButtons() for detection of button events
    /*--------------------------------------------------------------------------------------
     Init the LCD library with the LCD pins to be used
     --------------------------------------------------------------------------------------*/
    LiquidCrystal lcd( 8, 9, 4, 5, 6, 7 );   //Pins for the freetronics 16x2     LCD shield. LCD: ( RS, E, LCD-D4, LCD-D5, LCD-D6, LCD-D7 )
    /*--------------------------------------------------------------------------------------
     setup()
     Called by the Arduino framework once, before the main loop begins
     --------------------------------------------------------------------------------------*/
    void setup()
    {
      //button adc input
      pinMode( BUTTON_ADC_PIN, INPUT );         //ensure A0 is an input
      digitalWrite( BUTTON_ADC_PIN, LOW );      //ensure pullup is off on A0
      //lcd backlight control
      digitalWrite( LCD_BACKLIGHT_PIN, HIGH );  //backlight control pin D3 is     high (on)
      pinMode( LCD_BACKLIGHT_PIN, OUTPUT );     //D3 is an output
      //set up the LCD number of columns and rows:
       pinMode(13, OUTPUT);
      lcd.begin( 16, 2 );

      //Print some initial text to the LCD.
      Serial.begin(9600);
      lcd.begin( 16, 2 );

    }
    /*--------------------------------------------------------------------------------------
     loop()
     Arduino main loop
     --------------------------------------------------------------------------------------*/
    void loop()
    {

      setClock();
      byte button;

      button = ReadButtons();

      /**
       * After set clock now you have 3 int variables with the current time
       */
      //seconds
      //minutes
      //hours
      lcd.setCursor ( 0, 1);
      lcd.print(hours);
      lcd.print(":");
      lcd.print(minutes);
      lcd.print(":");
      lcd.print(seconds);
      lcd.print(":");
      lcd.print(elapsedMillis);

      //get the latest button pressed, also the buttonJustPressed,     buttonJustReleased flags

      //blank the demo text line if a new button is pressed or released, ready for a new label to be written

      //show text label for the button pressed
       if(buttonJustPressed || buttonJustReleased)
      switch( button )
      {

      case BUTTON_LEFT:
        {
          lcd.setCursor( 0, 0 );
                   lcd.print(hours);
                   lcd.print(":");
                   lcd.print(minutes);
                   lcd.print(":");
                   lcd.print(seconds);
                   lcd.print(":");
                   lcd.print(elapsedMillis);

          break;

        }
      default:
        {
          break;
        }
      }

      if( buttonJustPressed )
        buttonJustPressed = false;
      if( buttonJustReleased )
        buttonJustReleased = false;
    }
    /*--------------------------------------------------------------------------------------
     ReadButtons()
     Detect the button pressed and return the value
     Uses global values buttonWas, buttonJustPressed, buttonJustReleased.
     --------------------------------------------------------------------------------------*/
    byte ReadButtons()
    {
      unsigned int buttonVoltage;
      byte button = BUTTON_NONE;   // return no button pressed if the below checks don't write to btn

      //read the button ADC pin voltage
      buttonVoltage = analogRead( BUTTON_ADC_PIN );
      //sense if the voltage falls within valid voltage windows
      if( buttonVoltage < ( RIGHT_10BIT_ADC + BUTTONHYSTERESIS ) )
      {
        button = BUTTON_RIGHT;
      }
      else if(   buttonVoltage >= ( UP_10BIT_ADC - BUTTONHYSTERESIS )
        && buttonVoltage <= ( UP_10BIT_ADC + BUTTONHYSTERESIS ) )
      {
        button = BUTTON_UP;
      }
      else if(   buttonVoltage >= ( DOWN_10BIT_ADC - BUTTONHYSTERESIS )
        && buttonVoltage <= ( DOWN_10BIT_ADC + BUTTONHYSTERESIS ) )
      {
        button = BUTTON_DOWN;
      }
      else if(   buttonVoltage >= ( LEFT_10BIT_ADC - BUTTONHYSTERESIS )
        && buttonVoltage <= ( LEFT_10BIT_ADC + BUTTONHYSTERESIS ) )
      {
        button = BUTTON_LEFT;
      }
      else if(   buttonVoltage >= ( SELECT_10BIT_ADC - BUTTONHYSTERESIS )
        && buttonVoltage <= ( SELECT_10BIT_ADC + BUTTONHYSTERESIS ) )
      {
        button = BUTTON_SELECT;
      }
      //handle button flags for just pressed and just released events
      if( ( buttonWas == BUTTON_NONE ) && ( button != BUTTON_NONE ) )
      {
        //the button was just pressed, set buttonJustPressed, this can optionally be used to trigger a once-off action for a button press event
        //it's the duty of the receiver to clear these flags if it wants to detect a new button change event
        buttonJustPressed  = true;
        buttonJustReleased = false;
      }
      if( ( buttonWas != BUTTON_NONE ) && ( button == BUTTON_NONE ) )
      {
        buttonJustPressed  = false;
        buttonJustReleased = true;
      }

      //save the latest button value, for change event detection next time round
      buttonWas = button;

      return( button );
    }
    void setClock()
    {
      currentMillis = millis();
      /**
       * The only moment when currentMillis will be smaller than previousMillis
       * will be when millis() oveflows
       */
      if (currentMillis < previousMillis){
        elapsedMillis += MILLIS_OVERFLOW - previousMillis + currentMillis;
      }
      else {
        elapsedMillis += currentMillis - previousMillis;
      }

      /**
       * If we use equals 1000 its possible that because of the mentioned loop limitation
       * you check the difference when its value is (999) and on the next loop     its value is (1001)
       */
      while (elapsedMillis > 999){
        seconds++;
        elapsedMillis = elapsedMillis - 1000;
      }

      if (seconds == 60){
        minutes++;
        seconds = 0;
      }
      if (minutes == 60){
        hours++;
        minutes = 0;
      }
      if (hours == 24){
        hours = 0;
      }

      previousMillis = currentMillis;

     int analogValue = analogRead(analogPin);
      if (analogValue > threshold) {

    tone(13,C,timer/2);// Happy Bday to You
    delay(200);
    tone(13,C,timer/2);
    delay(200);
    tone(13,D,timer/2);
    delay(400);
    tone(13,C,timer/2);
    delay(400);
    tone(13,F,timer/2);
    delay(400);
    tone(13,E,timer);
    delay(750);
     }
    else {

    }
    }

body:
The code seems a little hotchpotch; is the code for reading the sensor supposed to be within the `setClock()` function? It would be better to put the following within `loop()`:

    if(analogRead(analogPin) > threshold)
    {
        playMelody();
        printTriggerTime();
    }

And create two new functions that handle the playing of 'Happy Birthday' and the printing of the time:

    void playMelody()
    {
        tone(13, C, timer / 2);// Happy Bday to you
        ...
        delay(750);
    }

...which is just a cut-paste of what you've got in the `setClock()` function, and:

    void printTriggerTime()
    {
        lcd.setCursor(0, 0);
        ...
        lcd.print(elapsedMillis);
    }
...which is a copy-paste of the code from within `case BUTTON_LEFT:`.

This will now play 'Happy Birthday' and print the time whenever the proximity sensor is triggered, AND it will print the time when the left-button is pressed (unless you remove that part of the code).

On a separate point, it's bad coding practice to use `#define` for a function, as you have done with `#define LCD_BACKLIGHT(state) { if ( state )...` - it makes it quite difficult to read the code, and can't conceive any reason why this isn't its own function. However, a nice trick in C is the following 'shortcut' statement:

    ( CONDITION ? DO_IF_TRUE : DO_IF_FALSE )

Thus you should change that line to:

    #define LCD_BACKLIGHT(state) ( state ? digitalWrite(LCD_BACKLIGHT_PIN,HIGH) : digitalWrite(LCD_BACKLIGHT_PIN,LOW))

That being said, "LCD_BACKLIGHT(state)" isn't actually used anywhere in the program!


sender: user

message:
How shiftOut function works internally? (explanation on source code)

I were examining `shiftOut()` function code in `wiring_shift.c` and I didn't quite understand what is going in digitalWrite function. I see `!!(val & (1 << i))` is taking the bit value from `val` but how exactly it works?

The whole function is below.

    void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
    {
     uint8_t i;

     for (i = 0; i < 8; i++)  {
      if (bitOrder == LSBFIRST)
       digitalWrite(dataPin, !!(val & (1 << i)));
      else
       digitalWrite(dataPin, !!(val & (1 << (7 - i))));

      digitalWrite(clockPin, HIGH);
      digitalWrite(clockPin, LOW);
     }
    }

sender: assistant

body:
I'll assume `bitOrder == LSBFIRST`.

* `i` is the bit number, i.e. the “index” of the next bit to write
* `1` is `00000001` in binary
* `<<` is the shift left operator. It returns its first argument shifted left by as many positions as indicated by the second argument
* `1<<i` is binary `00000001` shifted left by `i` positions, i.e. something like `0...010...0`, where the single 1 is in the i-th position counting from the right (rightmost being position 0)
* `&` is the “bitwise and operator”, where `any_bit & 0` is zero and `any_bit & 1` is `any_bit`
* `val & (1 << i)` is `0...0(i-th bit of val)0...0` in binary, where the i-th bit of val is in the i-th position of the result
* `!!` is a double negation: it converts zero to zero and any non-zero value to one
* `!!(val & (1 << i))` is either 0 or 1, and is exactly the i-th bit of val


message:
Can I use an arduino as a ground short?

I have a little personal project involving an Arduino Uno and an amp board from [Sure Electronics][1]. The amp has contacts for a mute function that involves shorting the contact to ground. I would like to control this muting with the Arduino which I was planning to do with a relay. However I think I might be complicating things and I thought it might be possible to do it directly with the pins.

Can I use the Arduino to directly short a circuit to ground? Or would I need something more complicated to be safe?

  [1]: http://store.sure-electronics.com/audio/audio-amplifier-board/low-power-100w/aa-ab31521 "Sure Electronics"

body: I can't see how much current the amp board will sink into the Arduino so like FuaZe I would recommend using your Arduino to drive an external component that you know can take the current.  This isn't really complicating the design too much, use an NPN transistor, with the P connected to the Arduino and just write High to the pin when you want to apply the mute.  If you blow the transistor then its going to cost you a few pence for a new one, if you blow your Arduino you are down £20!


body:
Depends on the voltage that is on that mute pin. If it's below 5 volt, you could use the arduino pin. You can measure the voltage using a multimeter.

If it's more than 5v you can use a NPN transistor and resistor combination. ![enter image description here][1]

Current isn't a problem with these kinds of "settings" pins, as there is just a pull-up resistor that by default (unconnected) sets the pin to HIGH. By connecting the pin to ground you set the pin to LOW.

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


message:
Books on Arduino development in C++

I will be using the Arduino platform with other data acquisition hardware for a school electronics project. I have limited knowledge of C++ syntax.

Are there good introductory to intermediate books that can bring a high school student with some programming experience to proficiency on Arduino?

body:
I'd recommend you go to [cplusplus.com][1]. Plenty of tutorial pages and topics to further your knowledge. However, be aware that Arduino uses a variant of **C** designed for microcontrollers (the exact flavour depends on the microcontroller type/family), rather than *C++*, so do be aware that some of the topics are not implementable on an Arduino. That said, I can't think why you'd be using some of the more elaborate C++ exclusive features in a fairly middle-of-road embedded system.

The only thing you need to ignore in C++ is memory allocation specifics - you're limited to the 'original' `malloc()` based functions rather than the all-singing-all-dancing `operator new` from C++. If you are in need of memory allocation functions, malloc is well-documented and a tutorial is only a quick Google away.

Of course I must also point you in the direction of the highly popular [Stack Overflow][2] site, part of this Stack Exchange network. While they don't have tutorials, there are plenty of great answers to common questions.

  [1]: http://www.cplusplus.com/doc/tutorial/
  [2]: http://www.stackoverflow.com


body:
There is a book called "C Programming for Arduino" by Julien Bayle that introduces it pretty well if you are just getting started at it. I think it's from Packt Publishing.

Another I found interesting is called "Practical AVR Microcontrollers" by Alan Trevennor that gives examples of programming using C without having to get an Arduino.

Otherwise, Stack Exchange is always really great to browse.


body:
I found the Arduino examples a good reference for refreshing/learning C++.

Important Arduino C++ classes are:

* String: https://www.arduino.cc/en/Reference/String
* Arduino classes for components: https://www.arduino.cc/en/Reference/Libraries

To learn more about the syntax of the language, the inventor of C++ has also a couple of videos online.


body:
I would start with [a standard C++ introduction book][1] to get an understanding for the language. After that I would read a book on [object-oriented design and implementation][2].

There is a lack of books on how to systematically approach programming small scale embedded systems such as Arduino. Due to the restrictions on resources, both processing and memory, C++ has to be used "carefully". There is a need to understand some of the more difficult concepts such as volatile, virtual, ISR, etc.

Reading others code is also a very good way to learn. I would recommend looking at the source code and example sketches to [Cosa][3]. This is an OOP framework for Arduino/AVR.

Last but not least - learning by doing!

Cheers!

  [1]: https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list
  [2]: http://www.amazon.com/Best-Sellers-Books-Object-Oriented-Design/zgbs/books/4013
  [3]: https://github.com/mikaelpatel/Cosa


message:
Arduino raise the error: `does not name a type` when an Object is used outside of the main two blocks setup and loop

I have this:

    class Person{
    public:
     int age;
    };

    Person p;
    p.age;

    void setup() { ... }

    void loop() { ... }

And I got this error:

    Compiling 'MyProgram' for 'Arduino Mega w/ ATmega2560 (Mega 2560)'
    MyProgram.ino:18:1: error: 'p' does not name a type
    Error compiling

But is I use the Person instance inside setup or loop functions it compiles find.

    void setup() {
     // initialize digital pin 13 as an output.
     Person p;
     p.age;
    }

I got this:

    Compiling 'MyProgram' for 'Arduino Mega w/ ATmega2560 (Mega 2560)'
    Binary sketch size: 4,674 bytes (used 2% of a 253,952 byte maximum) (3.45 secs)
    Minimum Memory Usage: 428 bytes (5% of a 8192 byte maximum)

What is the different? Why the instance only can be used into the blocks?

I also declared a file with a simple class and then create a instance of it class outside the blocks and I got the same error. If I put the instance inside the blocks it works. So, any tips?

body: All code intended to be executed must be inside a function block in C++.


body:
As you have already noticed, you cannot call methods of a class, nor access its properties, outside a "block" (as you call it).  More specifically, you can only perform "programatical" operations from within a *function*.  Anything outside a function (known as the *global scope*) is purely for declaration and initialization of variables and types, etc.

Any class variables declared in the *global scope* have their *constructor* executed before the rest of the program (even before `setup`) gets run.  However, `setup` is not the first function to be called at startup.

Anything you put into a constructor has to take into account the fact that anything might be happening between the constructor being called and the object instance actually being used.  Things like `pinMode` and `digitalWrite` are unsafe to use in a constructor, since there is a chance they may be negated during the startup.  That is why the majority of Arduino classes have a `.begin()` method which is called from `setup()`.

The proper method for using classes with pin control and similar operations is:

1. The constructor takes the pins to use
2. The constructor saves those pins in variables
3. The begin() method is called in setup()
4. The pins are configured appropriately.

For example:

    class myClass {
        private:
            int _myPin;
        public:
            myClass(int pin) : _myPin(pin) {}

           void begin() {
                pinMode(_myPin, OUTPUT);
                digitalWrite(_myPin, HIGH);
            }
    };

    myClass p(4);

    void setup() {
        p.begin();
    }

    void loop() {
    }

The object instance `p` is in the *global scope* and can be referenced from any function. The pin is configured only when setup() is run.

The startup sequence, more specifically, is typically this:

1. The memory used by global and static variables is "zeroed".
2. Any pre-defined variable values (*BSS*) are copied from flash into RAM.
3. Any object constructors are called.
4. The main() function is called (main startup function).
5. The init() function is called which configures the Arduino platform.
6. The initVariant() function is called which performs any board specific setup routines.
7. USB is configured on the boards that have it
8. Your setup() function is called.
10. Your loop() function is called.
11. The serialEvent() system runs if defined.
12. Go to 10.

As you can see quite a lot happens between the constructor being called and setup() being called, and you cannot reliably predict what that might be.  Some boards may do nothing more than configure interrupts and enable timers (for things like `delay` and `millis`), but other boards may configure IO pins to default settings (especially more complex boards with multiple functions per IO pin), so really the only safe operations you can perform in a constructor are operations which act directly on the internals of the class itself.  Anything outside the scope of the class could be changed before you come to use it.


message:
My arduino won't show up in Device Manager in any way, neither in unknown devices nor in COM port.

I have a brand new arduino(original), and it is not showing up in Device manager or anywhere else. Even the computer doesn't Prompt anything. I am using Windows 7 32 bit.

body:
As the OP reported: *It worked with a different cable.*

I converted his comment to an answer so the system would regard this issue as solved. Please accept this answer.

---

Some cheap USB cables only carry power, and not data. I have such a cable that came with a USB desk light. To save money they only run two wires and not four, since the desk light is not a data device.

Be cautious about grabbing any old cable from your desk for testing. Make sure it is designed for data use. If in doubt, try a known good cable.


message:
Serial communication stops when I connect the tx cable

I'm using the apc220 rf modules. Now I'm having the following problem:

My receiving arduino uno only receives data when the tx pin on the arduino (rx pin on the rf module) is disconnected. As soon as I connect the tx pin my serial monitor receives only the value 0.

Is my rf module broken, or can someone help me with this?

body:
To have two serial ports on Arduino board like Uno use `SoftwareSerial.h`.

Example

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(2,3); // RX, TX

    void setup()
    {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);

      Serial.println("Hello!");

      // set the data rate for the SoftwareSerial port
      mySerial.begin(9600);
    }

    void loop() // run over and over
    {
      if (mySerial.available())
        Serial.write(mySerial.read());
      if (Serial.available())
        mySerial.write(Serial.read());
    }

Now after opening `Serial monitor` you should see Hello! and then you can test `SoftwareSerial`.

**DO NOT FORGET!!!**

When you connect to pins 2,3 or etc, this is **TTL** voltage level. You **can't** connect direct to RS232.


message:
What is the difference between a motor driver and a motor shield?

what is the difference between a motor driver(like L293D) and a motor shield?

what are the advantage?disadvantages of both?

And which one do you suggest ?

body:
A motor driver is a chip that drives motors.  A motor shield is a circuit board with connections on it that contains a motor driver chip that drives motors.

A shield is convenient since you can just plug it in to your Arduino and wire the motors direct to it, but it lacks the flexibility of a raw driver chip which you can wire up precisely as your project demands.


body: The differrence is usablilty and, in some cases, the protection of your chip; if there is a surge of more than 5V to your driver it will fry, which is why some drivers have onboard voltage regulators and a heatsink for overheating problems. Advantage of motor driver is that you can use it as per your requirements, whereas a shield is fixed and you cannot change any aspects.


body:
*A motor driver is a chip that drives motors. A motor shield is a circuit board with connections on it that contains a motor driver chip that drives motors.*

**A shield is convenient since you can just plug it into your Arduino and wire the motors direct to it, but it lacks the flexibility of a raw driver chip which you can wire up precisely as your project demands**


message:
FTDI Adjustable 3v3/5v only outputs 5v

I bought the below FTDI programmer for use with my 3v3 arduino pro mini. But even when the switch is set to 3v3 it is powering the board with 5v, (hence the IO voltage is also 5v). Note that when the pro mini is powered by batteries on the RAW input the IO voltage is 3v3 as expected. The problem is that when programming at 5v, any 3v3 peripherals (such as the BMP180) will be surely damaged.

http://www.ebay.co.uk/itm/301597777458?_trksid=p2057872.m2749.l2649&ssPageName=STRK:MEBIDX:IT

Now on the eBay description it says:

> This board ship default to 5V, but you can cut the default trace and add a solder jumper if you need to switch to 3.3V

Which trace needs to be cut, and where does the jumper need to connect to/from?

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

  [1]: https://i.stack.imgur.com/XS2lX.jpg
  [2]: https://i.stack.imgur.com/tbIS0.jpg

body:
The 5V/3.3V switch is fed into the "VCCIO" pin which sets the voltage of communication and nothing else.  The 5V pin of the header is connected straight through to the USB port's 5V pin.

You can either take a separate 3.3V feed from the 3V3OUT pin of the FT232RL (limited to 50mA) which is easiest to take from the 3.3V side of the switch's pins (on the underside, either or both of the two pins with no visible trace connecting to them - the lowest two in your top picture), or you can re-wire the header so it takes its voltage from the output of that switch (the middle two pins).  It looks like it would be a case of cutting the left hand portion of the long fat trace at the top edge of the back (on your top picture) then soldering a wire from the 5V pin on the header to the center pins of the switch.  That should make the output power switchable between 5V and 3.3V.

![enter image description here][1]

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


message:
Stop at the end of a track

I would like to create a camera dolly for capturing timelapse movies.

i.e. something like this:
http://youtu.be/Qce1f6SKEMU

Whats a reliable way to detect the end of the track and stop the stepper motor moving the camera? In other words how is it possible to get the current position of the camera and stop the motor before the track ends to prevent crashing into the bumpers?

body:
The simplest way is to have an opto-interrupter fitted at one end of the track (IR LED and IR Phototransistor), and a small bit of plastic or whatever on the dolly which interrupts the IR beam.

Printers have been doing it that way with their print heads for decades.

http://www.martyncurrey.com/connecting-an-photo-interrupter-to-an-arduino/


body:
I find a mechanical switch the simplest and cheapest. But technically it is the same as an opto switch.  These are often refered to as [limit switches][1].

![enter image description here][2]

You tie the switch to a pin with the normally closed (NC) pin, set it to pinMode(pullup), and check it each each loop. When the read value goes low (0), you stop moving your motor.

  [1]: https://www.google.com/search?q=limit switch&tbm=isch
  [2]: https://i.stack.imgur.com/l7PWO.jpg


body:
Many methods exist:

References to unpowered means the switch does not draw power when not operated. When a motor is activated it will draw power.

 - Mechanical switch- microswitch is the most common (as per Spiked3's suggestion). Contamination and weather may be issues (depending on how waterproof your camera is). No power needed for actual switch.

 - Optical (a la Majenko). Some environmental issues. Effect of ambient light needs to be considered.

 - Capacitive. Can be fully sealed. Need to be powered.

 - Magnetic - Hall (powered) and Reed (unpowered).

Whatever is used, the current and voltage ratings need to be compatible with the load. In many cases the actual switch will need a transistor or relay or similar to provide the power drive to the dolly motor. This is not hard to do but needs to be noted.

___________________________
An end of track signalling method that is relatively unaffected by environmental issues is to use a magnet and magnet detector. The most common detectors are either a "Hall sensor" IC or a reed switch.

Reed switches are mechanical and more fragile than Hall sensors but need no power when unoperated and can be bought in ready made encapsulations that are robust enough to be reliable. Properly implemented a reed switch can be essentially indestructible.

Hall sensors need to be powered but power levels are small compared to eg dolly motor current and low current versions are available.

Both Hall sensors and reed switches have a degree of "hysteresis" - the point in the travel where they operate is past the point where they release again, but this is easily allowed for in practice.

____________________________

[Reed switch demonstration](https://www.youtube.com/watch?v=hnCEQYO-i_E) - 38 seconds video - simple and obvious.

Instructables [DIY powered dolly wity reed swithes](http://www.instructables.com/id/DIY-motorized-moving-timelapse-camera-dolly-with-A/all/)

[Sparkfun magnetic door switch set](https://www.sparkfun.com/products/13247) and encapsulated reed switch and magnet.

[Hall sensor theory of operation](http://www.electronics-tutorials.ws/electromagnetism/hall-effect.html)

[Many ideas here](https://www.google.co.nz/search?q=hall+sensor&biw=1280&bih=789&source=lnms&tbm=isch&sa=X&ei=buRtVYmRFtXh8AWv9YOYAQ&sqi=2&ved=0CAYQ_AUoAQ#tbm=isch&q=hall+effect+sensor++circuit) for using hall sensors.

[Reed switches](https://www.google.co.nz/search?q=hall+sensor&biw=1280&bih=789&source=lnms&tbm=isch&sa=X&ei=buRtVYmRFtXh8AWv9YOYAQ&sqi=2&ved=0CAYQ_AUoAQ#tbm=isch&q=reed+switch+)


message:
Is arduino suitable for high frequency application?

Can I use the arduino for an application with a frequency of 4 MHz?

I need to create a clk with this frequency and send and receive data on the rising and falling edges. and it is not a normal SPI interface I have my own conditions so I need to do it manually.

If it is not suitable, is it technically possible?

body:
No, it's not suitable due to the inherent maximum pin output frequencies in relation to the clock divider setting.

Yes, it's technically possible. Edit the divider to a value that sets the output to close to what you need. However this is annoying to do, and has serious repercussions in your code. (i.e. having to multiply every timing/bit value by 16, 8, 4, 2 or whatever you choose)

A clock of that high of a frequency would have to be some crystal to set the base time, and then a comparator circuit that could vary fast enough to push data into the edges.

You could, however, simply note the absence of the 4MHz signal as 0, and it's presence as 1, sending binary data that way it probably a lot easier than encoding it between each individual edge.


body:
Most Arduinos are based on AVR chips clocked at 16 MHz. On those,
you _can_ generate a 4 MHz clock using hardware timers. Bit-banging
data at this speed would be difficult though. It _may_ be possible,
using unrolled loops and hand-crafted assembly... or not, depending on
the specifics of your application. Even if possible, it would be a nice
challenge for an assembly programmer.

The Arduino Due is based on an ARM chip clocked at 84 MHz. This
gives you more leeway to bit-bang at 4 MHz. But even on the Due you
would certainly need hand-crafted assembly.


message:
Leonardo broken?

My leonardo was working fine until today, when I plug it to my computer all led (RX/TX/L/ON) stays on (Green for on, amber for others) and my computer no longer see a com port.
(by the way, do you know what the L led mean ?)
If I add external power, TX goes off then after few seconds RX goes off too then back on.
With external power, the atmega goes very hot (I can't touch it).
RESET button do nothing.

Is my Leonardo dead ? Any idea what could have cause that ? The fact that the atmega is so hot when the board is powered up with 12V let me think that the voltage regulators is no longer working. Good guess ?

body:
By your description, I'd say:

> Quite Probably.

You should check what the 5V and 3.3V voltages are using a DMM.


message:
Being able to run two functions at once

So I am doing a project where a bunch of servos are moving from 90 - 120 degrees and slowly speed up over time until they reach their max speed and so stay at that speed.
This is being done by editing the delay under the servo sweep for loop.
However though this works it doesn't work with the next component.

WHat I want to happen next is an MFRC522 RFID reader to always be scanning and at any time it detects a card and verifies it the servos from whatever speed they are now at start to slow down.
The problem is I can't get the two functions to run simultaneously. IF the servo is running its sweep function it must finish before the RFID tag can scan. This makes the whole device look very lagy.
Is there a way I can get the RFID scanner to be reading all the time even when the servo sweep for loop is working?

Here is the code:
Please note that I have put printins everywhere to see how often the RFID is scanning etc just while I test the code out.
I essentially have two functions one called nocardservo and yescardservo each one activating if there is a card there or not.
Any help would be fantastic!!

    #include <SPI.h>
    #include <MFRC522.h>
    #include <Servo.h>

    #define RST_PIN  9  //
    #define SS_PIN  10  //

    MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance

    Servo myservo;
    int pos = 0;
    int y = 15;
    int z = y;
    void setup() {
      myservo.attach(6);
      myservo.writeMicroseconds(1518);
      Serial.begin(9600);  // Initialize serial communications with the PC
      while (!Serial);  // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
      SPI.begin();   // Init SPI bus
      mfrc522.PCD_Init();  // Init MFRC522
      //ShowReaderDetails(); // Show details of PCD - MFRC522 Card Reader details
      //Serial.println(F("Scan PICC to see UID, type, and data blocks..."));
    }

    void loop() {
      // Look for new cards
      if ( ! mfrc522.PICC_IsNewCardPresent()) {
    nocardservo();
        return;
      }
      delay(20);
      Serial.println("carddetected");
      // Select one of the cards
      if ( ! mfrc522.PICC_ReadCardSerial()) {

      }
      Serial.println("correctcard");
      yescardservo();
    delay(20);
    return;
    }

    //***If card not detected this function runs**//

    void nocardservo() {

      for (pos = 90; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
      { // in steps of 1 degree
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);                       // waits 15ms for the servo to reach the position
      }
      for (pos = 180; pos >= 90; pos -= 1) // goes from 180 degrees to 0 degrees
      {
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(15);

      }
    }
    }

    //***If card is detected this function runs**//

    void yescardservo() {

      for (pos = 90; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
      { // in steps of 1 degree
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(50);                       // waits 15ms for the servo to reach the position
      }
      for (pos = 180; pos >= 90; pos -= 1) // goes from 180 degrees to 0 degrees
      {
        myservo.write(pos);              // tell servo to go to position in variable 'pos'
        delay(50);

      }

    }

body:
What you want to implement is described in [Blink Without Delay][1].  Basically, instead of using the delay function to just wait until your time has elapsed, you use variables to measure how much time has elapsed and only execute your operation when it has.  In the mean time, you can check on other things and do those in the mean time.

  [1]: http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay


body:
have a look my example program below for you reference.

    /*
     * Author BALASAIDULU.N
     * function -1 : Fading led with pwm pin 9
     * fucntion -2 : Blinking LED on pin 13
     * connect an LED on pin 9 with a 330 ohms resistor
     */
         int leda=9;
         int ledd=13;
    int i,g,s1,s2;
    int switchPin=8;

    void setup() {
    pinMode(ledd,OUTPUT);
    pinMode(switchPin,INPUT);
    }

    void fading()
    {
      st:
      if(s1==0){
    if(s1==1){goto hy;}
    analogWrite(leda,i);
    delay(30);
    i+=5;
    if(i>255){s1=1;}
    goto st1;
      }
    hy:

    if(i<0){s1=0;goto st;}
    i-=5;
    analogWrite(leda,i);
    delay(30);
     st1:
    delay(10);
    }

    void blinking()
    {
    digitalWrite(ledd,HIGH);
    delay(30);
    digitalWrite(ledd,LOW);
    delay(30);

    }
    void loop() {

    int g;
    g=digitalRead(switchPin);
    if(g==1) {delay(50);}
    if(g==0){
    blinking();
    fading();}
    }


message:
Motorcycle Battery Powering Arduino UNO

![Arduino power supply][1]

Folks

I am planning to power my Arduino, which will be mounted on a motorcycle, using the motorcycle's battery. So the same battery will be starting the engine and powering other electrical components.

I am wondering if this circuit will work fine.

C1 - 1000uF 50V;
C2 - 1000uF 25V;
D1 - 1N4001 ;

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

body:
Your circuit is 'going in the right direction' but can be improved.
If you wish to use the regulator shown:

 - The larger the input capacitor (C1) the better; it will survive noise spikes and low voltage "droops", eg during starting.

 - Adding a series resistor to drop some of the input voltage will help C1 filter out noise.
*Rin* should be V/I = V_drop_max/I_maximum .
With a 9V regulator and 12V supply you cannot afford much drop in the resistor.
 If you use the 6V output system I recommend below then you could allow closer to 3V drop in *Rin*.
If *Imax* is 100mA then *Rin* = V/I = 3/0.1 = 30 Ohms.
Typically you'd use 27 Ohms (which is the closest E12 standard value.

Power dissipation is the resistor = I^2 x R.
So for eg 27 Ohms and 0.1 A (100 mA) power dissipation in the resistor is
I^2 x R = 0.1^2 x 27 = 0.27 Watt
So you'd use at least a 0.5 Watt resistor and ideally  Watt or more. Air cooled resistors are relatively low cost and a much better way of dealing with heat than trying to cool a regulator.

 - Adding a ~15V zener diode at the input to U1 will help protect against spikes. This works better if *Rin* is used. Without *Rin* the zener may be destroyed by spikes. If you use the LM29xx regulators that I mention below the zener is not needed as the regulator has its own internal protection circuitry.

The LM7809 regulator is somewhat unusual. If you have them available they could be used but there are much more common and/or modern regulators available.

The regulator's Vout should be fed to the Arduino's Vin terminal, which supplies the Arduino's internal regulator, to provide 5V or 3V3 depending on which Arduino you are using. With a 5V Arduino, using Vin of 6V or more will be adequate. Higher Vin causes more heat in the Arduino on board regulator. (As Chaaarlie2 noted, 6V on Vin may be a bit on the low side for heavy loads on the Arduino 5V supply - as may happen if shields use the 5V supply. Increasing Vin to say 6.5V should allow the Arduino's internal regulator to supply its maximum rated current if desired.

9V output is higher than the Arduino needs. It is an acceptable voltage but 6V to 7V will cause less heat on-board the Arduino (and more in the external regulator).

Vehicle power systems can have extremely high voltage spikes present and sudden changes in supply voltage. Some regulators are made to work well in the automotive environment. One such family are the LM29xx series of regulators.

One superb version of this regulator is the LM2931-N [[**Data sheet here**]](http://www.ti.com/lit/ds/snosbe5g/snosbe5g.pdf) - this is available in a range of versions but the simplest is the 3 lead type in a range of packages. The TO220 package is recommended due to its good power dissipation capability and ease of heatsinking if necessary. This data sheet covers versions with about 100 mA output rating, but higher output examples are available. Fixed 3.3V and 5V output versions are available but in this application the variable output version, set to about 6V or maybe 6.5V is "safest". These are very similar to the common LM317 in operation. The basic regulator produces 1.26V output and 2 resistors are used to set the desired output voltage. The advantages over the LM317 are the lower dropout voltage and the protection against typical automotive input problems.

The datasheet description states:

> Designed originally for automotive applications, the LM2931-N and all regulated circuitry are protected from reverse battery installations or 2 battery jumps.
>
>During line transients, such as a load dump (60V) when the input voltage to the regulator can momentarily exceed the specified maximum operating voltage, the regulator will automatically shut down to protect both internal circuits and the load.
>
>The LM2931-N cannot be harmed by temporary mirror-image insertion. Familiar regulator features such as short circuit and thermal overload protection are also provided.


message:
How to add data without pre-defining variables?

I am currently working on a RFID card reader. I need the reader to send the ID to a storage space.

What I am trying to achieve is a person swipes their card, enters their name on the serial monitor, and then have that data stored in a pair. The thing is that I do not know how many people will have cards. After that, I could call a person's name and it would show "Hello `w`, your ID number is `xxx xxx xxx xxx xxx`.

So I know there are no such things as "dynamic" variables. And I think I would need to pre-define a TON of arrays if I wanted to use them. So I am kinda at a stopping point. Is there no way to generate a new variable name and store data to that variable?

Also, I work with PLCs so I thought that indirect addressing might work, but I am unfamiliar on how to even do that in C++, only in ladder logic or if it would even work. Or how I would be able to call out an ID by name with that approach.

body:
The "key" is creating a means to access a table of IDs that you can search through for a given name or a given ID number. There are various ways of doing this and if you are unclear on these that can be discussed in due course. But, to start, I'll assume that making and searching some form of table or array is not a problem for you.

You obviously MUST have enough storage space for the maximum number of simultaneous IDS that you wish to store at any time. Call this "IDCount".

You can allocate IDCount ID storage locations by whatever means suits you.
In unused locations you store a dummy or null ID number.
eg ID 000 000 000 000 000 is probably invalid so can be used as an 'empty' indicator.

To add a new ID  either search through your table of IDs for an empty location and store the new ID there. To find a given ID match you search the table for the ID and , if it exists, retrieve the matching name.

____________________

**"Improvements":**

**To reduce access times** when the potential entries are large you can store all entries "at the bottom" and have a pointer to the 1st free location. New entries are added "at the end". If an entry is removed, all entries above it are moved down by one. eg   if entry N is removed:
for (entry >= N and entry < end_pointer)
...move entry N + 1 into location N
...and step N by 1.

Another method is to use a "**linked list**" where each entry has a pointer to the next entry in the list. New entries take an address from the empty_locations list and add their address to the used_locations list. Removed entries do the opposite. This can be fast and effective but also mind blowing for beginners and, when it goes wrong it can go VERY wrong. Best avoided initially.

The simple "search for 1st empty entry" method will usually work very well.


body:
Use the EEPROM. This allows data to remain intact and unchanged even when power is disconnected.

As you say you're new to programming, and because I wrote a similar program just last week as an experiment for something bigger, I'll talk you through some of it. However, I'm not going to give you the whole code to copy-and-paste, I'm only going to give you information on dealing with EEPROM and structures. C-aficionados may grumble at some bits, and Arduinites at others - sic vita est. This is something of a crash-course so it's not gospel, but it should be more than enough to guide you. You may already know some or most of it; it's included nonetheless for completeness, for those who don't.

----------

## For those who don't know ##

In C, data relevant to an object can be stored in a [structure][1], or `struct`. You can put all sorts of different types of data in a struct, like so:

    struct personalProfile {
        char    firstName[8];
        char    lastName[8];
        uint    cardID;           // 'uint' is an unsigned int...
        bool    accessAllowed;
    };
You can then use that structure to create a 'personal profile' for however many people you want:

    // within your main program:

    struct personalProfile Person1;
    struct personalProfile Person2;

    // Now you can directly access individual aspects as so:

    Person1.firstName = "John";
    Person1.lastName = "Brown";
    Person1.accessAllowed = TRUE;

    Person2.firstName = "Dodgy";
    Person2.lastName = "Dave";
    Person2.accessAllowed = NOT_A_HOPE_IN_HELL;
You can use the *members* of a structure in exactly the same way you'd use that member type if it wasn't part of a structure. Nice and easy.

The best way to store multiple instances of a particular variable type is in an [array][2]:

    struct personalProfile listOfPeople[5];
You now have an array of five (blank) `struct`s, which can be accessed by `listOfPeople[n].firstName = Potato;`, where 'n' is between 0 and the number-of-entries-minus-one. So far so potato.

An array is pretty basic. It's present in all sorts of programming languages because it's inherently essential to almost any program, but the trouble is that it's static. Using the code above, once the array has been created with five `struct`s in it you can't add or remove any. One solution is to create a massive array, and set all the values in each `struct` to zero, or some other 'empty' identifier, so you're always going to have enough entries (up to a point). However, that's lazy, time inefficient (you've got to set aaaaalll the individual elements to your 'empty' signifier), resource inefficient (look at all that unused space!), and the data only lasts while the program is running. As soon as you cut the power to the Arduino, the information is lost.

Next comes [containers][3]. These are part of the Standard Template Library (STL) in C++. They're great for creating and managing dynamic-length arrays. There are different types for different purposes (see the link), but they don't exist in C (at least as far as this post is concerned) and they're not available as part of the Arduino IDE without installing a bunch of libraries or some other intervention. Therefore you've got to make your own version. It's actually pretty easy...

----------
## EEPROM basics ##

The [EEPROM library][4] that comes with Arduino is of course essential for this. It doesn't have many functions, and the ones that exist are fantastically easy to understand. EEPROM, for those who don't know, is non-volatile memory. That means that when you store data it stays there forever, even if you remove the power. The only way to get rid of the data is to write over it. The downside of EEPROM is that it has limited amount of times it can be written to - 100,000 times per bit typically so you don't need to start keeping count, it just means you shouldn't be using it as regular program memory. Reading data from EEPROM isn't limited in the same manner.

Using the function `EEPROM.put(address, data)` you can put ANY data type - an `int`, `char` or - you guessed it - a `struct` into the EEPROM, starting at the byte specified by *address*. Of course there has to be enough space so you can't put an `int`, which takes up more than 1-byte of space, into the last address without the function failing. (Or can you? I haven't tried it yet because I'd never do it in practice.)

So you've created your structure, and made sure that all it's members are a fixed size. That means the structure has a fixed size. If you know that size, you can start putting them into the EEPROM.

    // within main program

    struct personalProfile Person1;
    struct personalProfile Person2;

    // fill in the details for Person 1...
    // fill in the details for Person 2...

    // ...then put Person1 in the EEPROM at address 0.
    EEPROM.put(0, Person1);

    // Done. Now put in Person2. But where?
    // You need to make sure you put them AFTER Person1.

    int AddressJump = sizeof(personalProfile);

    // AddressJump now equals how many bytes are need to store one person.

    EEPROM.put(AddressJump, Person2);

Simple as that.

If you create a Person3, you're going to need to put them `sizeof(personalProfile)` bytes AFTER Person2, i.e. `EEPROM.put(AddressJump*2, Person3);`. So, you add Person*N* to address `AddressJump * (N-1)`.

Retrieving data is the same principle, except you use `EEPROM.get()`:

    // provided you've used the above snippet somewhere to actually
    // populate the EEPROM with something!

    struct personalProfile personA;

    EEPROM.get(0, personA);

    Serial.print("Person A is called:");
    Serial.println(personA.firstName);

Again, you're going to need `sizeof(personalProfile)` to read the second, third, or *N*th person. If you 'send `EEPROM.get()` to the wrong address it will still populate the personalProfile instance with data, it will just be gobbledygook. Once you start putting people in the EEPROM you're going to need to keep track of things otherwise you'll end up lost. You need to manage the list to make sure you don't `put` one person on top of another (you could get in trouble for that) and you don't want to `get` someone that isn't there.

----------
## List management ##

This is where I leave you, for now. When you have digested the information above, and you want to continue, I'll carry on.

Your first task is to determine what sort of array you want. Inevitably it's going to be a [Linked List][5]. This is an array of `structs`, where each `struct` element in the list *contains the memory address of the following element*, thus the list is **linked**. You need to consider:

 1. How the array will be linked (if at all);
 2. Whether or not the array is space-critical (does it have to be as small as possible);
 3. Where the array is going to start;
 4. How you're going to keep track of how many people are in the array.

@TL140 I await your response, good luck!

  [1]: http://www.cplusplus.com/doc/tutorial/structures/
  [2]: http://www.cplusplus.com/doc/tutorial/arrays/
  [3]: http://www.cplusplus.com/reference/stl/
  [4]: http://www.arduino.cc/en/Reference/EEPROM
  [5]: http://en.wikipedia.org/wiki/Linked_list


message:
Storing and parsing data with Arduino

I use Ethernet Shield and Arduino to GET data from the server in JSON format. Request looks like this:

    client.println("GET http://ramp.local/api/actions?");

The response I get is:

    [{"action_id":1,"action_type":"up","action_status":"new","ramp_id":31,"user_id":17},
    {"action_id":2,"action_type":"down","action_status":"new","ramp_id":32,"user_id":20},
    {"action_id":3,"action_type":"up","action_status":"completed","ramp_id":32,"user_id":17},
    {"action_id":4,"action_type":"up","action_status":"failed","ramp_id":31,"user_id":17}]

How to collect a data in a string variable and parse it to get `action_status`?

body:
Ideally, you would use a proper recursive JSON parser, like the one
suggested in prakharsingh95's answer. However, if code speed and size
are critical considerations, and if the format of the response is
narrowly constrained, then you can build a fast special-purpose parser.

Here is a simple example. It assumes the response has been stored in the
`response` char array:

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

    static const char key[] = "\"action_status\"";
    const char *p, *q;
    char action_status[16];

    for (p = response; ; p = q) {
        p = strstr(p, key);    // find key
        if (!p) break;         // not found
        p = strchr(p, ':');    // find ':' between key and value
        p = strchr(p, '"');    // find opening quotes for the value
        q = strchr(p+1, '"');  // find closing quotes

        // Report finding.
        strncpy(action_status, p+1, q-p-1);
        action_status[q-p-1] = '\0';
        Serial.print("Found action status: ");
        Serial.println(action_status);
    }

Of course, in production code you would check that every `strchr` call
returns a non-NULL pointer. And you would check that the status you
found fits in your buffer.

**Edit** about the pros and cons of this method:

Compared to a proper JSON parser, this approach will give you smaller
and faster code, the drawback is it being more _fragile_. For example,
this will not detect a corrupted JSON, and it will return garbage if the
action\_status happens to be a number instead of a string, or is a
string with embedded double quotes, or if the string "action\_status"
appears as a value of some other field... A full JSON parser should
correctly handle all these cases.

On a non-embedded computer, a proper JSON parser would probably be the
only appropriate answer. On a constrained microcontroller environment,
you sometimes have to make trade-offs. In this particular instance, the
“best” answer depends on how much you weight speed and size vs.
robustness against unexpected input.


body:
I would recommend a JSON parsing library. Checkout https://github.com/bblanchon/ArduinoJson

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

    var response = [] ; // get response here
    int response_length = 4; //Put length of the response array here
    StaticJsonBuffer<200> jsonBuffer;

    String action_ids[] = new String[response_length];
    String action_types[] = new String[response_length];
    String action_statuses[] = new String[response_length];
    String ramp_ids[] = new String[response_length];
    String user_ids[] = new String[response_length];

    for (int i=0; i < response_length ; i++) {
        JsonObject& data = jsonBuffer.parseObject(response[i]);
        // Note the '&' above

        action_ids[i] = data["action_id"];
        action_types[i] = data["action_type"];
        action_statuses[i] = data["action_status"];
        ramp_ids[i] = data["ramp_id"];
        user_ids[i] = data["user_id"];
    }

Of course, you only need to extract those fields that you need.


body:
[Try this on for size.][1]

This is an arduino based, open source, JSON processor.

  [1]: https://github.com/bblanchon/ArduinoJson


message:
How do I know how many memory that Arduino is use after my code is running for a few time

When I upload my program to Arduino it says the memory that the program is used. But what if I use a bad management of dynamic memory, or any object is created several times in use a lot of memory and the Arduino memory overload.

How do I know the current size of memory that Arduino is use?

I am thinking about to create a function in Arduino that return me this information if I send it a request command, but also I don't know how do I inspect the Arduino memory.

Note: I am using the Board: Arduino Mega 2560.

I read the question and the answer for [Measure SRAN usage][1]

In the question @fuenfundachtzig ask:

***Can I determine how much SRAM I have left in the live system?***

In my question I am asking about how do I know or monitoring my program memmory. Ok the Measure SRAN usage answer give me the tips or tools to develop my idea, but the question is not the same.

I am tryin to know in an specific time what is the size of my memmory.

### example...

    void setup() { //doing some configuration };

    void loop() {  // invoke some functions and evil function  };

    // in other place a evil function

    void evil(){
    MyClass * instance = new MyClass();
    //play with the instance and it class create other instances....
    //and a dynamic memmory is used but not deleted.
    }

I am trying to know if it happens and how do I detect with Arduino? I am not talking about how much memmory do I left in the live system.

  [1]: https://arduino.stackexchange.com/questions/11845/measure-sram-usage

body:
Basically it looks like you want to figure out if you have a memory leak. Since the objects get allocated continuously you will end up having less and less free memory.

You can use the functions presented in the sister question answered very nicely by Edgar (more specifically the complex one that calculates all the memory going through the allocation chain).

You can check the returned value every so often (few seconds/minutes depending on your needs) and if the free memory value drops continuously then you have a memory leak somewhere. This will not tell you where the leak is of course. Also this should work well while debugging the code, but would probably not be a good idea to leave it in "production" code.


message:
Shortening large chunks of code

Some of the code that I have is unbearably long and drives me insane. I don't know if there were simpler ways to doing what I am doing.

    long turn1;
    long turn2;
    long turn3;
    long turn4;
    long turn5;
    long turn6;
    long turn7;
    long turn8;
    long turn9;
    long turn10;
    long turn11;
    long turn12;
    long turn13;
    long turn14;
    long turn15;

 #################

      turn1 = random(sizeof(turns) / sizeof(char*));
      turn2 = random(sizeof(turns) / sizeof(char*));
      turn3 = random(sizeof(turns) / sizeof(char*));
      turn4 = random(sizeof(turns) / sizeof(char*));
      turn5 = random(sizeof(turns) / sizeof(char*));
      turn6 = random(sizeof(turns) / sizeof(char*));
      turn7 = random(sizeof(turns) / sizeof(char*));
      turn8 = random(sizeof(turns) / sizeof(char*));
      turn9 = random(sizeof(turns) / sizeof(char*));
      turn10 = random(sizeof(turns) / sizeof(char*));
      turn11 = random(sizeof(turns) / sizeof(char*));
      turn12 = random(sizeof(turns) / sizeof(char*));
      turn13 = random(sizeof(turns) / sizeof(char*));
      turn14 = random(sizeof(turns) / sizeof(char*));
      turn15 = random(sizeof(turns) / sizeof(char*));
###########
    if (turn1 == turn2 or turn2 == turn3 or turn3 == turn4 or turn4 == turn5 or turn6 == turn7 or turn7 == turn8 or turn8 == turn9 or turn9 == turn10 or turn10 == turn11 or turn11 == turn12 or turn12 == turn13 or turn13 == turn14 or turn14 == turn15) {

###########

    lcd.print(turns[turn1]);
    lcd.print(turns[turn2]);
    lcd.print(turns[turn3]);
    lcd.print(turns[turn4]);
    lcd.print(turns[turn5]);
    lcd.setCursor(0, 2);
    lcd.print(turns[turn6]);
    lcd.print(turns[turn7]);
    lcd.print(turns[turn8]);
    lcd.print(turns[turn9]);
    lcd.print(turns[turn10]);
    lcd.setCursor(0, 3);
    lcd.print(turns[turn11]);
    lcd.print(turns[turn12]);
    lcd.print(turns[turn13]);
    lcd.print(turns[turn14]);
    lcd.print(turns[turn15]);

body:
Yes you can, and the solution is very simple. It's in two parts, and they make up part of the absolute fundamental building blocks not just in C, but in almost any programming language.

You can read good information on arrays [**here**][1], and 'for loops' [**here**][2] (it's about half way down the page). Without wishing to offend, it seems like you are missing some really basic concepts and I recommend starting at the beginning of the [**tutorial series**][3] that the two aforementioned links are part of.

I'll just cover the basics. If you don't understand anything, refer to the tutorials. If you *still* don't understand then please comment, but make sure you can convince us that you've really given it a good go. We're here to help as long as you're here to learn.

To declare an array of *N* variables, all of which are the same type, you use:

    <type> <name_of_variable> [<number_of_elements>];

    or:

    long turns[15];
Now you have an array of 15 `long`s. Ta da!

You now have to set the values of each turn. As your values are all the same (if you ignore the fact that `random()` ultimately leaves you with different values) you can use a **for loop**:

    for (int x=0; x<15; x++)
    {
        turns[x] = random(sizeof(turns) / sizeof(char*));
    }
I won't explain how a for loop works; I gave you a link to the tutorial to save me writing it all out myself.

That covers shrinking of part 1 and 2. Part 3 requires a little more thought. That said, as you didn't complete your *if* statement, I don't actually know what you plan to do if any two adjacent `turn` elements are the same. I shall assume that you would 're-randomise' one of the duplicates. For this you can again use a for loop, starting at the beginning and running to *N-1* th element, where *N* is the total number of elements:

    for (int x=0; x<14; x++)
    {
        if (turns[x] == turns[x+1])
        {
            turns[x+1] = random(sizeof(turns) / sizeof(char*));
        }
    }
You need make sure that `turns[x+1]` is not outside of the array, which is why the for loop runs for one iteration less than there are elements.

The fourth shrinkable part is just a matter of swtiching multiple print statements into single for loops:

    for (int x=0; x<NUMBER_OF_PRINTS_IN_1st_BUNCH; x++)
        lcd.print(turns[x]);
    lcd.setcursor(0,2);
    for (int x=WHERE_YOU_LEFT_OFF; x<NUMBER_OF_PRINTS_IN_2nd_BUNCH; x++)
        lcd.print(turns[x]);
    lcd.setcursor(0,3);
    for (int x=WHERE_YOU_LEFT_OFF_AGAIN; x<NUMBER_OF_REMAINING_PRINTS; x++)
        lcd.print(turns[x]);

All done.

  [1]: http://www.cplusplus.com/doc/tutorial/arrays/
  [2]: http://www.cplusplus.com/doc/tutorial/control/
  [3]: http://www.cplusplus.com/doc/tutorial/


message:
Cannot open ov7670 output file

I have taken a data file using arduino and ov7670 camera module. In this project I used the famous code https://github.com/ComputerNerd/ov7670-no-ram-arduino-uno . But after taking the datafile ov7670NoRam.hex, I can't open it. I spent 3 hours to search how to open, but failed.

Could anyone please let me know how to have a look the image in .hex? or would it be possible to take image data from ov7670 directly to jpg?

I tried to convert the hex file to bin using hex2bin, but when I opened the bin, only errors occurred.

The following is the content of the ov7670NoRam.hex

    :100000000C9436000C944B000C944B000C944B0059
    :100010000C944B000C944B000C944B000C944B0034
    :100020000C944B000C944B000C944B000C944B0024
    :100030000C944B000C944B000C944B000C944B0014
    :100040000C944B000C944B000C944B000C944B0004
    :100050000C944B000C944B000C944B000C944B00F4
    :100060000C944B000C944B005244590011241FBEB9
    :10007000CFEFD8E0DEBFCDBF12E0A0E0B1E0EAE70D
    :10008000F2E002C005900D92A235B107D9F70E94A7
    :10009000AF000C943B010C9400008093BB0084E8FB
    :1000A0008093BC008091BC0087FFFCCF8091B90099
    :1000B000887F90E070E08617970709F408950E9402
    :1000C000A00084EA8093BC008091BC0087FFFCCF35
    :1000D0008091B900887F883009F408950E94A000BB
    :1000E000CF93DF93D82FC62F0E94610068E182E48E
    :1000F0000E944D0068E28D2F0E944D0068E28C2F17
    :100100000E944D0084E98093BC008FE99FE0019735
    :10011000F1F700C00000DF91CF910895CF93DF93F6
    :10012000EC0103C00E9470002296FE01849131967A
    :1001300064918F3FB9F76F3FA9F7DF91CF91089591
    :10014000259A90E285B1892785B92FEF31EE84E0B9
    :10015000215030408040E1F700C00000F3CFF89418
    :10016000239A8091B6008F798093B60083E48093C0
    :10017000B00089E08093B1001092B30087B1807F16
    :1001800087B98AB183708AB92FEF8BE792E9215042
    :1001900080409040E1F700C000008091B9008C7F62
    :1001A0008093B90088E48093B8001092C50081E084
    :1001B0008093C4008091C00082608093C00088E179
    :1001C0008093C10086E08093C20060E882E10E94D3
    :1001D00070002FEF81EE94E0215080409040E1F7D5
    :1001E00000C0000080E091E00E948E0060E285E1A6
    :1001F0000E94700060E08CE00E9470008AE392E050
    :100200000E948E0088E492E00E948E0069E181E104
    :100210000E947000E8E6F0E094918091C00085FFB4
    :10022000FCCF9093C6008091C00085FFFCCF319633
    :1002300084918111F1CF4B9BFECF4B99FECF40EEC5
    :1002400051E08FE792E04A99FECF36B129B1207F85
    :100250003F70232B2093C6004A9BFECF9C01215068
    :100260003109892B11F0C901EECF415051094115D7
    :0A027000510539F7CFCFF894FFCF06
    :10027A0012803A0412001713180132B619021A7AB8
    :10028A00030A0C003E00703A7135721173F0A20134
    :10029A0015027A207B107C1E7D357E5A7F69807616
    :1002AA0081808288838F849685A386AF87C488D706
    :1002BA0089E813C0000010000D401418A505AB070B
    :1002CA002495253326E39F78A068A103A6D8A7D84A
    :1002DA00A8F0A990AA9413C5300031000E610F4B03
    :1002EA0016021E07210222912907330B350B371DEF
    :1002FA003871392A3C784D404E20690074108D4F70
    :10030A008E008F009000910096009A00B084B10C84
    :10031A00B20EB382B80A430A44F045344658472815
    :10032A00483A59885A885B445C675D495E0E6C0A94
    :10033A006D556E116F9E6A400140026013C74F806F
    :10034A00508051005222535E5480589E41083F000B
    :10035A00750576E14C0077013D484B09C960564066
    :10036A0034113B12A48296009730982099309A84CF
    :10037A009B299C039D4C9E3F78047901C8F0790F14
    :10038A00C8007910C87E790AC880790BC801790C2F
    :10039A00C80F790DC8207909C8807902C8C07903C5
    :1003AA00C8407905C8307926FFFF32F617131801BD
    :1003BA0019021A7A030AFFFF12013D08413D76E14C
    :0203CA00FFFF33
    :00000001FF

body:
What is it you hope to achieve by "opening" the hex file or "converting it to binary"?

A hex file is a compiled sketch. It is intended to be installed into the Arduino Uno using avrdude.


body: I am the author of the code and needless to say I am very confused right now on what you are trying to do. You run make writeflash in order to do what the target names implies write the hex file to microcontroller's internal flash memory. After that is done the code will run and you will use my frame grabber https://github.com/ComputerNerd/simpleFrameGrabber to capture an image.


message:
Cleaning up code? Removing repetition?

I am using Adafruit motor shield, I am running multiple DC motors for different amounts of time, but to start at the same time - I have researched that to do this I have to monitor the elapsed time of each motor in the loop instead of using the delay to avoid blocking if I want them to run at the same time.

Eventually, There will be around 10 DC motors running off this, however it seems very sloppy to me to have 10 repeat entries of very similar code.

Is there a way to create a class or something for the following code so I am not repeating it all as although it works it seems like the way I am currently doing it is bad practice(?) and could be done more eloquently! Forgive me if this is a strange question as I am new to arduino.

In this example there are only 2 motors, however when it gets to around 10, there will be a lot of code just for this bit!

Any suggestions are welcome.

Thanks in advance.

Example code:

    #include <Wire.h>
    #include <Adafruit_MotorShield.h>

    boolean runMotor1 = false;
    boolean Motor1Running = false;
    unsigned long Motor1StartMillis;
    unsigned long Motor1RunTime = 5000;

    boolean runMotor2 = false;
    boolean Motor2Running = false;
    unsigned long Motor2StartMillis;
    unsigned long Motor2RunTime = 10000;

    //etc etc etc up to 10 Motors

    Adafruit_MotorShield AFMS = Adafruit_MotorShield();
    Adafruit_DCMotor *MotorMotor1 = AFMS.getMotor(1);
    Adafruit_DCMotor *MotorMotor2 = AFMS.getMotor(2);

    void setup()
    {
      Serial.begin(9600);
      AFMS.begin();
      runMotor1 = true;  // set condition to true for testing
      runMotor2 = true;
    }
    void loop()
    {
    /// Motor1 START
      if (runMotor1 == true) {
         Serial.println("Run Motor 1!");
         runMotor1 = false;
        MotorMotor1->setSpeed(255);
        MotorMotor1->run(FORWARD);
        Motor1StartMillis = millis();
        Motor1Running = true;
      }

      if( Motor1Running && (millis()-Motor1StartMillis > Motor1RunTime) )
      {
        Serial.println("Motor1 Time Elapsed!");
        MotorMotor1->setSpeed(0);
        MotorMotor1->run(RELEASE);
        runMotor1 = false;
        Motor1Running = false;
      }

      /// Motor 2
        if (runMotor2 == true) {
         Serial.println("Run Motor 2!");
         runMotor2 = false;
        MotorMotor2->setSpeed(255);
        MotorMotor2->run(FORWARD);
        Motor2StartMillis = millis();
        Motor2Running = true;
      }

      if( Motor2Running && (millis()-Motor2StartMillis > Motor2RunTime) )
      {
        Serial.println("Motor2 Time Elapsed!");
        MotorMotor2->setSpeed(0);
        MotorMotor2->run(RELEASE);
        runMotor2 = false;
        Motor2Running = false;
      }

    }

Thanks for reading, and thank you for any input you may have.
Steve

body:
You are perfectly right, a class would help simplify your code. Here is
a tentative class that should work for what you are doing:

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

    class Motor
    {
    public:
        Motor(const char *_name, Adafruit_DCMotor *_motor,
              unsigned long _runTime)
        : name(_name), startNow(false), running(false),
          runTime(_runTime), motor(_motor) { }
        void start() { startNow = true; }
        void update();
    private:
        const char *name;
        boolean startNow;
        boolean running;
        unsigned long startTime;
        unsigned long runTime;
        Adafruit_DCMotor *motor;
    };

Most of this is almost copy-paste from your actual code, except for your
`runMotorX` variables that I renamed `startNow`, which seemed more
appropriate.

Beware that the name of the motor is copied as a pointer. Thus you
should better call the constructor with a literal string (like
`"the name"`) as a first parameter. Otherwise it would be more
appropriate to allocate memory and copy the characters themselves, but I
like to avoid dynamic memory allocation on an Arduino if I can.

Now, all the code that you have in `loop()` for each motor would be the
Motor's `update()` method:

    void Motor::update()
    {
        if (startNow) {
            Serial.print("Run ");
            Serial.print(name);
            Serial.println('!');
            startNow = false;
            motor->setSpeed(255);
            motor->run(FORWARD);
            startTime = millis();
            running = true;
        }

        if (running && (millis()-startTime > runTime))
        {
            Serial.print(name);
            Serial.println(" Time Elapsed!");
            motor->setSpeed(0);
            motor->run(RELEASE);
            running = false;
        }
    }

With this class, your code would now look like:

    Adafruit_MotorShield AFMS = Adafruit_MotorShield();
    Motor m1("Motor 1", AFMS.getMotor(1),  5000);
    Motor m2("Motor 2", AFMS.getMotor(2), 10000);
    //etc etc etc up to 10 Motors

    void setup()
    {
        Serial.begin(9600);
        AFMS.begin();
        m1.start();
        m2.start();
    }

    void loop()
    {
        m1.update();
        m2.update();
    }

Of course, when you get to 10 motors, this would still be annoying
repetition. You can simplify further by putting the motors in an array
and looping through it:

    Adafruit_MotorShield AFMS = Adafruit_MotorShield();
    Motor motors[] = {
        Motor("Motor 1", AFMS.getMotor(1),  5000),
        Motor("Motor 2", AFMS.getMotor(2), 10000)
        //etc etc etc up to 10 Motors
    };
    #define NUM_MOTORS (sizeof motors / sizeof motors[0])

    void setup()
    {
        Serial.begin(9600);
        AFMS.begin();
        for (unsigned int i = 0; i < NUM_MOTORS; i++)
            motors[i].start();
    }

    void loop()
    {
        for (unsigned int i = 0; i < NUM_MOTORS; i++)
            motors[i].update();
    }


message:
Call a class method from inside the same class

If i have file cSpeedOfSound.h:

    #ifndef cSpeedOfSound_h
    #define cSpeedOfSound_h
    #include "Arduino.h"
    #include "math.h"
    class cSpeedOfSound{
     public:
      cSpeedOfSound(float *i,float *C);
     private:
      float *C;
      float *a;
      float *i;
     };
    #endif

and file cSpeedOfSound.cpp:

    #include "cSpeedOfSound.h"
    cSpeedOfSound::cSpeedOfSound(float *i,float *C){
     //some code...
     *C =roundto(*C,2);}
    float cSpeedOfSound::roundto(float x,float dp){
    return (round(x*pow(10., dp)) / pow(10., dp));}

where i want to run function roundto inside class, but it doesnt seems to work. So what im making wrong and how to do it properly?

Ps: Im begginer to arduino (want it to learn robotics + C language) and know python (learnd for about 1+ year), so pls do not hate me if i made crucial mistakes.

body:
You need to include `roundto()` in your class declaration, e.g. something like this:

    class cSpeedOfSound {
    public:
        cSpeedOfSound(float *i,float *C);

    private:
        float roundto(float x, float dp);

        float *C;
        float *a;
        float *i;
    };

In C++, class structures are fixed. You can define the body of a function almost anywhere, but all member functions/data must be specified in the original declaration.

---
As a side note, it's worth pointing out that you have a naming conflict in your code. You have member variables called `i` and `C`, **and** you have totally separate function parameters called `i` and `C`. The compiler won't complain about this (the function parameters will simply mask the member variables), but it may not do what you expect.


message:
What is the difference between file.print() and file.write()

From [here][1] I think I understand the difference between Serial.write and Serial.print, but is it the same when writing to a file in a SD card for example. Does it mean that File.write saves bytes in the file instead of text?

  [1]: https://arduino.stackexchange.com/questions/10088/what-is-the-difference-between-serial-write-and-serial-print-and-when-are-they

body:
The File class inherits from the Stream class, which in turn inherits from the Print class.

The Serial class inherits from the Stream class, which in turn inherits from the Print class.

`print()` and `write()` are defined by the Print class.

So yes, File.print() and Serial.print() are the same, as are File.write() and Serial.Write().


message:
What is the most memory-friendly way to declare integer literals?

I'm having SRAM overflow problems with my 8bit atmega328p in my Arduino Uno, which has 2KB of SRAM, so I'm defining all my for loops with bytes as counters instead of ints. As in:

    for(byte i=0;i<16;i++) buf[i]=(char)ap1[i];

Would it make any difference if I declared the integer literal 16 as a constant?

    const byte BUFSIZE=16;

Or using the preprocessor:

    #define BUFSIZE 16

There's also the macro `PROGMEM` which stores variables in flash memory, which I've decided to use for all my constants, but is it not the point of const to do this? as well as aiding the compiler in warning you if you screwed up changing the variable.

    const byte BUFSIZE PROGMEM=16;

AFAIK, using const would save BUFSIZE in the flash memory, but how about using the preprocessor? Using the preprocesor would be the exact the same as using the literal 16, as far as i'm concerned.

This fear arose from the fact that string literals are saved in Flash and then transferred to SRAM, wasting twice the space, which you can solve using the arduino macro F("thisisastring"), which stores them in flash memory, and I don't want to waste 2 bytes of SRAM in every for loop I use

body:
Yes, defining "const byte bufsize" would make a difference - it'll use one additional byte of SRAM. All variables are stored in RAM unless they're annotated as being PROGMEM.

A #define gets translated into its value by the preprocessor, and so looks the same to the compiler.

Your constant '16' isn't taking up any SRAM in the first place; look elsewhere (at actual variables) if you need to optimise.

String literals are treated the same way as arrays of any numeric type: they're copied to SRAM on startup because the code has to be able to dereference the pointer (which is what myarray[x] does) and find the location in RAM. Single numeric constants do not have this issue - they're value types - and so don't get copied into RAM.


body:
I'm not familiar with the Atmel megaAVR microcontrollers or Arduino.  But generally speaking, your memory optimization ideas are misguided.

For example, it's likely that the compiler implements local loop variables within a register so that they don't consume any RAM at all.

And the integer literal constants, such as 16 from your example, also likely don't consume any RAM.  The compiler likely incorporates these constants into the code.

Whenever you optimize something it's best to go after the big fish first.  You're focusing on the tiniest fish.  To find the big fish, look at the *.map file produced by the linker.  The map file should show how much RAM and Flash memory is used by your program.  The RAM sections might be labeled "bss" and "data" in the map file.  Hopefully the map file will also detail how much RAM is used by each compilation unit.  Find the compilation units that are using the most RAM and focus on them.  Maybe there are large buffers or arrays defined in those compilation units that can be reduced in size or redesigned.

The map file is also where you could check to see if your optimizations have made any difference.  For example, try some of the optimization you described and see whether the map file changes significantly.


body:
Well, it's easy to just try and see... Let's try the following program:

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

    #ifdef USE_CONST
    const byte BUFSIZE = 16;
    #else
    #  define BUFSIZE 16
    #endif

    char buf[BUFSIZE], ap1[BUFSIZE];

    int main(void)
    {
        for (byte i = 0; i < BUFSIZE; i++)
            buf[i] = ap1[i];
        return 0;
    }

I compiled this for an Uno both with and without `#define USE_CONST`,
and it doesn't make any difference! avr-size reports the same sizes for
both versions, and the generated assemblies are identical: the optimizer
transformed the loop into something like

    byte *Z = ap1;
    byte *X = buf;
    do {
        *X++ = *Z++;
    } while (Z != ap1 + 16);

where X and Z are two of the CPU's pointer registers, and `ap1 + 16` is
an _immediate_ constant, i.e. part of the instruction itself, c.f. the
[AVR addressing modes](http://www.csee.umbc.edu/~alnel1/cmpe311/notes/AVRAddressingModes.pdf).

It is worth noting that, in C++,
[`const` implies internal linkage](https://stackoverflow.com/a/998457).
Thus a const global variable is very much like a preprocessor constant.

This is unlike C, where you would need to qualify the variable as
`static const` in order to get the same behavior. Otherwise the compiler
would need to allocate storage to `BUFSIZE`, just in case it is
referenced as `extern` from another source file, even though it can
replace occurrences of `BUFSIZE` _in the same file_ with its immediate
value.

On the other hand, the Arduino IDE compiles your code with
[-ffunction-sections -fdata-sections](https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#index-funswitch-loops-1114)
and links it with
[--gc-sections](https://sourceware.org/binutils/docs/ld/Options.html#index-garbage-collection-179),
which means the linker will eventually get rid of the unused reserved
storage.


message:
Sketch stops working after ~40 minutes. Overflow?

I have this simple sketch I use on Arduino Micro:

    int fan = 3;
    int led = 13;
    int ledState = HIGH;         //all'inizio gira
    //unsigned long time;
    unsigned long prevMicros = 0;        // will store last time LED was updated  +
    unsigned long interval =  7000000;           // lunghezza della pausa in secondi
    unsigned long intervalON =  1000000;           // lunghezza del ON in secondi

    void setup() {
     pinMode(fan, OUTPUT);
     pinMode(led, OUTPUT);
     prevMicros = micros();
    }

    void loop() {
      unsigned long currMicros = micros();

      // manage overflow? BOH
       if (ledState == HIGH && (((unsigned long)(currMicros  - prevMicros)) >= intervalON)){
         prevMicros = currMicros;
          ledState = LOW;
        }
        else if (ledState == LOW && (((unsigned long)(currMicros - prevMicros)) >= interval)){
          ledState = HIGH;//riparte
          prevMicros = currMicros;
        }

        digitalWrite(led, ledState);
        digitalWrite(fan, ledState);
    }

I could use `millis()` instead of `micro()`, but I decided to keep this to shorten the overflow rate (should be 72 minutes). I shall go back to `millis()` once my issue is fixed.

 The sketch works as expected, turning on the LED for a second every 7, but **the sketch hangs after 40 minutes**. Can you tell me why, and how to manage overflow properly? Why is it hanging after 40 and not 72 minutes? Thanks

body:
When comparing time intervals, use unsigned long instead of long.

    if ( ... (((unsigned long)(currMicros - prevMicros)) >= intervalON) )

The time counter overflows at some point -- micros() overflows after 70 minutes, milis() overflows after nearly a month -- but these are unsigned values.

When an unsigned value is interpreted as a signed value -- `(long)` instead of `(unsigned long)` -- then half of the values are interpreted as negative numbers. So after 40 minutes, the micros() value looks like a negative number, and the (curr-prev) >= interval comparison returns false. After 70 minutes, the micros() overflows back to 0, and the signed comparisons work as expected.

The solution is to use unsigned long for all delta-time comparisons.

This is easier to see if you consider a smaller, 3-bit number: there are 8 values for a 3-bit number. If the 3-bit number is unsigned, then the values are 0, 1, 2, 3, 4, 5, 6, 7. But if the 3-bit number is signed, then those same binary code numbers are interpreted as 0, 1, 2, 3, -4, -3, -2, -1. Same principle for int and long values, just a larger range of values.

EDIT:

Based on your comment below, I did some testing on my own hardware (Sparkfun "red board" Arduino UNO R3 clone), and added some code to help make it more testable. Some highlights:

 1. Added a diagnostic LED on Arduino pin 9, to indicate when the timer overflow has happened (i.e. new time is less than previous time).
 2. Added a mask to force the timer overflow to happen sooner, so I don't have to wait an hour to verify whether the code had any effect.
 3. Calculated timeSinceLastChange and applied mask, to handle overflow.
 4. Added TIMER_DATATYPE based on jippie's comment

The complete code:

    //--- based on comment from jippie about using C++ standard width integer types
    // #define TIMER_DATATYPE unsigned long
    #define TIMER_DATATYPE uint32_t

    //--- MarkU: diagnostic LED to indicate that timer overflow happened.
    // Comment out this line for normal operation.
    #define DIAGNOSTIC_LED_TIME_OVERFLOW 9
    //---

    //--- MarkU: diagnostic: force timer overflow to happen sooner.
    // This must be significantly longer than the intervals being measured.
    // Must be a binary all-1's bitmask.
    // 0x3FFFFFF overflow after approximately 1 minute
    // 0xFFFFFFF overflow after approximately 5 minutes
    // 0xFFFFFFFF overflow after approximately 70 minutes
    #define DIAGNOSTIC_TIMER_OVERFLOW_MASK 0x3FFFFFF
    //---

    int fan = 3;
    int led = 13;
    int ledState = HIGH;         //all'inizio gira
    //unsigned long time;
    TIMER_DATATYPE prevMicros = 0;        // will store last time LED was updated  +
    TIMER_DATATYPE interval =  7000000;           // lunghezza della pausa in secondi
    TIMER_DATATYPE intervalON =  1000000;           // lunghezza del ON in secondi

    void setup() {
      pinMode(fan, OUTPUT);
      pinMode(led, OUTPUT);

      //--- MarkU: diagnostic LED indicate that timer overflow happened
    #if DIAGNOSTIC_LED_TIME_OVERFLOW
      pinMode(DIAGNOSTIC_LED_TIME_OVERFLOW, OUTPUT);
      digitalWrite(DIAGNOSTIC_LED_TIME_OVERFLOW, LOW);
    #endif // DIAGNOSTIC_LED_TIME_OVERFLOW
      //---

      prevMicros = micros();
    }

    void loop() {
      TIMER_DATATYPE currMicros = micros();

      //--- MarkU: diagnostic: force timer overflow to happen sooner
    #if DIAGNOSTIC_TIMER_OVERFLOW_MASK
      currMicros = (TIMER_DATATYPE)(currMicros & ((TIMER_DATATYPE)DIAGNOSTIC_TIMER_OVERFLOW_MASK));
    #endif // DIAGNOSTIC_TIMER_OVERFLOW_MASK

      //--- MarkU: consolidate time delta calculation
      TIMER_DATATYPE timeSinceLastChange;
      if (currMicros < prevMicros) {
        //--- MarkU: handle timer overflow
    #if DIAGNOSTIC_LED_TIME_OVERFLOW
        digitalWrite(DIAGNOSTIC_LED_TIME_OVERFLOW, HIGH);
    #endif // DIAGNOSTIC_LED_TIME_OVERFLOW
    #if DIAGNOSTIC_TIMER_OVERFLOW_MASK
        timeSinceLastChange = (currMicros - prevMicros) & DIAGNOSTIC_TIMER_OVERFLOW_MASK;
    #else // DIAGNOSTIC_TIMER_OVERFLOW_MASK
        timeSinceLastChange = (currMicros - prevMicros) & 0xFFFFFFFF;
    #endif // DIAGNOSTIC_TIMER_OVERFLOW_MASK
      } else {
        timeSinceLastChange = currMicros - prevMicros;
      }
      //---

      // manage overflow? BOH
      if (ledState == HIGH && (timeSinceLastChange >= intervalON)) {
        prevMicros = currMicros;
        ledState = LOW;
      }
      else if (ledState == LOW && (timeSinceLastChange >= interval)) {
        ledState = HIGH;//riparte
        prevMicros = currMicros;
      }

      digitalWrite(led, ledState);
      digitalWrite(fan, ledState);
    }


message:
How to int variables with similar names without tons of code?

I'm using `int` with 14 LEDs to specify pins, but I don't want to use int 14 times, like this:

    int led1 = 2;
    int led2 = 3;
    int led3 = 4;
    int led4 = 5;
    int led5 = 6;
    int led6 = 7;
    int led7 = 8;
    int led8 = 9;
    int led9 = 10;
    int led10 = 11;
    int led11 = 12;
    int led12 = 13;
    int led13 = 45;
    int led14 = 46;
is there any way to not do this?
Also, to define them as output, is there any way to avoid using `pinMode(***, OUTPUT)` 14 times as well?

body:
The word you are looking for is *array*.

An *array* is like a list of values all of the same type.  For instance, your LED pins could be specified as:

    int leds[14] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 45, 46 };

You can then access the LEDs by number.  Note that arrays *start counting from zero* not from one, so you would have:

    leds[0]
    leds[1]
    leds[2]
    ... etc to ...
    leds[12]
    leds[13]

It's great for using them in an array:

    for (int i = 0; i < 14; i++) {
        pinMode(leds[i], OUTPUT);
    }

If the values are never going to change, as in this case since they are pin numbers, the array should be declared *const* so it doesn't take up any of your precious RAM:

    const int leds[14] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 45, 46 };

Also you should get into the habit of tailoring the data types to the expected values.  If the values are never going to exceed 255 then you should use "byte" not "int", or better still the C standard "uint8_t".

    const uint8_t leds[14] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 45, 46 };

    for (uint8_t i = 0; i < 14; i++) {
        pinMode(leds[i], OUTPUT);
    }

An *int* takes two *bytes*, so using *int* when you can get away with *uint8_t* means you're wasting half the memory.


message:
Where is documentation on Arduino's Internal Interrupts?

First time arduino programmer here...however I have programmed the TI MSP430 in the past...

I am trying to figure out how to configure internal Interrupt Vectors on this Arduino Uno.

In the Arduino IDE, I am skeptical about writing lines of code like

    ISR(TIMER1_CAPT_vect) {
        Serial.Print("Entered Capture Vector");
    }

Because it doesn't appear to matter what I type inside ISR(), for instance I can write
    ISR(GibERisH) {
    }

And it still compiles and uploads to the arduino. What?! Also how could Arduino IDE know what the heck TIMER1_CAPT_vect is without having the library?

I found a list of interrupt vector names here: http://www.nongnu.org/avr-libc/user-manual/group__avr__interrupts.html

But I can not find documentation ANYWHERE ELSE on what to call these interrupt vectors.

Should I abandon the Arduino IDE and go with the Atmel Studio 6.2 (There is a juicy looking arduino plug-in...)? I need advanced control of the guts of this processor, and there is zero documentation about how to do this anywhere on the internet.

_________________________________________________________

EDIT: I realized my problem was I was looking for documentation for the atmega16U2 (that does something else on the board), not the atmega328P.

body:
The vector names are all defined within the header files for the main chip in the compiler.  The IDE doesn't need to know anything about that kind of thing - that's all up to the compiler.

Look for the files "lib/avr/include/avr/io*.h within the compiler in your chosen IDE.  In there are all the chips and all their definitions.

For instance, the ATMega328P definition (iom328p.h) has this list:

    #define INT0_vect         _VECTOR(1)   /* External Interrupt Request 0 */
    #define INT1_vect         _VECTOR(2)   /* External Interrupt Request 1 */
    #define PCINT0_vect       _VECTOR(3)   /* Pin Change Interrupt Request 0 */
    #define PCINT1_vect       _VECTOR(4)   /* Pin Change Interrupt Request 0 */
    #define PCINT2_vect       _VECTOR(5)   /* Pin Change Interrupt Request 1 */
    #define WDT_vect          _VECTOR(6)   /* Watchdog Time-out Interrupt */
    #define TIMER2_COMPA_vect _VECTOR(7)   /* Timer/Counter2 Compare Match A */
    #define TIMER2_COMPB_vect _VECTOR(8)   /* Timer/Counter2 Compare Match A */
    #define TIMER2_OVF_vect   _VECTOR(9)   /* Timer/Counter2 Overflow */
    #define TIMER1_CAPT_vect  _VECTOR(10)  /* Timer/Counter1 Capture Event */
    #define TIMER1_COMPA_vect _VECTOR(11)  /* Timer/Counter1 Compare Match A */
    #define TIMER1_COMPB_vect _VECTOR(12)  /* Timer/Counter1 Compare Match B */
    #define TIMER1_OVF_vect   _VECTOR(13)  /* Timer/Counter1 Overflow */
    #define TIMER0_COMPA_vect _VECTOR(14)  /* TimerCounter0 Compare Match A */
    #define TIMER0_COMPB_vect _VECTOR(15)  /* TimerCounter0 Compare Match B */
    #define TIMER0_OVF_vect   _VECTOR(16)  /* Timer/Couner0 Overflow */
    #define SPI_STC_vect      _VECTOR(17)  /* SPI Serial Transfer Complete */
    #define USART_RX_vect     _VECTOR(18)  /* USART Rx Complete */
    #define USART_UDRE_vect   _VECTOR(19)  /* USART, Data Register Empty */
    #define USART_TX_vect     _VECTOR(20)  /* USART Tx Complete */
    #define ADC_vect          _VECTOR(21)  /* ADC Conversion Complete */
    #define EE_READY_vect     _VECTOR(22)  /* EEPROM Ready */
    #define ANALOG_COMP_vect  _VECTOR(23)  /* Analog Comparator */
    #define TWI_vect          _VECTOR(24)  /* Two-wire Serial Interface */
    #define SPM_READY_vect    _VECTOR(25)  /* Store Program Memory Read */

Further, _ISR() is just a macro.  It creates a suitable function prototype for your function, and if that happens to include a valid vector then it becomes an ISR.

    #  define ISR(vector, ...)            \
        extern "C" void vector (void) __attribute__ ((signal,__INTR_ATTRS)) __VA_ARGS__; \
        void vector (void)

That is defined in "avr/interrupt.h" in the compiler's include files.  With your gibberish you'd end up with:

    extern "C" void GibERisH (void) __attribute__ ((signal,__INTR_ATTRS));
    void GibERisH (void) {
        // something here
    }

With a real vector you'd get the more meaningful:

    extern "C" void _VECTOR(7) (void) __attribute__ ((signal,__INTR_ATTRS));
    void _VECTOR(7) (void) {
        // something here
    }

Of course, _VECTOR() itself is a macro:

lib/avr/include/avr/sfr_defs.h:#define _VECTOR(N) __vector_ ## N

So that further expands out to:

    extern "C" void __vector_7 (void) __attribute__ ((signal,__INTR_ATTRS));
    void __vector_7 (void) {
        // something here
    }

And magically, that new function name of `__vector_7` is directly referenced from the standard vector handling code in the startup library *crt* of the AVR compiler.


body:
    ISR(TIMER1_CAPT_vect) {
        Serial.Print("Entered Capture Vector");
    }

Rule #1. Don't do serial prints inside an ISR. Doing that will likely hang the sketch.

> Because it doesn't appear to matter what I type inside ISR(), for instance I can write ISR(GibERisH) { }

Yes you can do that. It just degrades into some function that is never called. The way it is organized with all the defines, any non-valid ISR name effectively creates a non-ISR function, which is therefore ignored. Even getting the capitalization wrong can cause this.

>  I need advanced control of the guts of this processor, and there is zero documentation about how to do this anywhere on the internet.

There is a considerable amount of detail on my site: <http://www.gammon.com.au/interrupts>


message:
Do I need 3 full-size arduinos to control this LED setup?

I'm sourcing the parts now for an LED *persistence of vision* setup on a bicycle.  Two wheels with anywhere between 16-32 LED's per wheel, as well as 24 LED's mounted on the frame of the bike itself

Since the Arduinos have to be mounted into the wheels to drive the POV displays - do I need a total of 3 arduinos?

Driven by 2x [Nano 3.0 Atmel Atmega328P Mini-USB Board][1] + an Arduino Uno from the frame?
So far I think I'll pick up 2 x [433Mhz RF Transmitter Module + Receiver Module Link Kit][2] for wireless control, [Reed Switch Magnetic Detection Sensor Module][3] for calculating velocity from a small magnet mounted somewhere on one of the forks. 4 x [WS2811 RGB 8-LED Light Strip Module][4] as the POV LED's, or maybe some of the [DotStar Digital LED][5]
and miscellaneously perhaps are some of these required/ useful? maybe instead of the 4x8 I could go 4x [SSC Seoul P4][6], or from [SparkFun][7],  following pieces of [this guide][8]

 - DIY AT89S52 Microcontroller Development Board Set
 - [KT0026 Electronic Parts Pack][9]
 - [Square Prototyping Plate][10]
 - [ZnDiy-BRY Z-069 MB102 Breadboard + Power Supply Module][11]

My main concern is refresh rates....getting everything controlled...and making sure I have enough I/O. Any help would be greatly appreciated.  (URL's available on request :P)

body: Those WS2811 strips are a good idea. You can control them all from pins on the same port which will make the control a little more complex but multiply the refresh rate, or you can chain all of them off a single pin if you find the refresh rate high enough that way.


body:
You wouldn't necessarily need full Arduinos - you could prototype them on Arduinos, then move them to just Atmel chips on your own board (e.g. stripboard). To do this, you would need your own resonator, power supply, and programming. Resonators are cheap and easy, you would probably want to set up your own power supply anyway (3 AA batteries is a perfect power supply for the Atmel), and you can program using a USBISP or similar, right from inside the Arduino IDE.

As for speed, I see a bicycle wheel is on the order of 26 inches/660mm diameter. This makes the perimeter about 6 foot 9 inches/2 meters (sounds like a lot, doesn't it?). Google tells me that a sprint on a bike by a fit person is about 40km/h, or 11 meters/second, making 5.5 revs/second of the wheel - about 180 milliseconds/revolution. This means that if you want 1 degree accuracy, you're going to have to change ALL the (changing) leds at about 2khz. The Arduino can run at up to 20mhz, giving you 10,000 instructions to change the leds. Plenty of time.

If you have strips, you should check the specs on the strips to see how fast you can change them. Remember that you probably have to update ALL of them, and you want most of the time to be spent between updates; while you are updating, it may show unwanted lights on/off.


body:
Maybe look at [NeoPixels Revealed: How to (not need to) generate precisely timed signals](http://wp.josh.com/2014/05/13/ws2812-neopixels-are-not-so-finicky-once-you-get-to-know-them/). The author there controlled 1000 Neopixels with a Duemilanove with fairly simple code. These were WS2812 not WS2811 but perhaps the code could be adapted to suit. Judging by the datasheets they are fairly similar.

Since he got 30 fps with 1000 pixels, your requirement of around 100 pixels would seem fairly straightforward.


message:
IDE to program Arduino Uno especially internal interrupt vectors

I am trying to program this Arduino Uno's Timer1 module to use its Input Capture pin to record the times of edges and store / transmit them during the Input Capture Interupt Service Routine, but I cannot find documentation on how to program the guts of this Arduino Uno?

What IDE do people use to do advanced things with their Arduinos? I am trying to use Atmel Studio 6 after I gave up using the Arduino IDE and now I'm trying to use Visual Micro plug-in for visual studio.

Suggestions?

body:
You can do all you need to do in the Arduino IDE.  It doesn't "block" you from doing any low-level operations.  Any other IDE will also allow you to do what you want.

All the information you need to manipulate the "guts" of the Arduino is the datasheet for the main chip - the ATMega328P on the Uno.

http://www.atmel.com/images/atmel-8271-8-bit-avr-microcontroller-atmega48a-48pa-88a-88pa-168a-168pa-328-328p_datasheet.pdf