body:
As already mentioned, everything to the left of the relays is completely irrelevant when it comes to what the system can cope with.  It's purely down to the relays what voltage and current they can deal with.  As far as the circuit goes there's nothing wrong with it that I can see at first glance.

So to go from there to an actual physical shield there are a number of things you do need to consider:

1. Ensure that the relays have a rating *at least* as high as the expected maximum voltage and current, ideally *derate* it by *at least* 50%.  For CFLs (which present an inductive load as well as a resistive load) you want to dereate it even more.
2. Ensure that the mains voltage track layout is kept well away from the low voltage digital signals and ground plane.
3. Ensure that the mains voltage tracks are sized appropriately and kept as short as reasonably possible.  Use a track width calculator to get the right width.
4. Be sure to use appropriate connectors for the mains power.  They need to be able to cope with as much current and voltage as the relays and at the same time be *safe*.
5. Keep all mains voltages away from human contact.  This means no exposed live metal on the upper side of your board where it can be inadvertently touched.  Any components with exposed leads that have mains voltage in them should have their leads insulated.
6. Be absolutely certain that, since this is a shield, no mains voltages even come close to the Arduino the shield is plugged into.  This is especially critical around such areas as the USB socket where through-hole components (like screw terminal blocks) are likely to short circuit and cause very very nasty things to happen.

**Remember: Mains voltages are dangerous, caution and safety should be your first concern over everything else!**

One more tip: Do all your mains experimentation as safe as possible.  Either ensure that you have an [ELCB](https://en.wikipedia.org/wiki/Earth_leakage_circuit_breaker) *and* an [RCD](https://en.wikipedia.org/wiki/Residual-current_device) on your ring main / power outlet (with the former you must ensure that you have your earth wires connected properly), or even better (and what I would certainly recommend above all else), use an [Isolation Transformer](https://en.wikipedia.org/wiki/Isolation_transformer) to separate you from the mains circuit entirely.  With an Isolation Transformer electrocution is only possible if you contact *both* terminals at once as opposed to just one terminal of the normal mains supply.

**Edit:** One thing that does puzzle me with your circuit is how you have wired up the common pin of the relays.  That part of the circuit makes no sense to me at all.  You should have 2 connections to each relay - *in* and *out* where *in* connects to the *NO* and *out* connects to the *common* pin¹.  The only way your arrangement could work would be to designate one relay as a *master* power control and that one has the main power coming in which then feeds through to the common rail to supply the other three relays.  If this is what you want, then you will have to ensure that the relay designated as master (and its connector) has *at least* three times the capacity of the other three relays and connectors (or all four relays have *at least* three times the capacity you would otherwise need).

---

¹ Note: doing it this way around ensures that when the relay is in the *off* position the *NC* pin isn't live.  The only pin that would ever be live is the *common* pin.  Safety first...!


sender: user

message:
IR frequency difference

I want to create a device that interfaces with the Light Strike Lasertag system using an Arduino Leonardo.

The Light Strike system uses not laser but regular infrared signals. According to a site that I found (http://www.meatandnetworking.com/projects/hacking-at-the-light-strike-laser-tag-game/) it uses 37.8 khz signals. I only found IR-receivers using 37.9 or 38 khz. Can I use them? How far can the modulation frequency differ?

Is there anything else I need to watch out for when creating an IR-interface?

sender: assistant

body:
> Can I use 37.9 or 38 kHz IR-receivers for 37.8 khz communication?

Yes you can, it should be close enough. (I am assuming you are talking about some kind of prebuilt receiver that just receives the IR data and transmits it via RS232 or something like that)

--------

I'd suggest you'd use a phototransistor and a IR diode for the communication. You will have a lot more control over what frequencies you are operating on. Altho it might take a bit more work to program it, the end result will be exactly how you wish.


message:
XL335B accelerometer reports false readings

I'm using an XL335B accelerometer in a GY-61 breakout board. I'm powering the device using the UNO's built-in 3.3V power supply. The following code should convert the readings to m/s² (SI); however, it returns (-0.43|-0.52|-5.83) instead of the expected (0|0|-9.81) when lying untouched.

**Code:**

    const float CYCLE_LENGHT_MILLIS = 1000;

    // REFERENCE_VOLTAGE 5 & STEP_COUNT 1024
    // => VOLTAGE_STEP 0.0048828125
    // MAX_ACC_VOLTAGE 3.3
    // => MAX_ACC_VOLTAGE_STEP 675.84
    // MIN_ACC_VOLTAGE 1.65 = 0.5 MAX_ACC_VOLTAGE
    // => MIN_ACC_VOLTAGE_STEP 337.92
    // MAX_ACC_MEASUREMENT 29.43 = 3g

    // acceleration = (read()-MIN_ACC_VOLTAGE_STEP) * MAX_ACC_MEASUREMENT/(MAX_ACC_VOLTAGE_STEP-MIN_ACC_VOLTAGE_STEP)
    //This can be simplified to: acceleration = read()*j - k
    // => j = MAX_ACC_MEASUREMENT / (MAX_ACC_VOLTAGE_STEP-MIN_ACC_VOLTAGE_STEP)
    // => k = MIN_ACC_VOLTAGE_STEP * j

    const float j = 29.43/(675.84-337.92);
    const float k = 337.92*j;

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

    void loop(){
      Serial.print("(");
      Serial.print(analogRead(0) * j - k); //X-AXIS
      Serial.print("|");
      Serial.print(analogRead(1) * j - k); //Y-AXIS
      Serial.print("|");
      Serial.print(analogRead(2) * j - k); //Z-AXIS
      Serial.println(")");
      delay(CYCLE_LENGHT_MILLIS);
    }

body:
You are assuming here that 3g will result in the maximum voltage of 3.3v. This is not correct. The datasheet says it's 0.3v/g so; 0g-voltage + 3 x 0.3v => 1.65 + 3*0.3 = 2.55volt.

To get the g value use `(analogRead(0)-337.92)/61.44` (337.92 is the 0g voltage in steps; 61.44 is 0.3V is steps).

To get the acceleration is m/s² just multiply by 9.81; so `(analogRead(0)-337.92)/61.44*9.81`

Like you stated in the comments, the result isn't that accurate. Just have a look at the [datasheet](http://www.analog.com/media/en/technical-documentation/data-sheets/ADXL335.pdf). e.g. Volt per G is typically 300, but can be anything from 270 to 330. Same thing goes for the 0g voltage; 1.35V to 1.65V. So quite a bit of difference can occur between one chip and the next. Even between the 3 axis inside one chip.

So the best thing is to calibrate all 3 axis. For the Z axis; just lay the sensor flat, and get the analogRead value (-1g value). Flip the sensor upside down and get the analogRead value (+1g value). Optionally place the sensor on it's side to get 0g value or just calculate the value in the middle of the above two value. The steps-per-g will be the difference between the two divided by 2 (`+1g - -1g = 2g`). Put this value and the 0g step-value into the formula. Repeat the procedure for the other 2 axis.


body:
An effective but yet simple calibration is explained in https://chionophilous.wordpress.com/2011/08/26/accelerometer-calibration-ii-simple-methods/

> We need to find the 0G mark and the sensitivity on each axis.  Call them m_x, delta_x, m_y, delta_y, m_z, and delta_z (e.g. m_z is the zero-G mark or the “middle” on the z-axis, delta_z is the sensitivity on the z-axis).  That makes 6 numbers,  so we should expect to need at least 6 measurements.

Check also the more accurate setup: https://chionophilous.wordpress.com/2011/08/26/accelerometer-calibration-iii-improving-accuracy-with-least-squares-and-the-gauss-newton-method/

> Least-Squares
>
> Here is the idea.  We’ve been assuming that there are just six numbers we need to find to get a good calibration: m_x, m_y, m_z, delta_x, delta_y, and delta_z.   Now matter how we place our sensor before we take readings, we assume it is still and is detecting exactly 1G of acceleration in some direction.
>
> So if we read value x on the X-pin, y on the Y-pin, and z on the Z-pin we can look at the acceleration vector
>
> If our measurements have no noise and our parameters are correct, the length of this vector should be exactly 1 no matter which way it is pointing


message:
Count RISING edges of a wave form by using ARDUINO

I have realised an electrical circuit that gives 5V in output. When I press a button, it gives 0V.
So I have in output a square wave (5V - 0V).
I would like to count how many times I press the button, by using an Arduino MEGA AT2560.
I have written this code below, but it doesn't work, because when I press the button, it increase the counter three or four times.
For example: I press the button 5 times, but the counter has arrived to 30!

    #include <SD.h>
    #include <SPI.h>

    unsigned int count_hall_f = 0;

    void setup()
    {
      Serial.begin(9600);
      attachInterrupt(0, interrFront, RISING); //18
    }

    void loop(){

    }

    void interrFront() {
      count_hall_f++;
      Serial.println(count_hall_f);
    }

An example of the result is:

    1 <- I pressed here
    2
    3 <- I pressed here
    4
    5
    6
    7
    8
    9
    10
    11
    12 <- I pressed here
    13
    14
    15
    16

body:
Simple way to do it: since the first interrupt, wait a pre-determined amount of time (depends on the button you use, could be 100us to few tens of ms) and check again that the value is what triggered the interrupt.

This will kill the effect of the mechanical bounces.

You can even disable interrupts during the delay.

There are much more sophisticated way to do it, but this should be good enough to get you started on the way to debounce your inputs.


body:
> I have choosen the values of R and C by experiments. Do you have a suggest for choose these values?

I have a [page about switches](http://www.gammon.com.au/switches) - somewhat down the page is a discussion of debouncing, including some calculations which show how you can calculate the debounce time. With the switch pin pulled high by the internal pull-up (something you don't appear to be doing), and a 1 µF capacitor, that gives you a debounce of about 35 ms.

---

Example schematic:

[![Hardware debounce][1]][1]

Results on input pin:

[![Debounce scope image][2]][2]

(Maths supporting that figure on the above page).

---

Note that it is important to have a pull-up or pull-down for your switch or it will read random values if not closed.

  [1]: https://i.stack.imgur.com/Px1on.png
  [2]: https://i.stack.imgur.com/IvUfI.png


message:
Programming "Arduino" code to AT90S8515?

I found (from a previous life) an STK500 and a couple AT90S8515's in the recesses of my basement..  that I would like to put to use.

Is there a way in which I can write "arduino code" for the 8515?  I know that it's basically C/C++.

I also know that the 8515 doesn't have, or support, a bootloader like the Mega series of ICs do..  so I expect that I will need to program it using the STK500.

I downloaded AVR Studio, but I will admit, I became very lost, very quickly.

Thanks for any direction!

body: Theoretically yes, once you write a core (1.5.x/1.6.x) for it. I'm not sure if the IDE has a configuration for the STK500, but it should be easy enough to add (since avrdude already supports it).


body:
In Atmel Studio 7 you can create a project on Arduino Code.
For instance if you have a code for an Arduino UNO, it will ask for path of the sketch(a.ino file) and ask for device here it will be Atmega 328.
Now you can build the solution and it will generate code for Atmega 328.
Now you can rebuild the same solution by changing the device now select  AT90S8515.
In my case I built the code for a Atmega328. then rebuilt it by changing device to Atmega8. It worked


message:
Is there any problem about calling if (Serial) many times?

I am trying to debug a problem that I think may be related to the debug code itself and I tried to use theese macros:

    #define DEBUG_PRINT(x) { if (Serial) { Serial.print(x);} }
    #define DEBUG_PRINTLN(x) { if (Serial) { Serial.println(x);} }

That works a bit but everything starts running really slow and my sketch get to hung up quite fast. Maybe it is timing related but does not seems like that.

if I change that by this the problem is gone:

    #define DEBUG_PRINT(x) { if (true) { Serial.print(x);} }
    #define DEBUG_PRINTLN(x) { if (true) { Serial.println(x);} }

I'm using Arduino Pro Micro (Leonardo).

Is there any problem about calling if (Serial) so many times?

Full sketch [here][1]

  [1]: https://github.com/aalku/Arduino_ESP8266_HttpServer/tree/debugQuestion

body:
There is no *problem*, no, but yes it will slow you down.

This is the source code to the boolean operator for the Serial constructor for CDC:

    Serial_::operator bool() {
        bool result = false;
        if (_usbLineInfo.lineState > 0)
            result = true;
        delay(10);
        return result;
    }

As you can see from that all it does is check the value of a variable.  However it also imposes a 10ms delay¹.  Personally I'd have written it as:

    Serial_::operator bool() {
        return (_usbLineInfo.lineState > 0);
    }

And on top of that I'd have made it inline.

You might want to experiment by editing CDC.cpp to replace the bool operator with that smaller, leaner, code and see if it improves things (or breaks them completely)².

**Edit:** I have submitted a pull request to the Arduino GIT repository with a better method of monitoring the line state and imposing the `delay(10)` when it is actually needed rather than at every call to the `bool` operator regardless of need.

* https://github.com/arduino/Arduino/pull/3624

----

¹ *This is done to allow the port to complete opening at the PC end before data is allowed to be sent.  A better system would only perform the `delay()` at the moment of port opening rather than every call to the operator.*

² *Note that this would remove the delay which may be a bad thing as you may lose the first few bytes of the first debug message.  A better system is in the pull request mentioned in the edit to this answer.*


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

The real flaw is testing if Serial is available all the time. For one thing, that wouldn't work on a Uno etc. How about something like this?

    // make true to debug, false to not
    #define DEBUG true

    // conditional debugging
    #if DEBUG

      #define beginDebug()  do { Serial.begin (115200); while (!Serial) { } } while (0)
      #define Trace(x)      Serial.print   (x)
      #define Trace2(x,y)   Serial.print   (x,y)
      #define Traceln(x)    Serial.println (x)
      #define Traceln2(x,y) Serial.println (x,y)
      #define TraceFunc()   do { Serial.print (F("In function: ")); Serial.println (__PRETTY_FUNCTION__); } while (0)

    #else
      #define beginDebug()  ((void) 0)
      #define Trace(x)      ((void) 0)
      #define Trace2(x,y)   ((void) 0)
      #define Traceln(x)    ((void) 0)
      #define Traceln2(x,y) ((void) 0)
      #define TraceFunc()   ((void) 0)
    #endif // DEBUG

    long counter;
    unsigned long start;

    void setup() {
      start = micros ();

      beginDebug ();
      Traceln (F("Commenced debugging!"));
      TraceFunc ();  // show current function name

    }  // end of setup

    void foo ()
      {
      TraceFunc (); // show current function name
      }

    void loop()
    {

      counter++;
      if (counter == 100000)
      {
        Traceln (F("100000 reached."));
        Trace (F("took "));
        Traceln (micros () - start);
        counter = 0;
        foo ();
      }  // end of if

    }  // end of loop

That only does the Serial.begin() once, and the test for waiting for Serial to become available once.

Then, depending on the DEBUG define, the debugging code is executed or not. The fancy `((void) 0)` calls get optimized away completely by the compiler if DEBUG is false, thus making them have no effect if debugging is off (which wouldn't apply to your code).

---

*(Edited to add)*

> As you can deduce from my macros I wanted to debug IF the serial port is connected. I don't want to wait for it to be connected.

Well it wasn't *immediately* obvious from your code. In that case I suggest you test in the main `loop` function every second or so, to see if `Serial` is true. If so, set a flag. Test that flag in your debug function. That way you aren't slowing down every single `Serial.print` by 10 ms.

Like this amended code:

    // make true to debug, false to not
    #define DEBUG true

    // conditional debugging
    #if DEBUG

      #define beginDebug()  do { Serial.begin (115200); } while (0)
      #define Trace(x)      do { if (serialConnected) Serial.print   (x); }     while (0)
      #define Trace2(x,y)   do { if (serialConnected) Serial.print   (x, y); }  while (0)
      #define Traceln(x)    do { if (serialConnected) Serial.println (x); }     while (0)
      #define Traceln2(x,y) do { if (serialConnected) Serial.println (x, y); }  while (0)
      #define TraceFunc()   do { if (serialConnected) { Serial.print (F("In function: ")); Serial.println (__PRETTY_FUNCTION__);} } while (0)

    #else
      #define beginDebug()  ((void) 0)
      #define Trace(x)      ((void) 0)
      #define Trace2(x,y)   ((void) 0)
      #define Traceln(x)    ((void) 0)
      #define Traceln2(x,y) ((void) 0)
      #define TraceFunc()   ((void) 0)
    #endif // DEBUG

    const byte LED = 13;

    bool serialConnected;
    unsigned long timeSerialLastTested;

    long counter;
    unsigned long start;

    void setup() {
      start = micros ();

      beginDebug ();
      Traceln (F("Commenced debugging!"));
      TraceFunc ();  // show current function name

      pinMode (LED, OUTPUT);
    }  // end of setup

    void foo ()
      {
      TraceFunc (); // show current function name
      }

    void loop()
    {

      // every second, see if the Serial port is available
      if (millis () - timeSerialLastTested >= 1000)
        {
        timeSerialLastTested = millis ();
        serialConnected = Serial;
        digitalWrite (LED, !digitalRead (LED));  // blink LED
        }

      counter++;
      if (counter == 100000)
      {
        Traceln (F("100000 reached."));
        Trace (F("took "));
        Traceln (micros () - start);
        counter = 0;
        foo ();
      }  // end of if

    }  // end of loop


message:
Send numbers to arduino via serial port using python

I have a file with numbers called `fginputs.txt`. For example it could be something like this:

    4958
    4154
    4154
    4154
    4154
    4154
    4154
    4154
    4154
    4154
    4154
    4154
    4154
    4154
    4154
    4154
    4154
    4958

I want python to send each number to arduino via serial port. After each number is received, arduino should print back an acknowledgment number, indicating that it got a valid number, and then store that number in a dynamic array, because I could create larger files. When there are no more numbers left, send a '-1' to finish transmission.

Here's my arduino code:

```c++
// save some unsigned ints
uint16_t SIZE, *inputList, cont = 0;
boolean inputsReady = false;

void setup()
{
 // initialize serial communication at 9600 bits per second:
 Serial.begin(9600);

 //free dynamic array memory
 free(inputList);
 //counter for how many numbers I've received starts at 0
 cont = 0;
 //This is true when there are no more numbers to receive, meanwhile false
 inputsReady = false;
 setupInputList();
 }

/* If there's not enough space, resize the array by one unit and store the number
   */
void growAndInsert(int currentSize, int newInt){
    if(currentSize > SIZE)
        inputList = (uint16_t *)realloc(inputList, (currentSize + 1)*sizeof(uint16_t));
    inputList[currentSize] = newInt;
}
/**
  init inputList with 100 blocks
 */
void setupInputList(){
  SIZE = 10;
  inputList = (uint16_t *)malloc(sizeof(uint16_t) * SIZE);
}

void clearBuffer(){
while(Serial.available() > 0)
    Serial.read();
}

/**
Listens in serial port for an integer that represents a new input and returns it.
If it doesn't get anything useful from serial, return 0
*/
  int getNewInputFromSerial(){
   if (Serial.available() > 0) {
    delay(100);
    // look for the next word
    int cmd = Serial.parseInt();
    clearBuffer();

    if(cmd == 4958)
        Serial.write("4");
    else if(cmd == 4154)
        Serial.write("5");
    else
        Serial.write("0");
    return cmd;
   }
  return 0;

}

void loop()
{
     if(!inputsReady){
        int newInput = getNewInputFromSerial();
        if(newInput == 0)
            return;
        if(newInput != -1)
            growAndInsert(cont++, newInput);
        else{
            inputsReady = true;
            //initTimer();
        }
    }

}
```

and the python script:

```python
global arduino
PORT = '/dev/ttyACM0'
FILENAME = "fginputs.txt"
#Read file with inputs
with open(FILENAME) as f:
        content = f.readlines()
#init serial port
arduino = serial.Serial(PORT, 9600, timeout=1);
time.sleep(2);

#write
for input in content:
    arduino.flush()
    arduino.write(input)
    time.sleep(.1);
    resp = arduino.read();
    print "i got " + resp

#Finish transmission with -1
arduino.flush()
arduino.write("-1")
#done
arduino.close();
```

The fist time I execute the script I get this:

    i got 4
    i got 5
    i got 5
    i got 5
    i got 5
    i got 5
    i got 5
    i got 5
    i got 5
    i got 5
    i got 5
    i got 5
    i got 5
    i got 5
    i got 5
    i got 5
    i got 5
    i got 4

Which is great. But if I run it a second time I get this:

    i got 0
    i got 4
    i got 0
    i got 0
    i got 0
    i got 0
    i got 0
    i got 0
    i got 0
    i got 0
    i got 0
    i got 0
    i got 0
    i got 0
    i got 0
    i got 0
    i got 0
    i got 0

Which is terribly wrong because the file hasn't changed. I don't know what is going on here. If I unplug and plug back in the USB cable, transmission works flawlessly again.

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

    // save some unsigned ints
    uint16_t SIZE, *inputList, cont = 0;
    boolean inputsReady = false;

    void setup()
    {
     // initialize serial communication at 9600 bits per second:
     Serial.begin(9600);

     //free dynamic array memory
     free(inputList);

You are freeing a NULL pointer which is <s>an undefined operation</s> not necessary here, since it was never allocated.

---

      if (Serial.available() > 0) {
        delay(100);
        // look for the next word
        int cmd = Serial.parseInt();
        clearBuffer();

This is going to just throw data away, I'm not surprised stuff goes missing.

Read this: [How to process incoming serial data without blocking](http://www.gammon.com.au/serial) - you need to get rid of the `delay`, and the `clearBuffer()` for a start.

---

Example code for reading from Serial without blocking and without using `delay`:

    // how much serial data we expect before a newline
    const unsigned int MAX_INPUT = 50;

    void setup ()
      {
      Serial.begin (115200);
      } // end of setup

    // here to process incoming serial data after a terminator received
    void process_data (const char * data)
      {
      // for now just display it
      // (but you could compare it to some value, convert to an integer, etc.)
      Serial.println (data);
      }  // end of process_data

    void processIncomingByte (const byte inByte)
      {
      static char input_line [MAX_INPUT];
      static unsigned int input_pos = 0;

      switch (inByte)
        {

        case '\n':   // end of text
          input_line [input_pos] = 0;  // terminating null byte

          // terminator reached! process input_line here ...
          process_data (input_line);

          // reset buffer for next time
          input_pos = 0;
          break;

        case '\r':   // discard carriage return
          break;

        default:
          // keep adding if not full ... allow for terminating null byte
          if (input_pos < (MAX_INPUT - 1))
            input_line [input_pos++] = inByte;
          break;

        }  // end of switch

      } // end of processIncomingByte

    void loop()
      {
      // if serial data available, process it
      while (Serial.available () > 0)
        processIncomingByte (Serial.read ());

      // do other stuff here like testing digital input (button presses) ...

      }  // end of loop

In `process_data` in my example is where you would call `atoi` to convert the incoming string into an int (or `atol` if it is going to be longer).


body:
You could have a look at [this][1].

It's a python program which does record/playback of key-presses, through an UNO.

It already implements:

 - serial communication with error checking
 - ACK: each message has its own ID, so you can keep track of what was lost, should anything bad happen
 - synchronization, in case your Arduino is powered up after the python program is started

  [1]: https://github.com/01org-AutomatedFlasherTester/pem


message:
What happens if I don't open the USB serial port of Arduino Pro Micro / Leonardo?

My question is related to [this one][1]. My sketch seems to stop responding after some time if I run it with debug enabled and I don't open the serial port/monitor on the computer.

Does the UART buffer fill up and block or something? Or, does it discard the excess data and keep working?

I can't find information about it.

  [1]: https://arduino.stackexchange.com/questions/13890/is-there-any-problem-about-calling-if-serial-many-times

body:
As far as I can see from CDC.cpp it attempts to see if the USB is available and if not, do not write anything but set the "write error" flag.

    size_t Serial_::write(const uint8_t *buffer, size_t size)
    {
     /* only try to send bytes if the high-level CDC connection itself
      is open (not just the pipe) - the OS should set lineState when the port
      is opened and clear lineState when the port is closed.
      bytes sent before the user opens the connection or after
      the connection is closed are lost - just like with a UART. */

     // TODO - ZE - check behavior on different OSes and test what happens if an
     // open connection isn't broken cleanly (cable is yanked out, host dies
     // or locks up, or host virtual serial port hangs)
     if (_usbLineInfo.lineState > 0) {
      int r = USB_Send(CDC_TX,buffer,size);
      if (r > 0) {
       return r;
      } else {
       setWriteError();
       return 0;
      }
     }
     setWriteError();
     return 0;
    }

This is the same test as is done in `operator bool()` without the 10 ms delay.

    // This operator is a convenient way for a sketch to check whether the
    // port has actually been configured and opened by the host (as opposed
    // to just being connected to the host).  It can be used, for example, in
    // setup() before printing to ensure that an application on the host is
    // actually ready to receive and display the data.
    // We add a short delay before returning to fix a bug observed by Federico
    // where the port is configured (lineState != 0) but not quite opened.
    Serial_::operator bool() {
     bool result = false;
     if (_usbLineInfo.lineState > 0)
      result = true;
     delay(10);
     return result;
    }

Judging by the comments above, this may not be the most reliable thing in the world.


message:
Power saving of atmega 2560

Is arduino code Consume More power other than "Avr Studio" Code?

Please tell some key points for power saving.
Processor on $ off Methodology.

body:
There is nothing about the Arduino code that would inherently consume more power than using a different compiler, so no, it doesn't. What the code does you can change in either development environment.

Read [Power saving techniques for microprocessors](http://www.gammon.com.au/power) for a considerable number of tips about saving power.

Also see related threads about this question such as https://arduino.stackexchange.com/questions/6/what-are-or-how-do-i-use-the-power-saving-options-of-the-arduino-to-extend-bat


message:
What requirements should components have to work with Arduino (UNO in particular)

I am fairly new to the whole concept of Arduino and electronic engineering in general.

Recently I bought myself an Arduino UNO and I'm wondering what "non off the shelf" components will work when I hook them up with the UNO. I have a lot  of old electronic stuff laying around containing pushbuttons, sliders, faders, knobs etc. wich if possible, I'd like to take apart to connect them to the UNO for some fun fuzzin' around.

Many thanks in advance!

PS: this is my fist post ever on stackexchange so excuse me if the question is placed incorrectly or the tags are weird. Please DO correct me where I'm wrong.

body:
When it comes to electronics, hypothetically anything can be connected to anything else. The only real barriers are time, cost, and practicality.

Two major things to look out for though are voltage and current requirements.

Most Arduinos operate at 5 volts, so it's often easiest to connect it to other electronic devices which also operate at 5 volts. That certainly doesn't mean you *can't* connect an Arduino to something that operates at 3.3 volts (for example). However, it means you may need to add some voltage level conversion circuitry (although it's not always necessary, depending on the context).

Regarding current, a critical issue to look out for is how much current something will draw. For example, a motor will often require more current than an Arduino can safely provide. That means you'd need some kind of external power supply which can be switched by the Arduino.

The most valuable thing to do is to learn to find and read datasheets. These give information about electronic components, specifying things like voltage, current, timing and so on. For situations where there's no datasheet available, you may find it useful to learn how to use a multimeter and an oscilloscope to monitor how equipment behaves.


message:
Arduino Ethernet Shield Response Process, Time, and Synchronization

I have a ethenet shield. I want to update my server page. Server page have to show current time. The code is given in this [link][1]. Code works but there is two problem

1- When i press the stop button in the browser, Arduino stops. After this i press refresh button and there is no response.

2- How can i synchronize the arduino time. From where? without setup another server. Is there any time stamp server that compatible with arduino?

  [1]: https://drive.google.com/folderview?id=0BzuMgxouJ695flY2M0JQWFJrd0F5NGthMXhSTUFkQ2xPV3RpdzJ6X2dRc05mdENYOXJnMWc&usp=sharing

body:
I don't have an answer for question 1.

For question 2:

You can add a function to implement an NTP (network time protocol) client.  For example, see the [UdpNtpClient](https://www.arduino.cc/en/Tutorial/UdpNtpClient) article on arduino.cc.  In your `setup()` or `loop()` code call the function initially or perhaps hourly or daily to set system time via an NTP time server.  The server's IP address can be hardcoded or otherwise as you like.

For lists of public time servers, see [www.ntp.org](http://www.ntp.org/) and [pool.ntp.org](http://www.pool.ntp.org/en/).

Alternately, you could add a [DS1302](http://playground.arduino.cc/Main/DS1302) or similar clock chip board to your hardware.


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

### Question 1.

Your code looks odd:

    void checkForClient(){

      EthernetClient client = server.available();

      if (client) {
        boolean sentHeader = false;
        while (client.connected()) {
          if (client.available()) {
            if(!sentHeader){
              // send a standard http response header
              client.println("HTTP/1.1 200 OK");
              client.println("Content-Type: text/html");
              client.println();
              sentHeader = true;
            }
            durumBildir(client,50,ID);
          }
        }
      }
      delay(1); // give the web browser time to receive the data

    }

    void durumBildir(EthernetClient client, int deger,String ID){
      client.print(ID);
      client.print("-");
      client.print(deger);
      client.print("-");
      if (timeStatus()!= timeNotSet) {
        digitalClockDisplay( client);
      }

      client.print("<br>");
    }

You never **read** from client, so it will **always** be available (and thus you never leave your loop). I just tested it. Why are you sending the time out indefinitely? Even when you disconnect the poor Arduino is still sending the date and time out forever. No wonder you can't connect again.


message:
Can I supply the board's 3.3V directly to the AREF pin?

Short dumb question: can I connect the 3.3V pin and the analog reference pin (AREF) directly?

I've heard mentions of a 32K internal resistor but I'm not willing to risk a short circuit without confirmation. Should I add an external resistor? Won't that create a voltage divider?

body:
In Atmel's doc8271 pdf (with specification details for ATmega48A; ATmega48PA; ATmega88A; ATmega88PA; ATmega168A; ATmega168PA; ATmega328; and ATmega328P), table 29-20 on page 117 shows R_REF (the AREF input resistance) as 32KΩ (typical).  Section 24.5.2 on page 248 suggests that AREF is to be treated as a high-impedance input or output:
>... the reference voltage can be made more immune to noise by connecting a capacitor between the
AREF pin and ground. VREF can also be measured at the AREF pin with a high impedance voltmeter. Note that
VREF is a high impedance source, and only a capacitive load should be connected in a system.

Also note that there is no reason to connect anything to AREF (pin 21), because on a standard Uno, AVCC (pin 20) is connected to VCC (pin 7), and one can select AVCC as the reference voltage during analog converter setup [as explained below].  Quoting again from section 24.5.2:
>VREF can be selected as either AVCC, internal 1.1V reference, or external AREF pin.  AVCC is connected to the ADC through a passive switch. The internal 1.1V reference is generated from the internal bandgap reference (VBG) through an internal amplifier. In either case, the external AREF pin is directly connected to the ADC...

Summary: you can connect the 3.3V pin and the analog reference pin (AREF) directly, but on a 3.3V system  there is no reason to do so.

*Selecting AVCC as the reference voltage:*  Say [analogReference(DEFAULT)](https://www.arduino.cc/en/Reference/AnalogReference) to select AVCC as the reference voltage.  According to arduino.cc, this will choose “the default analog reference of 5 volts (on 5V Arduino boards) or 3.3 volts (on 3.3V Arduino boards)”.


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

I don't see any big objection to connecting the 3.3 V pin to AREF, providing you take precautions in your code.

The default for AREF is so-called DEFAULT (heh) as here:

    uint8_t analog_reference = DEFAULT;

Once you do an `analogRead` the analogRead code connects up the desired analog reference:

    ADMUX = (analog_reference << 6) | (pin & 0x07);

Then it starts the ADC conversion.

If you **change** the analog reference voltage then this needs to be done **before** doing the analogRead. eg.

      analogReference (EXTERNAL);
      analogRead (A0);  // use external reference

The reason they do it this way is so that it is safe to physically connect up the 3.3V pin to the AREF pin, because the initial state of the processor is to **read** the AREF pin.

Once you do your first analogRead, and with the DEFAULT reference voltage used, you will find 5V at the AREF pin. If you had then connected that to something else like the 3.3V pin, it will short out and damage the board.

Example code:

    void setup ()
      {
      pinMode (13, OUTPUT);
      delay (5000);
      digitalWrite (13, HIGH);
      int foo = analogRead (0);
      }  // end of setup

    void loop ()
      {
      }  // end of loop

Put your meter on AREF and you will see it jump to 5V after 5 seconds.


message:
What is the Vin Pin for?

I always asumed it was a different option to power the board, but it seems to act more like a 5V supply. What then is the difference between this pin and the 5V pin?

body:
The Vin pin serves the same purpose as the barrel jack.  The only difference is (usually) that it doesn't go through the schottky protection diode that causes a small voltage drop.

Normally its voltage is at around 0.3-0.4V below whatever you feed into the barrel jack.

If you power from USB then the USB voltage (~5V) is "back-fed" through the 5V regulator to appear on the Vin pin.  It's not safe to use that power for anything since you could damage the 5V regulator if you do.

The pin is designed to either be used to power external higher voltage devices with power (almost) direct from the barrel jack (motors, etc), or to feed power in from an external source without using the barrel jack (great for a shield that can provide its own power source).


body:
To answer this added question:

> At the moment I am using it as a sort of 5V "virtual ground". Is this an okay use without damaging it? I have a camera which triggers when two wires coming from it are connected, so it triggers on a short

I certainly would **not** be using it as a 5V "virtual ground" - whatever that means. The Vin pin could easily be up around the 10V mark, depending on what you plug into the barrel jack.

I had a [project](http://www.gammon.com.au/forum/?id=11671) a while ago where I wanted to trigger a camera flash. In the same way as you describe, two pins had to be shorted.

I wasn't sure what voltages would be on them, or if there would be a spike, so I used an opto-coupler like this:

[![Flash shoe activation][1]][1]

You need to identify by measuring with a meter which pin has the positive voltage on it. That would go to the collector of the transistor in the opto-coupler (pin 5 in this particular case).

---

*(edited to add)*

>  I'm just not sure about connecting 5V directly to ground though. Do you think this will be safe?

We can probably assume that the current will be low, after all they wouldn't short out the camera's battery through that pin. Put your meter in **current** mode across the camera's pin and measure the current when the pin is shorted (ie. the meter will short it).

If it is 20 mA or less then the Arduino digital pin can handle that. I imagine it will be a steady flow of current. I just measured my flash shoe with that method, and it seems to use a tiny fraction of current (0.1 mA).

So that should be safe, safer than your method with Vin anyway.

> Then, when I want to trigger it I need to change the digital in pin to a digital out pin and enable the internal pull down resistor on this pin, effectively connecting this pin to ground, and shorting the two wires.

Sounds complex. Just make the pin LOW, and make it output to fire it. eg.

In setup:

    digitalWrite (cameraPin, LOW);  // default will be INPUT mode

To activate camera:

    pinMode (cameraPin, OUTPUT);  // drive low
    delay (500);  // or whatever
    pinMode (cameraPin, INPUT);   // make high impedance

Make sure you measure the pin and get the correct polarity. You want the positive side to go to the Arduino pin, and the negative side to Ground.

And make sure it isn't higher than 5V. (Use **voltage** mode on the meter to check that).

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


body: I like the way someone explained Vin to me. "Whatever power source you connect to the DC Jack is supplied there, be it 12v or lesser"


message:
What's Wrong with this DHT22?

I made a circuit that takes humidity and temperature from DHT22 sensor and displays it on Lcd Screen. Simple enough but i get this error "Failed to read from DHT". That happens because i have this code

     if (isnan(t) || isnan(h)) {
      delay(100);
        Serial.println("Failed to read from DHT");
      } else {
        delay(100);
        Serial.print("Humidity: ");
        Serial.print(h);
        Serial.print(" %\t");
        Serial.print("Temperature: ");
        Serial.print(t);
        Serial.println(" *C");
        //lcd.print("Temp: ") ;
        //lcd.print(t);
        //lcd.setCursor(0, 1);
        //lcd.print("Hum: ") ;
        //lcd.print(h);
      }

So the values are **NaN** . But 1 minute before it worked fine, and now again it doesnt. Everything is soldered the right way and nothing is false. Lcd is wired ok and it works but i dont get values from DHT22.

Here are some pics to help you out.
![Overview](https://i.stack.imgur.com/ZG3Hi.jpg)
![Wiring](https://i.stack.imgur.com/yEfbl.jpg)
![Wiring](https://i.stack.imgur.com/KvYZu.jpg)

In the third Image we see its working. And now its not!
is the DHT sensor broken?

      #include "DHT.h"
    #include <LiquidCrystal.h>`

    #define DHTPIN 2
    #define DHTTYPE DHT22   // DHT 22  (AM2302)

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    DHT dht(DHTPIN, DHTTYPE);

    void setup() {
      Serial.begin(9600);
      Serial.println("DHT22 test!");
      lcd.begin(16, 2)
      dht.begin();
    }

    void loop() {

      float h = dht.readHumidity();
      float t = dht.readTemperature();

      if (isnan(t) || isnan(h)) {
        Serial.println("Failed to read from DHT");
      } else {

        lcd.print("Hum: ");
        lcd.print(h);
        lcd.setCursor(0, 1);

        lcd.print("Temp: ");
        lcd.print(t);

      }
    }

Thats my code by the way

body:
Two things:

 1. You need to put a delay in between your read requests. Currently you're reading way too fast, every few milliseconds you're hitting the DHT. Max interval should be every two seconds or so.
 2. Add a 10k resistor between pin 1 and 2 of the DHT.

I'd bet adding a delay, or using the simpleTimer library to control how frequently you read from the DHT will clear this up.


message:
MCP23017: 16x2 LCD showing black boxes

I've researched a lot but I couldn't find a solution to my problem, which is that after properly following all steps from this Website: http://www.danielealberti.it/2014/02/collegamento-diplay-lcd-ad-arduino-via.html

and after using the Library LIQUIDTWI2:

(https://drive.google.com/file/d/0BwSP1-P3E2UJY1loYWtWQVRWNlU/edit?usp=sharing)

for I2C connections, the LCD keeps displaying black boxes on the top row.

I'm pretty sure that I have wired (as shown in the tutorial linked above) and programmed everything correctly but I'm still getting the black boxes. Is the problem related with the MCP23017 pin expander or with something else?

I'm using an Arduino UNO

body:
Quite often such situation occurs when the display does not reset properly (the reset from the IDE does not necessarily reset the display!).

So, once the sktech has been uploaded to the board, I would first try to do a reset on the Uno board (using the RESET button). If that doesn't do the trick, I would recommend to make the contrast adjustable (all my LDC displays showed "black boxes in the upper row" on delivery and I had to ajust the contrast).

If that also has not the desired effect, there is no alternative to debugging your code. Without the code itself, we cannot guess what might be wrong.


message:
Simple Arduino - 74hc595 shift register construction [tmli5]

I'm quite new to Arduino world and I'm trying to understand how shift registers work.
I built this construction :
[![enter image description here][1]][1]

In fact, it is an Arduino Duemilanove with AtMega on it, but afaik it doesn't matter.

The tutorial I try to follow use SPI library so I try to do it too. I kind of understood that data input, latch and clock had to be pins 7, 4 and 11.

Basically, all I try to do is sending a byte to light the LEDs. As for me now, the sequence should light all LED, then no one, then one after another.
I know there is one more input ont the right side of the SR but I didn't plan this model so I ran out of LEDs...

This is the code I use :

    #include <SPI.h>
    #include <StandardCplusplus.h>
    #include <vector>
    #include <iterator>
    #include <size_type>

    using namespace std;

    //pin du shift register
    #define DATA_PIN 13
    #define LATCH_PIN 4
    #define CLOCK_PIN 11
    //à utiliser plus tard
    #define INPUT_PIN 2

    void setup() {
      pinMode(DATA_PIN, OUTPUT);
      pinMode(LATCH_PIN, OUTPUT);
      pinMode(CLOCK_PIN, OUTPUT);
      //pinMode(INPUT_PIN, INPUT);

      SPI.setBitOrder(MSBFIRST);
      SPI.setDataMode(SPI_MODE0);
      SPI.setClockDivider(SPI_CLOCK_DIV2);
      SPI.begin();

      //SPI.transfer(getBit(3));
      //digitalWrite(LATCH_PIN, HIGH);
      //digitalWrite(LATCH_PIN, LOW);

      Serial.begin(9600);
      Serial.println("start !");
    }

    void loop() {
      shift(B11111111);
      shift(B00000000);
      shift(B10000000);
      shift(B01000000);
      shift(B00100000);
      shift(B00010000);
      shift(B00001000);
      shift(B00000100);
      shift(B00000010);
      shift(B00000001);
    }

    void shift(int n){
      SPI.transfer(n);
      digitalWrite(LATCH_PIN, HIGH);
      digitalWrite(LATCH_PIN, LOW);
      Serial.print("shift : ");
      Serial.println(n);
      delay(1000);
    }

When I upload this code, LEDs sequence has no sense, but serial output was totally OK.

What I see (without the output 0 of course) is :
1111111, 0111111, 1011111, 1110111, 1111101 and then 1111111 without further changes, whereas serial output is 255, 0, 128, 64, 32, 16, 8, 4, 2, 1, 255, 0, 128 and so on.

I assume I didn't understand something important, and it prevent me from finding answers in google.

Thanks for helping, it's really disturbing for me.

EDITS :

changed the title, it is a 74HC595.

Strangest behavior too (not gonna create another topic for that now), I dont have to connect both the gnd and VCC from my arduino for this to light LEDs. It changes a little the brighness of LEDs, but surprisingly VCC< GND< both

This is the tutorial I use to understand shift registers : [https://youtu.be/6fVbJbNPrEU?t=195][2], and the one that uses SPI is nXl4fb_LbcI

I am now aware that I should get one resistor for each LED but I don't have that much resistors and as far as I can see this don't harm my LEDs nor underpower them.

  [1]: https://i.stack.imgur.com/dmFiN.jpg
  [2]: https://youtu.be/6fVbJbNPrEU?t=195

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

You have a number of problems here. The first is the wiring.

[![595 wiring diagram][1]][1]

My wiring diagram above is for the Uno / Duemilanove. Since that is what you have, you should follow that.

The pins are fixed in hardware, except for the slave select pin. Thus D13 on the Duemilanove should go to pin 11 on the 595. D11 on the Duemilanove should go to pin 14 on the 595. And your slave select (which may as well be pin 10 on the Duemilanove) should go to pin 12 on the 595.

---

Your code looks more complex than it needs to be. This code will exercise the 8 LEDs:

    #include <SPI.h>

    const byte LATCH = 10;

    void setup ()
    {
      SPI.begin ();
    }  // end of setup

    byte c;
    void loop ()
    {
      c++;
      digitalWrite (LATCH, LOW);
      SPI.transfer (c);
      digitalWrite (LATCH, HIGH);
      delay (20);
    }  // end of loop

---

As other responders have said, you should have a current-limiting resistor for **each** LED. You can't share it like that.

Also the 595 ground (pin 8) should be wired to the Duemilanove ground, not via a resistor.

---

## Reference

[Using a 74HC595 output shift register as a port-expander](http://www.gammon.com.au/forum/?id=11518)

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


message:
Motor shield power from Arduino pro mini 5v RAW Pin 150mAh cannot run servo

linked to my old question, [Pro Mini 5v with Adafruit motor shield v1 power sharing problems][1]

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

I figured out and use one 7.2v battery (6 AA cells), and link it with RAW pin to Pro mini and join its 5v pin to motor shield 5v. It works but as I have a servo on this shield, 2 distance sensors so servo does not work well all the times. Stops or does not move as directed, shaking etc. I figured out that pro mini output 5v but only 150mAh which is not sufficient to run a servo which while sharing same 5v for motor shield. I need to know if I want to supply 5v 2000mAh from AA cells or 5v regulator, should I use these pins on motor shield (5v, Gnd, 9v)? I tried but it did not work. I did not find it anywhere on net.

1. How can I use these pins shown in the picture.
2. What is the min/max mAh value of current I can provide at these pins?
3. If supplying input current at these pins, should I connect/disconnect power jumper?

 I am totally stuck. Need help. And here is the quick diagram how things are attached. All other pins are attached at shield connects to UNO when stack on it.

[![My robotic car diagram.][3]][3]

  [1]: https://arduino.stackexchange.com/questions/12775/pro-mini-5v-with-adafruit-motor-shield-v1-power-sharing-problems
  [2]: https://i.stack.imgur.com/srD93.jpg
  [3]: https://i.stack.imgur.com/V00dc.jpg

body: You can't, or at least you can't do it the way you want to. Each pin can give you a maximum of 40mA. You may try using more than one pin but that possibly wont work for you. I suggest you supply additional power from a separate source and control On/Off from Arduino. It would be like a relay. Or simply buy a relay to do this.


message:
Using arduino Due for camera control

Could the arduino Due take and send image data from 5MP camera module to PC in the following condition?

- frame rate = 1fps
- resolution = 2592 x 1944
- format = 10 bit bayer raw RGB
- interface : parallel ports (DVP) between camera and Due
               spi between Due and PC(or SD card)
- FIFO(frame buffer): would not be used
- SDRAM: would not be used
(But if it is needed, I would SDRAM via spi. Also I can use a frame buffer like AL422B. But if it is possible I would avoid using them.)

The camera would send 50Mbit image data per second and they will be transferred via 8 parallel lines(D0~D7) to the Due. And then they would go to PC directly or after passing SDRAM. But how can one evaluate if the 84Mhz is enough to do this job by calculation?

Arduino Due specs
https://www.arduino.cc/en/Main/arduinoBoardDue

camera module example (OV5642)
http://www.uctronics.com/cmos-camera-adapter-board-for-omnivision-image-sensor-p-248l.html
But this is not what I want to use. In my project I need to build a camera module and it would not include FIFO unless it's highly recommended.

body:
So a quick feasability assessment:

2592 W * 1944 H * 10 bit = 50388480 bits

50388480 bits / 8 bit data bus = 6298560 packets

84000000 clocks per second / 6298560 packets = ~13 clock cycles per packet

I think that by itself, from a purely data perspective, without looking too deep into datasheets, you could feasibly read data from a port and push it out the USB port, and clock the data in less than 13 cycles. But what this means is you'd have to get into the nitty gritty of the processor and figure out how to do that as low level as possible because `DigitalRead()` and `Serial.print()` aren't going to cut it as they won't be fast enough.

The real challenge is that the above totally depends on being able to clock the data from the sensor yourself, which if I recall correctly, these sensors can actually be pretty picky about their clock.

I would highly recommend a FIFO, that way the sensor data can be clocked to it as fast as it wants to be clocked, and then you could read from the FIFO at your own pace as it will clock data out at exactly the rate you want it. Also 1 FPS is a pretty lofty goal if you are only a beginner. Like I said, it is probably possible, but it requires a lot of optimizations and planning that are not very straightforward to implement, especially if you are just starting out.


message:
Pass Several Values to Library

Unfortunately I have yet to learn C++ though I have experience with C# and other non-C languages. After trying for the past 5 hours to pick up what I can from Stack and other sites I haven't found a workable solution that actually works with Arduino IDE (hence why I'm posting here and not stackoverflow).

Im trying to create a simple library to handle some analog inputs. I need to be able to compare the value from a pin to a list of values and handle the result accordingly. I can easily send the number of the pin to the constructor and read it. My issue is actually defining that list from the `setup()` function.

The list can be variable in length so I can't hard code an array in the library class and then pass values one by one. I can pass the length in the constructor but then I'm not really sure how to use it to initialize the array length without having the values to assign.

In C# or other languages I'd either use a list or pass the array directly. Neither of these seem to be an option with C++ (or at least I couldn't pass the array correctly). How could I solve this problem? If it helps I'm using a teensy++ 2.0.

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

If the list is a static list you could conceivably pass a pointer to it in the constructor. Example:

    class myClass {
      const int num_;
      const int * values_;

      public:

      // constructor
      myClass (const int num, const int * values) : num_ (num), values_ (values) { }

      // other stuff here

      // demo
      void printThem ();
    };  // end of class myClass

    void myClass::printThem ()
      {
      for (int i = 0; i < num_; i++)
        Serial.println (values_ [i]);
      } // end of myClass::printThem

    const int NUMBER_OF_VALUES = 6;
    const int myValues [NUMBER_OF_VALUES] = { 22, 33, 44, 55, 66, 77 };

    // make an instance of the class with the wanted values
    myClass foo (NUMBER_OF_VALUES, myValues);

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

      foo.printThem ();
      }  // end of setup

    void loop ()
      {

      }  // end of loop

That is the simple method. The values in the list are passed to the constructor as a pointer, the class remembers the list and uses it when necessary.


body:
Here are a few examples how to pass vectors and variable number of arguments to a function in C/C++:

    void foo(int* vector, size_t nmemb);

The function *foo* takes a *vector* of integers and the number of members, *nmemb*.

    const size_t VECTOR_MAX = 5;
    int vector[VECTOR_MAX] = { 0, 1, 3, 5, 7 };

    foo(vector, VECTOR_MAX);

The next variant is generalization. A vector of whatever, number of members, and size of each member;

    void fie(void* vector, size_t nmemb, size_t size);

This allows the function to handle different types of element.

    fie(vector, VECTOR_MAX, sizeof(int));

Examples of usage are the standard library functions [qsort()][1] and [bsearch()][2].

The next variant is variable arguments. C/C++ allows the syntax "..." for a list of arguments.

    void fum(size_t nmemb, ...);

This allows the following call:

    fum(5, 0, 1, 3, 5, 7);

The implementation of function must be able to "parse" the argument list.

    #include <stdarg.h>

    void fum(size_t nmemb, ...)
    {
      va_list ap;
      va_start(ap, nmemb);
      int arg;
      for (size_t i = 0; i < nmemb; i++) {
        va_arg(int, arg);
        ...
      }
      va_end(ap);
    }

There are four primary methods to determine the number of arguments and value types; 1) number of arguments as parameter and fixed data type, 2) special end parameter value, 3) indirect through format descriptor such as [printf()][3] format string, and 4) attribute-value pairs.

Below is an example of variable number of arguments as attribute-value pairs.

    void set_attrs(size nr, ...);

    set_attrs(5, X_POS, 10, Y_POS, 110, R_COLOR, 0, G_COLOR, 255, B_COLOR, 0);

A usage of this notation can be found in [Motif][4].

  [1]: http://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#gafd4bf2faec43342e7ad3d2ab37bac1fe
  [2]: http://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#ga885c1ccefb716ff16ab73a57003140be
  [3]: http://www.nongnu.org/avr-libc/user-manual/group__avr__stdio.html#ga4c04da4953607fa5fa4d3908fecde449
  [4]: http://www.opengroup.org/infosrv/openmotif/R2.1.30/motif/lib/Xm/VaSimple.c


body:
Arrays in C/C++ are handled as a pointer.  That means the value of the pointer is the location in memory of the first element in the array.  The next element is at that starting address, plus the size of each element.  So for an array of 1-byte characters, each item in the array is at the very next address.  For 32-bit members, it's at +4, and so forth.

You're storing an array of values to compare with analogRead() - so uint16_t (aka: short int) will be large enough for each element, without wasting too much memory.  But we also need to store a count of them, I'll assume 32-bits is enough readings.

    uint16_t *comparison_points;
    uint32_t  comparison_point_count;

These can be declared statically like:

    uint16_t  comparison_points[] = { 2, 4, 6, 8, 47 };
    uint32_t  comparison_point_count = 5;

Giving you a comparison function like:

    bool readingInSet(uint16_t reading, uint16_t *check_points, uint32_t check_points_length)
    {
        bool found = false;
        for (uint32_t i=0; i<check_points_length; i++)
        {
            if (reading == check_points[i])
            {
                found = true;
                break;
            }
        }
        return found;
    }

But you could also make the array into an object, embedding this functionality

    class AnalogueVector
    {
    public:
        AnalogueVector(uint32_t size, uint16_t *points)
        {
            comparison_point_count = size;
            comparison_points = points;
        }

        bool readingIn(uint16_t reading)
        {
            bool found = false;
            for (uint32_t i=0; i<comparison_point_count; i++)
            {
                if (reading == comparison_points[i])
                {
                    found = true;
                    break;
                }
            }
            return found;
        }

    private:
        uint16_t *comparison_points;
        uint32_t  comparison_point_count;
    };

Giving a usage like:

    uint16_t  comparison_points[] = { 2, 4, 6, 8, 47 };
    uint32_t  comparison_point_count = 5;

    AnalogueVector cmp_points(comparison_point_count, comparison_points);

    if (cmp_points.readingIn(analogRead(A1)))
        Serial.println("Matched");
    else
        Serial.println("no");

Obviously if you're reading these data points in from a file, or other external media, then you would need to allocate space for the items, and store them in the object.

As with most coding problems, there's multiple solutions.  Here I've tried to keep it simple, and explore different ways of handling array data, without getting to far away from that fact that an array in C/C++ is just a big contiguous block of data in memory somewhere.  The address of that data, (aka the *pointer*), is simply the address of that first element.


message:
Arduino Mega as a USB device

My need is to connect an Arduino board (any board that has around 3 UARTs support) to a host PC via USB and expose the 3 UART connections as 3 USB devices (say /dev/ttyUSB0, /dev/ttyUSB1, /dev/ttyUSB2) in the host PC. From my search, I found Arduino Mega 2560 supports upto 3 UARTs. My question is can we expose these UARTs into individual USB ports to the host system?

Thanks,
Alexander

body:
Not directly, no.  You have basically have 4 UARTs on the Mega2560 - one of them (USART0, pins 0&1) is connected to the USB interface chip, and the others are left unassigned for you to use as you like.  It's the USB interface chip that is being seen in your computer as /dev/ttyUSB0, not the UARTs in the Mega2560 chip.

That's not to say that what you are after is not possible - it is perfectly possible, but it will require some clever programming on your part.  You will need to:

1. Define a protocol that will multiplex 3 streams of serial data through the one USB serial connection
2. Write a sketch that works with that protocol to direct the incoming data to the right UART ports and multiplex the UART traffic into the protocol stream you have defined
3. Write software on your computer to perform a similar task - read in data and multiplex it, and read the multiplexed data stream and split it out to three separate destinations.

What the destinations on the PC end can be is a bit of a wooly area.  If you want to make it look like serial ports in /dev then you can use a *pty pair*, which is a master/slave pair of pseudo TTY devices that you can use to pass data through.  On most Linux systems they are numbered devices in /dev/pts, so /dev/pts/1 would be an example.

The function [`openpty(...)`](http://man7.org/linux/man-pages/man3/openpty.3.html) creates and opens a pty pair for you to use in your program.  You would do that 3 times to make three pairs and each one would be the endpoint to a sub-stream in your multiplexed data.

For instance, here is a bit of code I use to open a pty pair:

    struct termios options;
    openpty(&_masterfd, &_slavefd, _dev, NULL, NULL);
    fcntl(_masterfd, F_SETFL, 0);
    tcgetattr(_masterfd, &_savedOptions);
    tcgetattr(_masterfd, &options);
    cfmakeraw(&options);
    options.c_cflag |= (CLOCAL | CREAD);
    if (tcsetattr(_masterfd, TCSANOW, &options) != 0) {
        fprintf(stderr, "Can't set up PTY\n");
    }

That makes it appear to almost be a serial connection in style.  Of course you don't have the concept of a baud rate over a pty connection, so it will be down to your software to define how you control the baud rate (probably easiest to have it hard coded to the baud rates you need).

In that snippet you talk internally to the `_masterfd` with normal `read()` and `write()` functions as you would any other device or file.  Some other piece of software would open the other end of the pty pair (the `_slavefd`), the name of which is placed in `_dev` when the pty pair are opened.  You could use that `_dev` name to then create a symbolic link to a better named device instead of using the `/dev/pts/x` name that could change without warning from one run to the next.


message:
2,5m cable too long for LCD connected to Arduino UNO?

So i got that 2,5m cable wired with the LCD and the arduino, but i keep getting those weird characters showing up on the LCD. Clearly there is a signal loss between the components but there has to be a solution to the problem. Perhaps by connecting capacitors/resistors to the wires will help? Is there any solution other than not using this long cable?

body: If the interface you're using is I2C(only two cables from arduino to lcd, vice versa)you have a problem,you need to pull up the sda-scl channel with appropriate resistors, you could (maybe) boost the I2C signal using ti-p82b715 bus extender, I just assume you use I2C (2,5m length?), what interface do you use? SPI? I2C?


body:
I'm presuming this is I2C or SPI, because a Serial cable of 2.5 m should still work.

You can slow both I2C and SPI down.

---

In the case of [SPI](http://www.gammon.com.au/spi) you can call something like this:

    SPI.setClockDivider(divider);

Where "divider" is one of:

* SPI_CLOCK_DIV2
* SPI_CLOCK_DIV4
* SPI_CLOCK_DIV8
* SPI_CLOCK_DIV16
* SPI_CLOCK_DIV32
* SPI_CLOCK_DIV64
* SPI_CLOCK_DIV128

The default is SPI_CLOCK_DIV4, so try a larger divider.

---

In the case of [I2C](http://www.gammon.com.au/i2c) you can change the clock speed and the prescaler. The default frequency is 100 kHz, but you could make it slower.

    TWBR   prescaler   Frequency

      12       1       400   kHz  (the maximum supported frequency)
      32       1       200   kHz
      72       1       100   kHz  (the default)
     152       1        50   kHz
      78       4        25   kHz
     158       4        12.5 kHz

For example, to run at half the frequency (50 kHz) use:

      Wire.begin ();
      TWBR = 152;

To run at 25 kHz you also need to change the prescaler, eg.

      Wire.begin ();
      TWBR = 78;
      TWSR |= bit (TWPS0);

In the case of I2C make sure you have pull-up resistors on SDA and SCL in order to get a clean signal. 4.7 k is a reasonable value to try (for both of them) with the other ends connected to +5 V.


message:
Model Rocket Sensors

My idea is to record the acceleration/altitude of a small model rocket launch using these sensors and record all the data onto a microSD card which I'll retrieve afterwards. I'd like to be able to plot all of the data to analyze the performance of the rocket. This data will also help compare the experimental results to the theoretical ones.

[Accelerometer][2]

[OpenLog/SD Card][3]

(Was only allowed two links so couldn't include barometer)

  [2]: http://www.amazon.com/gp/product/B008BOPN40/ref=ox_sc_act_title_3?ie=UTF8&psc=1&smid=A1564KB351MEZB
  [3]: http://www.amazon.com/gp/product/B00ADSNLMI/ref=ox_sc_act_title_2?ie=UTF8&psc=1&smid=A1LHQ5G6ONPXVT

I have a few questions to make sure that my logic is sound when trying to design this circuit;

1.) Since the OpenLog contains the ATmega328 microcontroller I was going to use the Arduino to write the instructions to this which will initialize the two sensors and start logging data. Is this the correct way to do this? From what I could tell the other sensors did not contain any EEPROM/Flash so there was no way to store any code on there.

2.) If I have multiple sensors running at the same time is this going to cause a data conflict when writing to the SD card? Would it be possible to save two different .txt files, one for each sensor?

Thanks

body:
The OpenLogger was designed to be paired with and Arduino Pro or Arduino Pro Mini and just log the serial output from one of those. You could theoretically use the OpenLogger itself to do the sensor reading and writing, however, the I2C pins that your sensor needs [haven't been broken out][1] on the OpenLogger.

This means if you really wanted to make this happen, you would have to hand solder those pins and break them out yourself. After that the process is pretty straightforward. SparkFun provides both the [source code][2] and directions on [programming][3] it.

If trying to break those out is a little too tricky, you can either pair it with one of those Arduino models and use it to read the data, or find another similar logger device that has more pins broken out.

Two answer the second part of your question, reading multiple sensors isn't a problem. Usually the way these sensors work is you send a request for data to them and they return the reading, so you would just request from the first sensor, request from the second sensor, write out to the file.

You can write to two different files no problem eiteher. I would not however, recommend writing to two different files. Switching from one file to another, back and forth introduces a little extra overhead which will slow down your loop. In rocketry, things happen very fast, and you'll probably want keep your loop running as fast as possible. I would recommend just writing to a single file and include data from both sensors probably something along the lines of `time,accelX,accelY,accelZ,bar`.

  [1]: https://www.sparkfun.com/datasheets/DevTools/Arduino/OpenLog-v11.pdf
  [2]: https://github.com/sparkfun/OpenLog/tree/master/firmware/OpenLog_v3
  [3]: https://github.com/sparkfun/OpenLog/wiki/flashing-firmware


message:
NRF24L01+ PA not working with Arduino Mega (works with Nano)

**Full disclosure**: I'm a newbie.

I've got an Arduino Nano and a Mega, and a pair of NRF24L01+ PA modules (exactly these: http://www.elektrotedarik.com/Images/Urun/11122013173429.jpeg)

I'm trying to get them to work. I am on this tutorial with the RF24 library: https://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo

On Arduino Nano, it works perfect. I wire everything as told, and set up my radio:

    const uint64_t pipe = 0xE8E8F0F0E1LL;
    RF24 radio(CE_PIN, CSN_PIN);
    fdevopen( &my_putc, 0);
    radio.begin();
    radio.setPALevel(RF24_PA_MAX);
    radio.setDataRate(RF24_250KBPS);
    radio.openWritingPipe(pipe);

When I call `radio.printDetails();` I get a nice output in serial monitor:

    STATUS   = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
    RX_ADDR_P0-1 � = 0xe8e8f0f0e1 0xc2c2c2c2c2
    RX_ADDR_P2-5 � = 0xc3 0xc4 0xc5 0xc6
    TX_ADDR   = 0xe8e8f0f0e1
    RX_PW_P0-6 � = 0x20 0x00 0x00 0x00 0x00 0x00
    EN_AA   = 0x3f
    EN_RXADDR � = 0x03
    RF_CH   = 0x4c
    RF_SETUP � = 0x27
    CONFIG   = 0x0c
    DYNPD/FEATURE � = 0x00 0x00
    Data Rate  = 250KBPS
    Model   = nRF24L01+
    CRC Length  = 16 bits
    PA Power  = PA_HIGH

Everything as expected. If I remove a wire (for testing), it displays all zeroes, when I plug it back, it displays right again, so I assume that it's in working condition. I then try the same with Mega, but even after re-checking the wiring after 4 times, it's not working. Here's what I get with the same code:

    STATUS   = 0x00 RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=0 TX_FULL=0
    RX_ADDR_P0-1 � = 0x0000000000 0x0000000000
    RX_ADDR_P2-5 � = 0x00 0x00 0x00 0x00
    TX_ADDR   = 0x0000000000
    RX_PW_P0-6 � = 0x00 0x00 0x00 0x00 0x00 0x00
    EN_AA   = 0x00
    EN_RXADDR � = 0x00
    RF_CH   = 0x00
    RF_SETUP � = 0x00
    CONFIG   = 0x00
    DYNPD/FEATURE � = 0x00 0x00
    Data Rate  = 1MBPS
    Model   = nRF24L01
    CRC Length  = Disabled
    PA Power  = PA_MIN

Tried many times, no avail. Then I've came upon several threads talking about the different pins. Changed the pins to match Mega's MOSI, MISO, SCK, CE, CSN pins, no avail. I've tried exact same configuration with people who say that it's working, no avail. Then I've stumbled upon that Mega ironically can't supply enough current from the 3V3 pin (while Nano perfectly can) and it can't power the NRF24L01+ PA. I've tried drawing 3V from my power supply (my power supply has either 3 or 4.5 volts, I can't risk burning my transceiver with 4.5 volts). It still doesn't work, and it became extremely hot in seconds (the one attached to my nano doesn't heat up at all). I immediately turned it off, thought that I've burned something, swapped with the Nano's transceiver, and it (fortunatelly) works. So there's no problem with the NRF24L01+ PAs. Why would it not work with Mega (I've also tried the lowest power setting too), and why would it get extremely hot when attached to an external power supply? What else can I do?

**UPDATE:** I've added a 470uF decoupling capacitor to the receiving end (the one attached to Mega), it seems to be worse.

A very interesting observation: If I touch the receiver when it's not working, it starts receiving the signal excellently. If I let it go, signal is lost again.

**UPDATE 2:** Nevermind the last "when I touch..." update, it appears to be related to wiring (haven't soldered them yet, just using jumper wires)

**UPDATE 3:** My initial assumption is correct, something happens when I touch the cables. Something more weird is going on. I soldered my module on a prototype board, and my module sometimes works even without CE pin plugged in. When I touch the cable, it transmits, and stops. Here, TX pin lighting up means it's receiving the signal (I'm writing data to serial). It receives the data (and yeah, the correct data) when I touch the CE pin's cable:

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

How on Earth is this possible? Does the CE pin/cable (and myself) act as an antenna? Makes no sense.

**UPDATE 4:** If I plug that pin to 5V, the whole receiver starts working absolutely perfectly, with no errors/drops at all. But I can't get it: why? And would it overheat/short something?

  [1]: https://i.stack.imgur.com/Gz7kO.gif

body:
I have a NRF24L01 - not that exact model, mine looks like this:

[![NRF24L01 with aerial][1]][1]

Pin-outs:

[![NRF24L01 pin-outs][2]][2]

I hooked it up to my Mega2560 like this:

    NRF24L01     Mega2560
    ----------   ----------------

      VCC         3.3V pin
      Gnd         Gnd
      CSN         D10
      CE          D9
      MOSI        D51 - (MOSI)
      SCK         D52 - (SCK)
      IRQ         N/C
      MISO        D50 - (MISO)

I used the [RF24 library](https://codeload.github.com/maniacbug/RF24/zip/master). Then I hit a number of issues.

For one thing, the "Getting Started" sketch doesn't seem to work too well, even between two Unos, for reasons I haven't worked out.

However the "pingpair" sketch worked OK between two Unos. But **not** when one device was moved to the Mega2560! I tried various things including a separate power supply, and moving the CSN/CE pins around, but to no avail.

Then I had a look at Vcc/Gnd using the scope:

[![NRF24L01 Vcc][3]][3]

That's over half a volt of ripple! I soldered on a 0.1 µF capacitor between Vcc and Gnd on the NRF24L01 and the problems went away. Using the pingpair sketch I now have:

    Now sending 56...ok...Got response 56, round-trip delay: 23
    Now sending 1080...ok...Got response 1080, round-trip delay: 21
    Now sending 2103...ok...Got response 2103, round-trip delay: 21
    Now sending 3126...ok...Got response 3126, round-trip delay: 21
    Now sending 4148...ok...Got response 4148, round-trip delay: 22
    Now sending 5171...ok...Got response 5171, round-trip delay: 22
    Now sending 6194...ok...Got response 6194, round-trip delay: 22
    Now sending 7217...ok...Got response 7217, round-trip delay: 22
    Now sending 8240...ok...Got response 8240, round-trip delay: 21
    Now sending 9263...ok...Got response 9263, round-trip delay: 21
    Now sending 10286...ok...Got response 10286, round-trip delay: 21

So, my suggestion is a decoupling capacitor on the NRF24L01.

---

### Extra

I still had some weird issues where the above results actually came from a NRF24L01 **without** the aerial. The one with the aerial had much more marginal results.

These are the results **with** the aerial:

    Now sending 181378...ok...Failed, response timed out.
    Now sending 182581...ok...Failed, response timed out.
    Now sending 183784...failed.
    Failed, response timed out.
    Now sending 185047...failed.
    Failed, response timed out.
    Now sending 186309...ok...Got response 186309, round-trip delay: 26
    Now sending 187336...ok...Got response 187336, round-trip delay: 22
    Now sending 188359...ok...Failed, response timed out.
    Now sending 189561...ok...Got response 189561, round-trip delay: 22

Still, I think it is worth trying the decoupling capacitor.

---

> and why would it get extremely hot when attached to an external power supply?

Did you have the grounds connected?

  [1]: https://i.stack.imgur.com/f5V7b.jpg
  [2]: https://i.stack.imgur.com/Wg6a6.jpg
  [3]: https://i.stack.imgur.com/WvdeG.png


body:
An old thread.
But I want to share my fix when hooking nRF24 with MEGA. I forgot the website where I got the solution.

It is simply adding a `pinMode(x, OUTPUT)` in the `setup`, where `x` is the CSN pin you choose.

I believe the issue is only on pin 53 only on MEGA.
However, add this in all my sketches with or without MEGA just for precaution.


message:
Float arithmetic vs. int arithmetic - is there any power penalty?

It is widely known that float arithmetic takes longer (that is, eats more cycles) than fixed-point (or integer, or bitwise arithmetic), and that surely is something to consider for speed- and time-critical applications.

My question is: supposing I don't have any time-critical need (and I have enough program and RAM memory), should I be worried by any other disadvantage of using `float`?

Specifically, I wonder if the processor would be more power-hungry because of those extra CPU cycles.

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

UPDATE:   What will my application do meanwhile?

The only goal of the application is to turn lights on and off (lots of them) based on push-button input. I am using `float` to apply filtering to button inputs, in order to [debounce the buttons simulating a RC filter + schmitt-trigger][1]. So the loop in pseudo-code would be:

1. Read all inputs (digitalRead or direct port access);
2. Filter the readings and decide if a button action has been detected;
3. Set some control flags that determine which part of the cycle the lights are in;
4. Check for elapsed time to actually turn blinkers on and off.

So, since I plan to react to button input as realtime as possible, most time would be spent filtering (that is, performing floating point operations), since direct port access and flag-setting are supposed to be nearly instantaneous, right?

  [1]: http://forum.arduino.cc/index.php?topic=125297.0

body:
It depends on what your processor is doing while it has no real work to do:

* If you put it to sleep, then yes, using floats will keep the CPU awake for a longer time and burn more energy.
* If you are instead doing busy-waits (e.g. with `delay()`) it should make no difference, since the CPU is busy 100% of the time anyway.

**Update**: According to your update, it seems your program never
sleeps. Then I would expect no substantial difference in power
consumption between using floats or ints. As Majenko said, there can
theoretically be some small difference depending on the number of
transistor transitions involved in each instruction (and, I would add,
the capacitive loading of the involved transistors), but I do not expect
this to be very significant.

If you are really concerned about the consumption of your Arduino, I
would suggest you use it only for prototyping, then move your code to a
bare ATmega (or maybe even an ATtiny) chip. Also, add at least one call
to `sleep_mode()` inside your main loop. Each such call will put your
CPU to sleep until the next timer interrupt, which typically happens
every 1024 µs. There is a lot more to say about power savings, see
for example this [excellent writeup by Nick
Gammon](http://www.gammon.com.au/power).

**Edit**: When trying to minimize power consumption, one of the very
first things to do is figure out how much work has to be done, and make
sure your program never does more work than required. In your case, this
means you have to know how often your main loop should execute, and
prevent it from running more often than needed. For example:

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

    #include <avr/sleep.h>

    const unsigned long loop_period = 5;  // run the loop every 5 ms.

    void loop() {

        /* Sleep while waiting for the next time slot. */
        static unsigned long last_time;
        while (millis() - last_time < loop_period)
            sleep_mode();
        last_time += loop_period;

        /* Actual work goes here... */
    }

If the actual loop work takes significantly less time than the loop
period, your CPU will sleep most of the time, leading to significant
power savings. Then you can start digging into more advanced
power-saving techniques like those mentioned in the article linked
above.


body:
Yes, more power will (theoretically) be consumed.  That is, compared to doing nothing.

Float operations will require more mathematical operations to perform compared with integer or fixed point.  That will mean more gates are being activated and deactivated etc, compared to doing nothing.

Would that increase in power be noticeable?  Probably not.  It'll be so tiny as to be negligible.  As Edgar Bonet has mentioned, if you are making use of sleep modes then the extra time taken to perform the float operations will impact the ratio of running to sleep time, but if all you are doing is a set of mathematical operations a few times a second and using the `millis()` or `delay()` functions to control the timing then the difference will be so minimal you'll never notice it.

The effect is more noticeable on a PC when you perform very complex operations (like 3D rendering) and the CPU gets hotter and the fan speeds up.  In this situation the CPU is entering an *idle* state (like sleep, but less so) when it's not needing to perform any tasks which reduces both power consumption and heat dissipation.  When performing heavy tasks it has less time to be idle and so generates more heat. The more complex the operations the more transistors need to switch and so the more heat is dissipated.

Unfortunately the power dissipation per op-code is not documented, but it should be possible to write some assembly code to execute a single instruction in a tight loop (start with NOP) and measure the current, then change that instruction for a different one and compare the current.  Using NOP as a baseline you should then be able to calculate the increase in current for each op-code.  Of course, the actual data the op-codes are operating on will also have a bearing on the power consumption.

But that would be pretty pointless unless you are budgeting for every single femtowatt of power.


body:
If you are interested in power saving, I think it would be more important to check that the standard Arduino library doesn't turn on HW blocks that you do not need.

From an engineering perspective, though, the filter you are pursuing seems a bit overkill, if you only worry about bounces. Waiting for a reasonable amount of time after the first transition should be sufficient and would keep the code simpler to write, test and debug.

The mechanical switch is already a dampened system with its own intrinsic time constant.


body:
> The only goal of the application is to turn lights on and off (lots of them) based on push-button input. I am using float to apply filtering to button inputs, in order to debounce the buttons simulating a RC filter + schmitt-trigger.

Using floats is **way** overkill here. To debounce all you need to do is note when the switch changed state, and ignore further state changes during a certain interval, say 10 ms. It is even quite feasible to sleep during that debounce period. One of the watchdog timer intervals is 16 ms which would be about right for that.

In any case, an application that turns lights on is hardly going to be one where you are worried about how much power floating point operations take. I would be 1000 times more worried about how much power the lights use.


message:
Arduino Uno & Simulink - high frequency pulses

I'm trying to control a large stepper motor with high frequency pulses (eventually around 4kHz), but what I get out of the simulink scope is super different from what the Arduino is putting out. I'm using this variable frequency PWM block: www.mathworks.com/matlabcentral/fileexchange/48563-variable-frequency-pwm-block

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

(yes, I've tried it on pin 5/6, but if I do that there's no difference)

This is the output from the Simulink scope (period of 0.01s):[![output from scope][2]][2]

and the Arduino is putting out pulses with a period of ~4 seconds. This is on pin 6 of the Uno, by the way. Why won't the Arduino output the same frequency as the Simulink program?

  [1]: https://i.stack.imgur.com/LHwle.png
  [2]: https://i.stack.imgur.com/qxJLy.png

body:
It seems clear from what you have described that this is a Simulink bug.

> Why won't the Arduino output the same frequency as the Simulink program?

The Arduino can output quite a lot of frequencies. I have a [page about Arduino timers](http://www.gammon.com.au/timers) which describes them in some detail.

However since Simulink is generating the code for the Arduino (which we are not being shown) and since it claims to be generating 0.01 s, and the code it is generating does not do this, that is a bug in Simulink.

I suggest you contact their customer support.

Alternatively you could attempt to program the hardware timers yourself. The page I linked could be a good starting point for such an exercise.


message:
Existence of a non blocking and task yield framework for Arduino programming

I've been playing around with Arduino and understand that the standard runtime provides a single thread essentially.

I was wondering if it is possible to write a thin layer (library) that allows one to write code that is non blocking and one where each task yields control manually which allows the master loop to implement some form of timesharing.

I'd appreciate any:

1. Comments on existing frameworks that can allow me to write my programs this way
2. Any comments on how hard implementing anything of this order of magnitude would be.

body:
I would recommend [NilRTOS][1].
I like the fact that it's really minimal.
However, you might find that some libraries (which you would like to use) work in blocking mode and cannot be used with this RTOS, because they might do bad things (polling) or worse things (polling in interrupt context with other interrupts disabled).
But that will be the case regardless of the thread framework you choose.

You might want to try also [femtoos][2].
I think that the code could be organized far better, which is one of the reasons I preferred NilRTOS.

  [1]: https://github.com/greiman/NilRTOS-Arduino
  [2]: http://www.femtoos.org/


body:
My recommendation would be to simply code without needing blocking. I have examples [here](http://www.gammon.com.au/blink).

Petri Häkkinen coded a game - [Toorum's Quest](https://www.youtube.com/watch?v=sLvgW_zb6bQ) - without using any real-time library. That game (on a Uno) has multiple sprites, TV output and sound effects, all interleaved.

The basic technique is to know that you have multiple things you need to have done, from time to time, and check in the main loop if it is time to do one of them.

One issue with any sort of real-time library is, you only have limited resources. You need to be really aware, for example, of which bits of hardware are doing what (eg. timers, SPI, I2C, interrupt handlers, serial comms).

Even existing libraries suffer from the problem that one library may require (say) pin-change interrupts, and "requisition" the interrupt handlers needed for that, and another library also uses pin-change interrupts, and they cannot be linked together.


message:
Arrays and Functions

How can I return a char array from a function?

    char c[] = getFloat(val, valid);

    char getFloat(float val, bool valid){
          if(valid){
            char stringFloat[16];
            dtostrf(val, 10, 8, stringFloat);
            return stringFloat;
          } else Serial.print("No Float");
        }

body:
Allocate it in the heap. Don't forget to free it after.

    #include <stdlib.h>
    #include <string.h>

     ...

    char *c = getFloat(val, valid);
    use(c);
    free(c);

     ...

    char *getFloat(float val, bool valid){
      if(valid){
        char stringFloat[16], *ret;
        dtostrf(val, 10, 8, stringFloat);
        ret = strdup(stringFloat);
        return ret;
      } else {
        Serial.print("No Float");
        return NULL;
      }
    }


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

An alternative method would be to allocate the string **statically** inside the function, like this:

    const char * getFloat(float val, bool valid){
          if (valid)
            {
            static char stringFloat[16];
            dtostrf(val, 10, 8, stringFloat);
            return stringFloat;
            }
          else
            return "No Float";
        }

Now we can use that string:

    const char * c = getFloat(24.5678, true);

However note that this is only good for one use **at a time**!

This would not work properly, for example:

    const char * c1 = getFloat(24.5678, true);
    const char * c2 = getFloat(42.7654, true);

Now c1 and c2 both point to the same piece of memory, so only the last one would be correct. However this restriction may not matter to you. And it saves you having to free memory afterwards, and possibly saves you from heap fragmentation.


message:
Recover from wrong Wi-Fi password on Arduino Yún

I'm trying to customize my Arduino Yún to work as an access-point (or hotspot) for providing services to clients directly connected and, alternatively, to work as a client on a wireless network for downloading resources from the Internet.

The access to such a wireless network is gained after the user submits a network SSID and password in the web control panel provided by Yún.

How can I recover from a user submitting a wrong password? At the moment the Yún stays stuck without any connection, and thus is unreachable via SSH to attempt any recover.

body:
The simplest option is to provide a serial console interface which will either give full access to the OS (pipe through *Console*) or a menu driven interface that sends instructions to the main chip (through *Bridge*).

The user would then connect to the USB interface and use a terminal program to access the configuration in whatever way you have chosen.  This could either be via options within your installed sketch, or by uploading a special sketch through the USB connection.


body:
At the end I came out with a button connected to one of the digital input pins and a sketch that, using the bridge to communicate with the "Linux part" of Yún, restores original values in the configuration files and reboots the whole controller.

After the reboot completes the Arduino Yún is accessible again through the Wi-Fi network "Arduino Yun xxxxxxxxxx".


message:
is there any possibility of connecting ACCELEROMETER + ARDUINO UNO + GSM module together?

I am lakshman a mechanical engineer,i have a question that is there any possibility of connecting ACCELEROMETER + ARDUINO UNO + GSM module together???

so that i can take the output value from Accelerometer so that to make a call to a preprogrammed number???

Plz help me.

Thank you.

body:
Yes, that is perfectly possible.  Typically:

* Accelerometer is either an analog, SPI or I2C interface.
* GSM is usually a UART interface
* The Arduino UNO has all four interfaces (analog, SPI, I2C and UART) available on separate pins.

The rest is just a SMOP.


message:
Wrong code ouput, when the specific function runs more than once

If I run the following code, I get the correct output, and the path is displayed on the serial monitor. However when I run the code together with the commented out portion (in the code below) I don't get any output; even the output that is printed before this code doesn't print completely. Why is that?

I have figured it out that this happens when the dijkstra functions runs more than once. But it shouldn't happen like this.

       int *path1 = NULL;
     int no_of_nodes_1;
     dijkstra(graph, startingNode1, end1_start2, &path1, no_of_nodes_1);

     /*int *path2 = NULL;
     int no_of_nodes_2;
     dijkstra(graph, end1_start2, end2_start3, &path2, no_of_nodes_2);

     int *path3 = NULL;
     int no_of_nodes_3;
     dijkstra(graph, end2_start3, endingNode3, &path3, no_of_nodes_3);
            */
            delete graph;

     Serial.println();

     Serial.println( "PATH 1:");
     for (int k = 0; k < no_of_nodes_1; k++){
      Serial.print(path1[k]);Serial.print("..");
            }

    /*
     Serial.println();
            Serial.println( "PATH 2:");
     for (int x = 0; x < no_of_nodes_2; x++){
      Serial.print(path2[x]);Serial.print("..");
     }

     Serial.println();
     Serial.println( "PATH 3:");
     for (int y = 0; y < no_of_nodes_3; y++){
      Serial.print(path3[y]);Serial.print("..");
     }

    */

**::UPDATE::**

    /******************************************************************************/
        void getNextNode(int node, const int& src, const int predecessor[264], int temp_path[], int& i){

         i = 1;

         if (node == src)
         {
          temp_path[i] = src;
         }

         else if (predecessor[node] == -1)
         {
                    Serial.println("No path exists");
         }
         else {
          getNextNode(predecessor[node], src, predecessor, temp_path, i);
          temp_path[i] = node;
          i++;
         }

         return;
        }
    /********************************************************************************/
        int* savePath(int predecessor[264], const int& src, const int& targetnode, int & numofnodes){

         int temp_path[200];
         temp_path[0] = src;
         int i;

         if (targetnode == src)
         {
          temp_path[1] = src;
         }
         else
         {
          getNextNode(targetnode, src, predecessor, temp_path, i);
         }

         numofnodes = i;
         int *path = new int[i];

         for (int k = 0; k < i; k++){
          path[k] = temp_path[k];
         }

         return path;

        }
     /****************************************************************************/
        void dijkstra(struct Graph* graph, int src, int target, int **path, int& numofnodes)
        {
         // The main function that calulates distances of shortest paths from src to all
         // vertices. It is a O(ELogV) function

         int V = graph->V;// Get the number of vertices in graph
         int* dist = new int[V];      // dist values used to pick minimum weight edge in cut

         int predecessor[264]; //array to save nearest nodes

         // minHeap represents set E
         struct MinHeap* minHeap = createMinHeap(V);

         // Initialize min heap with all vertices. dist value of all vertices
         for (int v = 0; v < V; ++v)
         {
          dist[v] = INT_MAX;
          minHeap->array[v] = newMinHeapNode(v, dist[v]);
          minHeap->pos[v] = v;
          predecessor[v] = -1;
         }

         // Make dist value of src vertex as 0 so that it is extracted first
         minHeap->array[src] = newMinHeapNode(src, dist[src]);
         minHeap->pos[src] = src;
         dist[src] = 0;
         decreaseKey(minHeap, src, dist[src]);

         // Initially size of min heap is equal to V
         minHeap->size = V;

         // In the followin loop, min heap contains all nodes
         // whose shortest distance is not yet finalized.
         while (!isEmpty(minHeap))
         {
          // Extract the vertex with minimum distance value
          struct MinHeapNode* minHeapNode = extractMin(minHeap);
          int u = minHeapNode->v; // Store the extracted vertex number

          // Traverse through all adjacent vertices of u (the extracted
          // vertex) and update their distance values
          struct AdjListNode* pCrawl = graph->array[u].head;
          while (pCrawl != NULL)
          {
           int v = pCrawl->dest;

           // If shortest distance to v is not finalized yet, and distance to v
           // through u is less than its previously calculated distance
           if (isInMinHeap(minHeap, v) && dist[u] != INT_MAX &&
            /*pCrawl->weight*/1 + dist[u] < dist[v])
           {
            dist[v] = dist[u] + 1 /*pCrawl->weight*/; // 1 is the weight of the node
            predecessor[v] = u;
            // update distance value in min heap also
            decreaseKey(minHeap, v, dist[v]);
           }
           pCrawl = pCrawl->next;
          }
         }

            delete[] dist;
            delete minHeap;
         *path = savePath(predecessor, src, target, numofnodes);
        }

body:
You have likely run out of RAM.

You have 200 integers in the `temp_path` array. That equates to 400 bytes of SRAM. You also have 3 `predecessor` arrays each with 264 integers, which equates to 1584 bytes. These arrays combined use 1984 bytes. This is in addition to all your other variables and function calls.

The Arduino Uno only has 2KB of SRAM.

Solution:
Use an Arduino with a greater amount of SRAM.

 - ARDUINO M0/Zero - 32KB of SRAM
 - Arduino Mega  - 8KB of SRAM
 - Arduino Due   - 96KB of SRAM