body:
Eventually i've found the reason. And it was bug in HM-10 firmware.
In mode 0 it does not accept control commands and in modes 1 and 2 it accepts AT commands to control PIO and commands are look like 'AT+...', f.e. 'PIO set value 1 to pin 1' command is 'AT+PIO11' and change mode to 0 look like 'AT+MODE0'. I need mode 1 to set PIO to 1 and 0 to reset arduino board. The problem is that some of upload commands look like 'A [0x41] . [0x81]   [0x20]' (starts from 'A' too) and it makes HM-10 think it's control command which also starts from 'A'. If i add changing mode to 0 after pin control commands (in order to make HM-10 stop accepting control commands) it starts uploading:

    2015-09-18 10:27:32.144 xctest[94852:4603627] [TRACE  ] [IN ]: Rx value received 9 bytes: O [0x4F] K [0x4B] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] : [0x3A] 1 [0x31]
    2015-09-18 10:27:32.145 xctest[94852:4603627] [WARNING] [IN ]: Got 9 bytes in incoming buffer
    2015-09-18 10:27:32.145 xctest[94852:4603627] [TRACE  ] [IN ]: Rx value received 9 bytes: O [0x4F] K [0x4B] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] : [0x3A] 0 [0x30]
    2015-09-18 10:27:32.146 xctest[94852:4603627] [WARNING] [IN ]: Got 9 bytes in incoming buffer
    2015-09-18 10:27:32.146 xctest[94852:4603627] [TRACE  ] [IN ]: Rx value received 8 bytes: O [0x4F] K [0x4B] + [0x2B] S [0x53] e [0x65] t [0x74] : [0x3A] 0 [0x30]
    2015-09-18 10:27:32.147 xctest[94852:4603627] [WARNING] [IN ]: Got 8 bytes in incoming buffer
    2015-09-18 10:27:32.147 xctest[94852:4603627] [TRACE  ] [IN ]: Rx value received 1 bytes: . [0x00]
    2015-09-18 10:27:32.147 xctest[94852:4603627] [TRACE  ] [IN ]: Ignoring single 0x00 char
    2015-09-18 10:27:32.207 xctest[94852:4603578] [TRACE  ] [IN ]: Finish reading
    2015-09-18 10:27:32.208 xctest[94852:4603578] [TRACE  ] [IN ]: Ble clear buffer
    2015-09-18 10:27:32.208 xctest[94852:4603578] [DEBUG  ] [IN ]: Drained 26 bytes
    2015-09-18 10:27:32.208 xctest[94852:4603578] [DEBUG  ] [   ]: Draining incoming buffer (0 bytes)
    2015-09-18 10:27:32.208 xctest[94852:4603578] [DEBUG  ] [OUT]: Sending 2 bytes
    2015-09-18 10:27:32.208 xctest[94852:4603578] [TRACE  ] [OUT]: Send: 0 [0x30]   [0x20]
    2015-09-18 10:27:32.209 xctest[94852:4603578] [TRACE  ] [OUT]: BLE sending bytes range from 0 length 2
    2015-09-18 10:27:32.209 xctest[94852:4603578] [DEBUG  ] [IN ]: Reading 1 bytes ...
    2015-09-18 10:27:32.209 xctest[94852:4603578] [TRACE  ] [IN ]: Start reading
    2015-09-18 10:27:32.561 xctest[94852:4603630] [TRACE  ] [IN ]: Rx value received 1 bytes: . [0x00]
    2015-09-18 10:27:32.561 xctest[94852:4603630] [TRACE  ] [IN ]: Ignoring single 0x00 char
    2015-09-18 10:27:32.561 xctest[94852:4603627] [TRACE  ] [IN ]: Rx value received 2 bytes: . [0x11] . [0xFC]
    2015-09-18 10:27:32.561 xctest[94852:4603627] [WARNING] [IN ]: Got 2 bytes in incoming buffer
    2015-09-18 10:27:32.563 xctest[94852:4603578] [TRACE  ] [IN ]: Finish reading
    2015-09-18 10:27:32.563 xctest[94852:4603578] [TRACE  ] [IN ]: Receive: . [0x11]
    2015-09-18 10:27:32.563 xctest[94852:4603578] [DEBUG  ] [IN ]: Read 1 bytes, actually received 2 bytes
    2015-09-18 10:27:32.563 xctest[94852:4603578] [TRACE  ] [IN ]: 1 bytes in incoming buffer remaining for next receive
    2015-09-18 10:27:32.563 xctest[94852:4603578] [ERROR  ] [   ]: STK500:synchronize: attempt 1 of 3: no sync: received [0x11]
    2015-09-18 10:27:32.564 xctest[94852:4603578] [DEBUG  ] [   ]: Draining incoming buffer (1 bytes)
    2015-09-18 10:27:32.564 xctest[94852:4603578] [DEBUG  ] [OUT]: Sending 2 bytes
    2015-09-18 10:27:32.564 xctest[94852:4603578] [TRACE  ] [OUT]: Send: 0 [0x30]   [0x20]
    2015-09-18 10:27:32.564 xctest[94852:4603578] [TRACE  ] [OUT]: BLE sending bytes range from 0 length 2
    2015-09-18 10:27:32.565 xctest[94852:4603578] [DEBUG  ] [IN ]: Reading 1 bytes ...
    2015-09-18 10:27:32.565 xctest[94852:4603578] [TRACE  ] [IN ]: Start reading
    2015-09-18 10:27:32.636 xctest[94852:4603627] [TRACE  ] [IN ]: Rx value received 1 bytes: . [0x00]
    2015-09-18 10:27:32.636 xctest[94852:4603627] [TRACE  ] [IN ]: Ignoring single 0x00 char
    2015-09-18 10:27:32.636 xctest[94852:4603627] [TRACE  ] [IN ]: Rx value received 2 bytes: . [0x14] . [0x10]
    2015-09-18 10:27:32.636 xctest[94852:4603627] [WARNING] [IN ]: Got 2 bytes in incoming buffer
    2015-09-18 10:27:32.638 xctest[94852:4603578] [TRACE  ] [IN ]: Finish reading
    2015-09-18 10:27:32.638 xctest[94852:4603578] [TRACE  ] [IN ]: Receive: . [0x14]
    2015-09-18 10:27:32.638 xctest[94852:4603578] [DEBUG  ] [IN ]: Read 1 bytes, actually received 2 bytes
    2015-09-18 10:27:32.638 xctest[94852:4603578] [TRACE  ] [IN ]: 1 bytes in incoming buffer remaining for next receive
    2015-09-18 10:27:32.639 xctest[94852:4603578] [DEBUG  ] [IN ]: Reading 1 bytes ...
    2015-09-18 10:27:32.639 xctest[94852:4603578] [TRACE  ] [IN ]: Having current receive buffer: . [0x10]
    2015-09-18 10:27:32.639 xctest[94852:4603578] [TRACE  ] [IN ]: Start reading
    2015-09-18 10:27:32.639 xctest[94852:4603578] [TRACE  ] [IN ]: Finish reading
    2015-09-18 10:27:32.640 xctest[94852:4603578] [TRACE  ] [IN ]: Receive: . [0x10]
    2015-09-18 10:27:32.644 xctest[94852:4603578] [DEBUG  ] [IN ]: Read 1 bytes, actually received 1 bytes
    2015-09-18 10:27:32.644 xctest[94852:4603578] [TRACE  ] [IN ]: Ble clear buffer
    2015-09-18 10:27:32.645 xctest[94852:4603578] [DEBUG  ] [OUT]: Sending 3 bytes
    2015-09-18 10:27:32.645 xctest[94852:4603578] [TRACE  ] [OUT]: Send: A [0x41] . [0x81]   [0x20]
    2015-09-18 10:27:32.645 xctest[94852:4603578] [TRACE  ] [OUT]: BLE sending bytes range from 0 length 3
    2015-09-18 10:27:32.645 xctest[94852:4603578] [DEBUG  ] [IN ]: Reading 1 bytes ...
    2015-09-18 10:27:32.646 xctest[94852:4603578] [TRACE  ] [IN ]: Start reading
    2015-09-18 10:27:32.711 xctest[94852:4603630] [TRACE  ] [IN ]: Rx value received 1 bytes: . [0x00]
    2015-09-18 10:27:32.711 xctest[94852:4603630] [TRACE  ] [IN ]: Ignoring single 0x00 char
    2015-09-18 10:27:32.711 xctest[94852:4603630] [TRACE  ] [IN ]: Rx value received 3 bytes: . [0x14] . [0x04] . [0x10]
    2015-09-18 10:27:32.711 xctest[94852:4603630] [WARNING] [IN ]: Got 3 bytes in incoming buffer
    2015-09-18 10:27:32.712 xctest[94852:4603578] [TRACE  ] [IN ]: Finish reading
    2015-09-18 10:27:32.713 xctest[94852:4603578] [TRACE  ] [IN ]: Receive: . [0x14]
    2015-09-18 10:27:32.713 xctest[94852:4603578] [DEBUG  ] [IN ]: Read 1 bytes, actually received 3 bytes
    2015-09-18 10:27:32.713 xctest[94852:4603578] [TRACE  ] [IN ]: 2 bytes in incoming buffer remaining for next receive
    2015-09-18 10:27:32.713 xctest[94852:4603578] [DEBUG  ] [IN ]: Reading 1 bytes ...
    2015-09-18 10:27:32.713 xctest[94852:4603578] [TRACE  ] [IN ]: Having current receive buffer: . [0x04] . [0x10]
    2015-09-18 10:27:32.714 xctest[94852:4603578] [TRACE  ] [IN ]: Start reading
    2015-09-18 10:27:32.714 xctest[94852:4603578] [TRACE  ] [IN ]: Finish reading
    2015-09-18 10:27:32.728 xctest[94852:4603578] [TRACE  ] [IN ]: Receive: . [0x04]
    2015-09-18 10:27:32.728 xctest[94852:4603578] [DEBUG  ] [IN ]: Read 1 bytes, actually received 2 bytes
    2015-09-18 10:27:32.729 xctest[94852:4603578] [TRACE  ] [IN ]: 1 bytes in incoming buffer remaining for next receive
    2015-09-18 10:27:32.729 xctest[94852:4603578] [DEBUG  ] [IN ]: Reading 1 bytes ...
    2015-09-18 10:27:32.729 xctest[94852:4603578] [TRACE  ] [IN ]: Having current receive buffer: . [0x10]
    2015-09-18 10:27:32.729 xctest[94852:4603578] [TRACE  ] [IN ]: Start reading
    2015-09-18 10:27:32.730 xctest[94852:4603578] [TRACE  ] [IN ]: Finish reading
    2015-09-18 10:27:32.730 xctest[94852:4603578] [TRACE  ] [IN ]: Receive: . [0x10]
    2015-09-18 10:27:32.730 xctest[94852:4603578] [DEBUG  ] [IN ]: Read 1 bytes, actually received 1 bytes
    2015-09-18 10:27:32.730 xctest[94852:4603578] [TRACE  ] [IN ]: Ble clear buffer
    2015-09-18 10:27:32.731 xctest[94852:4603578] [DEBUG  ] [OUT]: Sending 3 bytes
    2015-09-18 10:27:32.731 xctest[94852:4603578] [TRACE  ] [OUT]: Send: A [0x41] . [0x82]   [0x20]
    2015-09-18 10:27:32.731 xctest[94852:4603578] [TRACE  ] [OUT]: BLE sending bytes range from 0 length 3
    2015-09-18 10:27:32.732 xctest[94852:4603578] [DEBUG  ] [IN ]: Reading 1 bytes ...
    2015-09-18 10:27:32.732 xctest[94852:4603578] [TRACE  ] [IN ]: Start reading
    2015-09-18 10:27:32.786 xctest[94852:4603627] [TRACE  ] [IN ]: Rx value received 1 bytes: . [0x00]
    2015-09-18 10:27:32.786 xctest[94852:4603627] [TRACE  ] [IN ]: Ignoring single 0x00 char
    2015-09-18 10:27:32.787 xctest[94852:4603627] [TRACE  ] [IN ]: Rx value received 3 bytes: . [0x14] . [0x04] . [0x10]
    2015-09-18 10:27:32.787 xctest[94852:4603627] [WARNING] [IN ]: Got 3 bytes in incoming buffer
    2015-09-18 10:27:32.788 xctest[94852:4603578] [TRACE  ] [IN ]: Finish reading
    2015-09-18 10:27:32.788 xctest[94

I was working for Mega2560 since it uses different bootloader and upload commands do not start from 'A'. It's definitely HM-10 firmware bug as it can understand it's not control command since the second byte is not 'T'.

If i had oscilloscope i'd find the reason in 1 hour but for casual engineering i don't need it. I've reported a bug to HM-10 manufacturer but i'm not sure when they fix it. HM-10 firmware version is v532.


sender: user

message:
How to print a line with a variable in it?

I want to know if there is a way to write like in C programming:

      printf("the num is %d",num);

I know that to print a line or a variable the command will be Serial.println
when I write:

     Serial.println("the num is %d",num);

It's not working.

Is there a way to write it in just one line?

sender: assistant

body:
    Serial.print("the num is "); Serial.println(num);
is how you do it with the Serial object. There is a printf in the library and it's a lot easier to use (as you already know) but a little bit more work to set up. Here is a simple program using printf:

    // Define a file descriptor for the serial output:
    static FILE uartout = { 0 };

    // Declare our put-character function:
    static int uart_putchar (char c, FILE *stream);

    void setup() {
       // Fill in UART file descriptor with pointer to my char-out func.
       fdev_setup_stream(&uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE);
       stdout = &uartout;

       Serial.begin(9600);   // open serial port, sets baud rate
    }

    void loop( void ){
       printf("Run time: %ld\n", millis());
       delay(1000);          // wait 1 sec
    }

    // My char output function
    static int uart_putchar (char c, FILE *stream)
    {
       if( c == '\n' )
       Serial.write('\r');
       Serial.write(c) ;
       return 0 ;
    }


body:
You can try "extending" the Print class to include a printf() function.  It requires modification of the Arduino core to add it, and it's something I have been meaning to suggest to the Arduino guys as a permanent modification, but I often manually add a function such as this:

    void Print::printf(const char *fmt, ...) {
        va_list va;
        va_start(va, fmt);
        char temp[1];
        uint32_t slen = vsnprintf(temp, 1, fmt, va);
        va_end(va);
        char out[slen + 2];
        va_start(va, fmt);
        vsnprintf(out, slen+1, fmt, va);
        va_end(va);
        print(out);
    }

to my core.

It's not wonderfully efficient from a processing point of view - it first runs a `vsnprintf()` to a single byte target.  This allows it to work out how long the formatted string will need to be:

> If the output was truncated due to this limit, then the return value is the number of characters (excluding the terminating null byte) which would have been written to the final string if enough space had been available.

So it then knows how much memory is needed to store the formatted string.  It then goes ahead and allocates that much memory on the stack and re-formats the string again into that newly allocated memory.  It can then go ahead and send that data to the serial port.

It's a "quick and dirty" hack, but it works.  A better solution would be to re-write the `printf()` parser in the function and instead of formatting to memory then printing, to format the data stream directly to the `Serial` device, thus saving the double-processing and memory allocation.

You can then quite happily do things like:

    Serial.printf("The temperature is %d degrees C\n", temperature);


body:
I use:

    Serial.println("The temperature is " + String(temperature) + " degrees C");

With this solution you can't format the variable's value but I find this quick and dirty for debug messages.


message:
How to calculate voltage?

I want to check each cell voltage using arduino.

and how to calculate dc current using CT Sensor using Arduino?

body:
You have two problems here:

1. How to take 24 readings on an Arduino with only 6 analog inputs.
2. How to get the voltage in the range of 0 to 5 volts.

To take 24 readings you can use an [analog multiplexer](http://www.gammon.com.au/forum/?id=11976) or two. For example the 74HC4051 (8 channels) or the 74HC4067 (16 channels). With both of those you could handle 24 channels.

---

To read the voltages you could successively read each cell, relative to ground (eg. the first one should be 2 V, the second should be 4 V, and so on up to 48 V).

Cells 1 and 2 are fine, they are lower than 5 V. Cells 3 to 24 are not. You need to set up a voltage divider to divide down the voltage into the range 0 to 5.

The formula for a voltage divider is:

    Vout = Vin * R2/(R1+R2)

Let's make R1 to be 10k ohms, and solve for R2 (given that we want Vout to be 5).

    R2 = Vout * R1/(Vin - Vout)
    R2 = 5 * 10000 / (Vin - 5)

Plugging that into a spreadsheet we get:

    Vin    R
    6  50000
    8  16667
    10 10000
    12  7143
    14  5556
    16  4545
    18  3846
    20  3333
    22  2941
    24  2632
    26  2381
    28  2174
    30  2000
    32  1852
    34  1724
    36  1613
    38  1515
    40  1429
    42  1351
    44  1282
    46  1220
    48  1163

---

These aren't particularly easy resistor values to work with, so we'll use standard values and calculate what the output voltage should be (with the spreadsheet):

    Vin   R   volts   Scale
    2
    4
    6   47000 4.9474  1.2128    <--- R2 is 47 k
    8   16000 4.9231  1.6250    <--- R4 is 16 k
    10  10000 5.0000  2.0000
    12   6800 4.8571  2.4706
    14   5100 4.7285  2.9608
    16   4300 4.8112  3.3256
    18   3600 4.7647  3.7778
    20   3300 4.9624  4.0303
    22   2700 4.6772  4.7037
    24   2400 4.6452  5.1667
    26   2200 4.6885  5.5455
    28   2000 4.6667  6.0000
    30   2000 5.0000  6.0000
    32   1800 4.8814  6.5556
    34   1600 4.6897  7.2500
    36   1600 4.9655  7.2500
    38   1500 4.9565  7.6667
    40   1300 4.6018  8.6923
    42   1300 4.8319  8.6923
    44   1200 4.7143  9.3333
    46   1200 4.9286  9.3333
    48   1100 4.7568 10.0909

The "Scale" column will be explained in a moment.

---

Now we are ready to make up a circuit along these lines:

[![Multiplexer circuit][1]][1]

I haven't shown all the battery cells here - I don't have that much energy! But the principle is the same.

---

The 2V and 4V inputs we can read directly. From 6V upwards we need to apply the scaling factor from the voltage divider network.

That is shown in the "Scale" column above.

The formula for the voltage on the pin is:

    float voltage = ((float) rawADC  + 0.5 ) / 1024.0 * Vref;

So assuming Vref is 5V, and you have a reading of 512, then you apply it like this:

     ( 512  + 0.5 ) / 1024.0 * 5 = 2.502 volts

Now you multiply by the scale factor above, so if this was the 34 V input, the scale factor would be 7.25, and the voltage from the battery would be:

    2.502 * 7.25 = 18.14  volts

---

The stage is now set to work out each voltage:

* Use the multiplexer "select" pins to choose one of the battery inputs
* Take an analog reading
* Scale it by the appropriate amount from the table
* Work out what the charge in the cell is (by comparing it to the previous one)

For example, if the first cell read 1.9V and the second cell read 3.85V then you know that the difference is 3.85 - 1.9 which is 1.95 volts.

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


message:
Serial comms failure after long time - can't open COM port

I've been using an Arduino UNO to log data: it's queried by a LabView VI over a VISA connection. It'll happily sit there and log for days, but very occasionally one of the VISA functions will fail.

After this, I can't open the COM port again (in LabView or elsewhere) and the only way to restore communication is to unplug and replug the USB cable. The Arduino hasn't crashed because I can see the other results of the program it's running working fine, but Serial comms are a gonner.

Has anyone experienced this? Do you know if this is an Arduino problem, a Labview problem, a Windows problem? Or something else?

I'm writing a minimum working example to try and catch this happening in the most simple code possible, but since the error usually takes several days to show up I can't tell you the results yet!

body:
The assumption I am making is "VISA connection" is a PC operating VISA.
I have seen ports shut down on windows several times yet the same port works fine while in DOS.  My suggestion is try a different computer, that should narrow down your problem to which side of the connector is failing.


body:
In the end I found a solution, more or less through trial and error.

Labview default its VISA VIs to "asynchronous" mode: I found that by switching them to "synchronous" (right click on them and select "synchronous") this problem disappeared.

I think this is caused by the computer occasionally getting ahead of the Arduino and asking for the next measurement before it's finished receiving the first one. Switching to synchronous mode forces execution to wait until the VISA exchange is complete before it continues.


message:
C++ Pointer Issues - Mangled Data

I am having trouble getting my head around pointers in C++, specifically how they behave when passed around or used within objects. As far as my understanding goes as long as pointers, or more specifically values/objects pointed *to* - do not go out of scope, I should be able to use that pointer.

I have been playing around with some test code on my Arduino Uno and I am bumping into behaviour I cannot explain.

I have read rather a lot on the topic of pointers in C++ and thought I had a good grasp of it. However, practice doesn't seem to match the theory in my head. I don't know if this is a lack of understanding or if the Arduino platform has idiosyncrasies that I am not aware of.

In my test code I have created two classes, `Alpha` and `Beta`. Alpha simply holds a C-type string in a member variable called `alpha`. `Beta` is designed to hold two `Alpha` instances in an array*.

*While this is "toy" code, the general structure mirrors my actual project. I have used this toy code as it more succinctly describes the set up and the issue I am facing.

**pointers.h**

    #import "Arduino.h"
    class Alpha {
        private:
            char alpha[20];
        public:
            Alpha();
            ~Alpha();
            char* getAlpha(char* s, int size=20);
            void setAlpha(char* value, int size=20);
            void debug();
    };

    class Beta {
        private:
            Alpha** alphas;
        public:
            Beta();
            ~Beta();
            Alpha* getAlpha(int index);
            void setAlpha(Alpha* alpha, int index);
            void doStuffWithAlpha(int index);
    };

**pointers.cpp**

    #import "pointers.h"

    Alpha::Alpha() {
        setAlpha("Initial");
    }

    Alpha::~Alpha() {}

    char* Alpha::getAlpha(char* s, int size/*=20*/) {
        *s = *alpha;
        return s; //return not strictly needed here since s is passed in
    }

    void Alpha::setAlpha(char* value, int size/*=20*/) {
        strncpy(alpha, value, size-1);
        alpha[size-1] = '\0';
    }

    void Alpha::debug() {
        Serial.println(alpha);
    }

    Beta::Beta() {
        alphas = new Alpha*[2];
    }

    Beta::~Beta() {}

    Alpha* Beta::getAlpha(int index) {
        return alphas[index];
    }

    void Beta::setAlpha(Alpha* alpha, int index) {
        alphas[index] = alpha;
    }

    void Beta::doStuffWithAlpha(int index) {
        Alpha* alpha = getAlpha(index);
        /* Alpha* alpha = alphas[index]; */ //This doesn't work either - same outcome.
        alpha->debug();
    }

**sketch.ino**

    #import "pointers.h"
    Alpha a1;
    Alpha a2;
    Beta b1;

    void setup() {
        Serial.begin(9600);
        Serial.println("SETUP()");
        Serial.println();

        a1 = Alpha();
        a1.setAlpha("Hello");

        Serial.println("----- a1.debug -----");
        Serial.println("Expected: Hello");
        Serial.print("Actual: "); a1.debug();
        Serial.println();

        a2 = Alpha();
        a2.setAlpha("Goodbye");

        Serial.println("----- a2.debug -----");
        Serial.println("Expected: Goodbye");
        Serial.print("Actual: "); a2.debug();
        Serial.println();

        Beta b1 = Beta();
        b1.setAlpha(&a1, 0);
        b1.setAlpha(&a2, 1);

        Serial.println("----- b1.doStuffWithAlpha -----");
        Serial.println("Expected: Hello");
        Serial.print("Actual: "); b1.doStuffWithAlpha(0);
        Serial.println("Expected: Goodbye");
        Serial.print("Actual: "); b1.doStuffWithAlpha(1);
        Serial.println();
    }

    void loop() {
        Serial.println("LOOP()");
        Serial.println();

        Serial.println("----- a1.debug -----");
        Serial.println("Expected: Hello");
        Serial.print("Actual: "); a1.debug();
        Serial.println();

        Serial.println("----- b1.doStuffWithAlpha(0) ------");
        Serial.println("Expected: Hello");
        Serial.print("Actual: "); b1.doStuffWithAlpha(0);
        Serial.println();

        Serial.println("----- a2.debug -----");
        Serial.println("Expected: Goodbye");
        Serial.print("Actual:   "); a2.debug();
        Serial.println();

        Serial.println("----- b1.doStuffWithAlpha(1) ------");
        Serial.println("Expected: Goodbye");
        Serial.print("Actual:   "); b1.doStuffWithAlpha(1);
        Serial.println();

        delay(10000);
    }

This sketch is quite straight-forward. It creates 2 `Alpha` objects and a `Beta` object and passes the two Alphas into Beta. The myriad `Serial.print()` statements produces the output below.

**output**

    SETUP()

    ----- a1.debug -----
    Expected: Hello
    Actual:   Hello

    ----- a2.debug -----
    Expected: Goodbye
    Actual:   Goodbye

    ----- b1.doStuffWithAlpha -----
    Expected: Hello
    Actual:   Hello

    Expected: Goodbye
    Actual:   Goodbye

    //everything is fine up to this point...

    LOOP()

    ----- a1.debug -----
    Expected: Hello
    Actual:   Hello

    ----- b1.doStuffWithAlpha(0) ------
    Expected: Hello
    Actual:   CÃoçëyc=Lä^ÜŽYw¸Nv†Ý¿  //uh oh...

    ----- a2.debug -----
    Expected: Goodbye
    Actual:   Goodbye

    ----- b1.doStuffWithAlpha(1) ------
    Expected: Goodbye
    Actual:   ÿß/ï //uh oh again...

Everything works as expected when running `a1` or `a2.debug()` or `b1.doStuffWithAlpha()` in the `setup()` function.

The result of `a1.debug()` and `a2.debug()` works as expected in the `loop()` function.

The issue, as you can see, is when running `b1.doStuffWithAlpha(0)` or `b1.doStuffWithAlpha(1)`. The output is usually junk, which suggests to me the pointer has been mangled and points in the wrong place.

I don't understand what is happening between the transition from `setup()` to `loop()`. At first I thought the issue was the "Hello" and "Goodbye" strings going out of scope, but `Alpha::setAlpha()` makes a copy of the C-string. Also, accessing `Alpha::debug()` in `loop()` works, as shown above.

I have tried variations on the above code, such as using a struct or an int for `alpha` instead of a C-string and the results are the same: Mangled values.

Have I done something obviously silly that my scant C++ experience hasn't picked up on, or is there some fundamental Arduino shenanigans at play?

body: Problem is local shadow variable `b1` in setup() function declared as `Beta b1 = Beta();`. In `loop()` is considered uninitialized global variable `b1`.


message:
Measurement of pulse duration greater than 3mins

Is it possible to measure the width of a pulse which is longer than 3 minutes? The pulseIn function can only measure duration of maximum 3 minutes accurately.
I've tried using interrupts but haven't come up with a correct solution yet.

I'm measuring the duration of pulse (HIGH) generated by AND gate connected to the outputs of two comparators. AND gate output voltage is around **4.9 volts**.

Any logical solution or idea would be appreciated. Thanks!

body:
The concept is actually quite simple.

You need to record the time when the signal goes high, and record the time when it goes low. The pulse width is the difference between the two times.

Yes, you can do it with interrupts, but you don't need to if you're not trying to do anything else at the same time.

A simple polling code could be something like this:

    while (digitalRead(pin) == LOW); // Wait for input to go high
    unsigned long startTime = millis(); // Record start time
    while (digitalRead(pin) == HIGH); // Wait for input to go low
    unsigned long endTime = millis(); // Record end time
    unsigned long pulseDuration = endTime - startTime;

You basically sit doing nothing until the leading rising edge of your pulse.  You then record the time, and again sit doing nothing - this time while looking for the trailing falling edge of the pulse.  Then record the end time and subtract the two.


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

Here is some code I used to time a ball running down a ramp:

    const byte LED = 12;
    const byte photoTransistor = 2;

    unsigned long startTime;
    volatile unsigned long elapsedTime;
    volatile boolean done;

    void ballPasses ()
    {
      // if high, start timing
      if (digitalRead (photoTransistor) == HIGH)
        {
        startTime = micros ();
        }
      else
        {
        elapsedTime = micros () - startTime;
        done = true;
        }

      digitalWrite (LED, !digitalRead (LED));
    }

    void setup ()
    {
      Serial.begin (115200);
      Serial.println ("Timer sketch started.");
      pinMode (LED, OUTPUT);
      attachInterrupt (0, ballPasses, CHANGE);
    }

    void loop ()
      {
      if (!done)
        return;

      Serial.print ("Time taken = ");
      Serial.print (elapsedTime);
      Serial.println (" uS");
      done = false;
      }

Using `micros()` here is probably overkill, but that should be good for an interval up to 71 minutes.


message:
How does Yun identify itself to Windows?

When I plug in my Yun, Windows pops up a box saying `Windows needs to install driver software for your Arduino Yun`.

What does Windows use to identify my device as an Arduino Yun? Is it written in a file somewhere, so I could for example, remove that driver prompt, or change it to `Windows needs to install driver software for your Foo Bar?`

body:
It is written in what is called the *USB String Descriptor*.  I don't have my Yun to hand right now (it's acting as a wireless bridge temporarily), but all USB devices have these *USB String Descriptors*.  Here's an example for the Leonardo (which you can easily inspect on Linux):

    $ sudo lsusb -v -d 2341:0036

    Bus 001 Device 015: ID 2341:0036 Arduino SA
    Device Descriptor:
      bLength                18
      bDescriptorType         1
      bcdUSB               1.10
      bDeviceClass            2 Communications
      bDeviceSubClass         0
      bDeviceProtocol         0
      bMaxPacketSize0         8
      idVendor           0x2341 Arduino SA
      idProduct          0x0036
      bcdDevice            0.01
      iManufacturer           2 Arduino LLC      <<== String descriptor ID 2
      iProduct                1 Arduino Leonardo <<== String descriptor ID 1
      iSerial                 0
      ... etc ...

Internally the strings are stored as an indexed table - there's two there, ID 1 and ID 2.  The *Device Descriptor* then has a couple of bytes in it that says "The manufacturer is string ID 2, and the product name is string ID 1".  The operating system then requests those string descriptors so it can display the friendly message for you.

If you want to change that name you basically have to both re-program the bootloader (which has the USB descriptors when in program upload mode) and the Arduino core (that has the string descriptors programmed into it).


message:
Can I stack an Arduino to another Arduino?

I'm using Arduino clones, which have pin headers the same as Arduino's shields have (with extended "legs" below the board to be stackable).

Can I stack my Arduino (Mega) clone to an Arduino (Uno) clone without destroying both? Wouldn't it explode or something?

Just asking before trying it.

Thanks!

body:
No, I don't think that is a good idea. You would basically short the pins of each of them together, plus their power supplies. The only way it might conceivably work was if one Arduino had all its pins as inputs and the other as outputs, otherwise they would be "fighting" each other to drive a pin high or low. You would also have connected together their Reset pins so they would both reset at the same time. And doing serial comms would be problematic as the serial ports would be fighting each other.

---

Also, uploading sketches would be virtually impossible, as when you started the upload, both would be reset, both bootloaders would try to read the incoming data, and reply at the same time. Plus, the Mega and the Uno have different uploading protocols. So at the very least, you would have to separate them every time you uploaded new code, to either one.


message:
Arduino ethernet shield not getting correct IP

I have a very simple sketch which I'm using to (try to) prove out an ethernet shield. The complete sketch is below. When I upload the sketch, the IP address that the shield gets is 0.140.140.140, which is incorrect. I just received the shield today from SparkFun, it is [this one][1]. Am I doing something wrong, or is my shield  and/or Arduino broken? The Arduino is an Uno R3. The sketch works otherwise (the LED blinks as expected).

Sketch:

    #include <SPI.h>
    #include <Ethernet.h>

    // Network information
    byte mac[] = {0xDE, 0xAD, 0xBE, 0xCF, 0xFE, 0xEE };
    byte ip[] = { 172, 31, 42, 201 };

    void setup() {
      pinMode(4,OUTPUT);
      digitalWrite(4, HIGH);
      delay(1);

      // initialize serial:
      Serial.begin(9600);
      Serial.println("Starting sketch...");
      Ethernet.begin(mac,ip);
      delay(1000);
      Serial.println(Ethernet.localIP());
      Serial.println("Setup done.");
      pinMode(13, OUTPUT);
    }

    void loop() {
      digitalWrite(13,HIGH);
      delay(1000);
      digitalWrite(13,LOW);
      delay(1000);
      Serial.println(Ethernet.localIP());
    }

  [1]: https://www.sparkfun.com/products/11166

body:
The sketch you have written works perfectly with a cheap Ethernet Shield clone from eBay.  Those (and the older Arduino Ethernet Shields) use the Wiznet W5100 chip.

The new shields, of which you have one, use the newer, more powerful, Wiznet W5500 chip.

You can't use the old Ethernet library with the new Wiznet W5500 chip.  It doesn't work.

You have to use the "Ethernet 2" library as described here:

* http://labs.arduino.org/Ethernet+2+Library

> Note: this library is used to work with the new Ethernet shield (version 2) and Leonardo Eth that uses a new Controller W5500.

That page is linked from the product page you link to above.  If you had read the product page you would already know this.


message:
Unexpected output form Serial.println

So I have a teensy and an arduino uno connected together via I2C, however some very odd behavior is occurring, when monitoring the serial connection for shorter data sent over I2C I receive the expected serial output. However if the data is longer I only receive 2 characters. More strange even is that if I send the longer data again I receive none, but if I send the shorter data I receive the expected output. After sending the shorter data again sending the longer data will result is the odd 2 characters.

Uno code
     //#include <DmxSimple.h>

     #include <Wire.h>

    boolean pinout = 0;
    byte current[512];

    void setup() {
      // put your setup code here, to run once:
      Wire.begin(1);
      Serial.begin(115200);
      Wire.onReceive(data);
      //DmxSimple.usePin(3);
      //DmxSimple.maxChannel(30);
    }

    void loop() {

    }

    void data(int numBytes){
    //Serial.println("DATA RECIVED");

     delay(500);

     char input[20];
     int pos = 0;

     while(Wire.available()){
       input[pos++] = Wire.read();
      }
      input[pos++] = '\0';

      Serial.print("Recived \"");
      Serial.print(input);
      Serial.println("\"");

      char* next = strchr(input, ',');
      while(next != 0){
      *next = 0;
      next++;
      char* splitter = strchr(next, ':');
      if(splitter != 0){
      *splitter = 0;
      splitter++;
      int channel = atoi(next);
      int value = atoi(splitter);
          //DmxSimple.write(channel,value);
          Serial.print(channel); Serial.print(":"); Serial.println(value);
        }
      }
    }

Teensy code

                #include <i2c_t3.h>
                //#include <ArduinoPebbleSerial.h>

         /*
        static const uint16_t SERVICE_ID = 0x1001;
    static const uint16_t UPTIME_ATTRIBUTE_ID = 0x0002;
    static const size_t UPTIME_ATTRIBUTE_LENGTH = 4;
    static const uint16_t LAMP_ATTRIBUTE_ID = 0x0003;
    static const size_t LAMP_ATTRIBUTE_LENGTH = 20;

    static const uint16_t SERVICES[] = {SERVICE_ID};
    static const uint8_t NUM_SERVICES = 1;

    static const uint8_t PEBBLE_DATA_PIN = 1;
    static uint8_t buffer[GET_PAYLOAD_BUFFER_SIZE(4)];

    typedef struct __attribute__((packed)){
      uint8_t channel;
      uint8_t value;
    } DMXP;*/

    void setup() {
      pinMode(LED_BUILTIN, OUTPUT);
      Wire.begin();
      Serial.begin(9600);
      /*
     #if defined(__MK20DX256__) || defined(__MK20DX128__)
      // Teensy 3.0/3.1 uses hardware serial mode (pins 0/1) with RX/TX shorted together
     ArduinoPebbleSerial::begin_hardware(buffer, sizeof(buffer), Baud57600, SERVICES, NUM_SERVICES);
    #elif defined(__AVR_ATmega32U4__)
     // Teensy 2.0 uses the one-wire software serial mode
     ArduinoPebbleSerial::begin_software(PEBBLE_DATA_PIN, buffer, sizeof(buffer), Baud57600, SERVICES,
                                      NUM_SERVICES);
    #else
    #error "This example will only work for the Teensy 2.0, 3.0, or 3.1 boards"
    #endif
    */
    /*for(int i = 1; i < 8; i++){
      sendChannel(i,0);
    }
    */

    }

    /*
    void handle_dmx_request(RequestType type, size_t length) {
    if (type != RequestTypeWrite) {
      return;
    }

    DMXP cmd = *(DMXP*)buffer;
    sendChannel(cmd.channel, cmd.value);

    // ACK that the write request was received
    ArduinoPebbleSerial::write(true, NULL, 0);
    ArduinoPebbleSerial::notify(SERVICE_ID, UPTIME_ATTRIBUTE_ID);
    }
    */

    void loop() {

      /*
      if (ArduinoPebbleSerial::is_connected()) {
      digitalWrite(13,true);
    } else {
      digitalWrite(13,false);
    }

    uint16_t service_id;
    uint16_t attribute_id;
    size_t length;
    RequestType type;
    if (ArduinoPebbleSerial::feed(&service_id, &attribute_id, &length, &type)) {
      // process the request
      if (service_id == SERVICE_ID) {
        switch (attribute_id) {
          case LAMP_ATTRIBUTE_ID:
            handle_dmx_request(type, length);
            break;
          default:
            break;
        }
      }
    }
    */

    }

    void serialEvent(){
      if(Serial.read() == 't'){
      digitalWrite(13,true);
      Serial.println("Starting Controller");
      int chans[8] = {1,2,3,4,5,6,7,8};
      int vals[8] = {2,4,6,8,16,32,64,128};
      sendChannel(chans,vals,4);
      } else {
        sendChannel(1,1);
      }
      while(Serial.available()){
        Serial.println(Serial.read());
      }
    }

    void sendChannel(int chan, int val){
     char chno[8];
      itoa(chan,chno,10);
      char vano[8];
     itoa(val,vano,10);
     char message[20];
     int messagei = 0;
     for(int i = 0; i < 7; i++){
     if(chno[i] == '\0'){
       break;
      }
     message[messagei++] = chno[i];
    }
     message[messagei++] = ':';
     for(int i = 0;i < 7; i++){
     if(vano[i] == '\0'){
      break;
     }
     message[messagei++] = vano[i];
     }
      //message[messagei++] = '\n';
    //message[messagei++] = '\r';
    message[messagei++] = '\0';

    Serial.println(message);

    Wire.beginTransmission(1);
    Wire.write(message);
    Wire.endTransmission();
    }

    void sendChannel(int chan[], int val[], int num){
     char message[20*num + 1];
     int at = 0;

     for(int i = 0; i < num; i++){
    char chno[8];
    itoa(chan[i],chno,10);
    char vano[8];
    itoa(val[i],vano,10);
    for(int i = 0; i < 7; i++){
      if(chno[i] == '\0'){
        break;
      }
      message[at++] = chno[i];
    }
    message[at++] = ':';
    for(int i = 0;i < 7; i++){
      if(vano[i] == '\0'){
        break;
      }
      message[at++] = vano[i];
      }
      if(i+1!=num){
      message[at++] = ',';
      } else {
      message[at++] = 0;
     }
     }

     char finalMessage[at+1];
     for(int i = 0; i <= at; i++){
    finalMessage[i] = message[i];
     }

     Serial.println(finalMessage);

    Wire.beginTransmission(1);
    Wire.write(message);
    Wire.endTransmission();

    }

(If modifying the teensy code to run on a second arduino replace the line `#include <i2c_t3.h>` with `#include <Wire.h>` no other changes should be necessary)

To use the Teensy code open a serial terminal to access it, press 't' to send a long packet, or any other character to send a shorter one.

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

Your code which I will reproduce here as it wasn't in the question has a major issue:

    //#include <DmxSimple.h>

    #include <Wire.h>

    boolean pinout = 0;
    byte current[512];

    void setup() {
      // put your setup code here, to run once:
      Wire.begin(1);
      Serial.begin(115200);
      Wire.onReceive(data);
      //DmxSimple.usePin(3);
      //DmxSimple.maxChannel(30);
    }

    void loop() {

    }

    void data(int numBytes){
      //Serial.println("DATA RECIVED");

      delay(500);

      char input[20];
      int pos = 0;

      while(Wire.available()){
        input[pos++] = Wire.read();
      }
      input[pos++] = '\0';

      Serial.print("Recived \"");
      Serial.print(input);
      Serial.println("\"");

      char* next = strchr(input, ',');
      while(next != 0){
       *next = 0;
       next++;
        char* splitter = strchr(next, ':');
        if(splitter != 0){
          *splitter = 0;      Wire.onReceive(data);
      //DmxSimple.usePin(3);
      //DmxSimple.maxChannel(30);
    }

---

Your function `data` does `Serial.print`s. It is called as an interrupt service routine effectively, and thus should not do serial prints:

          Wire.onReceive(data);
        }

        void loop() {

        }

        void data(int numBytes){

    ...

          Serial.print("Recived \"");
          Serial.print(input);
          Serial.println("\"");

---

> More strange even is that if I send the longer data again I receive none, ...

Yep, that will definitely happen. The serial printing "blocks" if you print a lot, and thus the code will hang indefinitely.

---

      delay(500);

You definitely should not use `delay` in an interrupt routine. It will almost certainly hang because the timer interrupts which are needed for `delay` to work are not being serviced.

---

      Wire.begin(1);

You should not be choosing to use I2C address 1. It is reserved. See:

[7-bit, 8-bit, and 10-bit I2C Slave Addressing](http://www.totalphase.com/support/articles/200349176) and [I2C specification (pdf)](http://www.nxp.com/documents/user_manual/UM10204.pdf)

<!-- language-all: lang-none -->

    Slave Address  R/W Bit  Description
    000 0000  0  General call address
    000 0000  1  START byte(1)
    000 0001  X  CBUS address(2)
    000 0010  X  Reserved for different bus format (3)
    000 0011  X  Reserved for future purposes
    000 01XX  X  Hs-mode master code
    111 10XX  X  10-bit slave addressing
    111 11XX  X  Reserved for future purposes

> (1) No device is allowed to acknowledge at the reception of the START byte.
>
> (2) The CBUS address has been reserved to enable the inter-mixing of CBUS compatible and I2C-bus compatible devices in the same system. I2C-bus compatible devices are not allowed to respond on reception of this address.
>
> (3) The address reserved for a different bus format is included to enable I2C and other protocols to be mixed. Only I2C-bus compatible devices that can work with such formats and protocols are allowed to respond to this address.


message:
Unable to set up Intel Edison on Windows

I am new to hobby electronics and have hit a dead end with my Intel Edison (which hopefully will not join the pile of useless components I have wasted my money on), and would appreciate some help with the setup procedure. The main problem is that I cannot connect to my Edison via the middle (lets call it "A") micro-USB port in order to get it into a working condition.

My objective is to connect to it's build-in Linux via SSH with the USB cables connected after installing the latest flash image.

I am using an Edison with an Arduino breakout board.

Here is the sequence of steps I followed:

1. I connected a 12V 2.6A AC to DC adapter to power the board. (Via the barrel connector). The green light came on to indicate it is powered.
2. I connected the "A" micro-USB port (i.e. not the one on the edge) to my computer.

At this point I could access the drive through Windows Explorer, however this changed when I executed the next step:

3. I installed the software from step 2 at https://software.intel.com/en-us/iot/library/edison-getting-started.
4. Something went wrong during the subsequent installation process. I don't know what.

At this point I could no longer access the drive. It would only appear as an "Unknown device" in Windows Device Manager. In order to try and fix this I gave up on the option where it is mounted as a Windows Drive.

5. I connected to the micro-USB port at the edge of the Arduino board and disconnected A.
6. I went to Windows Device Manager and found the connected device on COM6
7. I installed Putty and connected to COM6 with a baud of 115200.
8. The console showed a blank screen with a green cursor in the top left.
9. I waited 30 seconds for it to boot.
10. I hit Cntrl+C because I still saw the same screen from step 9.

I then saw this on the console:

<pre>

Unknown boot mode: boot
Saving Environment to MMC...
Writing to MMC(0)... done
Resetting to default boot mode and reboot...
resetting ...

******************************
PSH KERNEL VERSION: b0182b2b
                WR: 20104000
******************************

SCU IPC: 0x800000d0  0xfffce92c

PSH miaHOB version: TNG.B0.VVBD.0000000c

microkernel built 11:24:08 Feb  5 2015

******* PSH loader *******
PCM page cache size = 192 KB
Cache Constraint = 0 Pages
Arming IPC driver ..
Adding page store pool ..
PagestoreAddr(IMR Start Address) = 0x04899000
pageStoreSize(IMR Size)          = 0x00080000

*** Ready to receive application ***

U-Boot 2014.04 (Jun 19 2015 - 12:05:55)

       Watchdog enabled
DRAM:  980.6 MiB
MMC:   tangier_sdhci: 0
In:    serial
Out:   serial
Err:   serial
Hit any key to stop autoboot:  0
Target:ifwi
Partitioning already done...
Partitioning already done...
Saving Environment to MMC...
Writing to redundant MMC(0)... done
GADGET DRIVER: usb_dnl_dfu

</pre>

I have no idea what to do next.

body:
I fixed it by following these steps (through trial and error, I don't really understand what I did but it works ...)

I am using Windows 8.1, 64 bit edition.

1. Download the Edison firmware from https://software.intel.com/en-us/iot/hardware/edison/downloads. For me it was http://downloadmirror.intel.com/25028/eng/edison-image-ww25.5-15.zip.
2. Extract the zip file.
3. Start the Windows Command Prompt as Administrator.
4. The extracted archive should contain a file called "flashall.bat". Change to the directory containing the file.
5. Connect all micro-USB ports and the barrel connector. At this point Windows did not recognize the Edison as a flash disk. This is part of what I was fixing.
6. Follow the steps in my question until the output on the console (also from my question) appears.
5. Run "flashall --recovery"
6. Run "flashall". When "Please plug and reboot the board" appears, disconnect the A (or middle) USB port and the barrel connector for the power. At this point everything is switched off. Then reconnect A and the barrel connector to reboot the board.
7. Wait about 5 minutes for the rest of the process to run automatically.

At this point everything should work again.

You should see this on the command line in Windows:

<pre>
C:\Users\_\Desktop\edison-image-ww25.5-15>flashall --recovery
Starting Recovery mode
Please plug and reboot the board
Flashing IFWI
!!! You should install xfstk tools, please visit http://xfstk.sourceforge.net/

C:\Users\_\Desktop\edison-image-ww25.5-15>flashall
Using U-boot target: edison-blankrndis
Now waiting for dfu device 8087:0a99
Please plug and reboot the board
Dfu device found
Flashing IFWI
Download        [=========================] 100%      4194304 bytes
Download done.
Download        [=========================] 100%      4194304 bytes
Download done.
Flashing U-Boot
Download        [=========================] 100%       237568 bytes
Download done.
Flashing U-Boot Environment
Download        [=========================] 100%        65536 bytes
Download done.
Flashing U-Boot Environment Backup
Download        [=========================] 100%        65536 bytes
Download done.
Rebooting to apply partiton changes
Dfu device found
Flashing boot partition (kernel)
Download        [=========================] 100%      6111232 bytes
Download done.
Flashing rootfs, (it can take up to 5 minutes... Please be patient)
Download        [=========================] 100%    566330368 bytes
Download done.
Rebooting
U-boot & Kernel System Flash Success...
Your board needs to reboot to complete the flashing procedure, please do not unplug it for 2 minutes.

C:\Users\_\Desktop\edison-image-ww25.5-15>
</pre>


message:
Arduino Pin won't go LOW

I have something strange going on with an output. When the following code is called the LED goes on, but it stays on, there is no blinking. If I comment out the set HIGH statement the LED never comes on (as expected).

    #define devicePin 10

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

    void loop() {
        digitalWrite(devicePin, HIGH);
        delay(2000);
        digitalWrite(devicePin, LOW);
    }

Could I have damaged the board in some way?

body:
After you drive the pin low, you immediately go to the beginning of the loop and set the pin high (if you have an oscilloscope, you might see a very short downward pulse).
So, add another delay after `digitalWrite(devicePin, LOW)`.


body:
you forgot to add a delay after digitalWrite(devicePin, LOW);

    #define devicePin 10

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

    void loop() {
        digitalWrite(devicePin, HIGH);
        delay(2000);
        digitalWrite(devicePin, LOW);
        delay(2000);
    }


body:
Yes, the pin is going low. I tested it for you:

[![Pin 10 going low][1]][1]

It went low for 6 µs, once every 2 seconds. :)

---

Overall, this is the effect:

[![Pin 10 mainly high][2]][2]

As you can see, high for most of the time.

  [1]: https://i.stack.imgur.com/qDZxx.png
  [2]: https://i.stack.imgur.com/3QuPS.png


message:
Consulting and inserting a string into an array if it doesn't exist (Arduino IDE) 1

Sorry that I repeat my question, I can't enter to my user...

In the project I'm doing, I connect an arduino mega with ethernet and Post some Strings to the server. The arduino mega has a receiver(315MHz). I have some arduinos nano connected with PIR sensors that sends a some int with transmitters (315MHz). What I want to do is a list in my arduino mega that stores the values sent by the arduinos nanos to use them to my server (using POST). my question is the following:

If I had an empty array, what I would like to do is

    listOfSensors[]={}

    void funtion (String sensor){
        if (sensor is inside listOfSensors){
             //dont do anything
        }
        else {
             add sensor to listOfSensors
        }

I have been looking for hours, but I haven't found anything so far... Anyone has any idea? Thanks!!

body:
In C there is no such thing as an "empty array".  All arrays have a finite pre-defined size.

    String sensors[10]; // Room for up to 10 sensors

The usual way of storing an unknown number of entries that will be added to "as and when" is to use a *linked list* or *doubly-linked list*.

A *linked list* is a list of items where each item also contains a pointer to say where the next item in the list is located.

Also you shouldn't use the String class as it is not good when working with linked lists (or in general - stick to C strings).

**Warning: linked lists aren't for the faint of heart.**

First you would define a *struct* to store the data you want in the linked list:

    struct sensor {
        char *name;
        int currentValue;
        struct sensor *next;
    };

That would store the name of the sensor ("name"), the current value from the sensor ("currentValue") and also contains a pointer ("*next") to the next entry in the list.  That last bit is the most important.

Now you create a "head" pointer variable to start your list off:

    struct sensor *mySensors = NULL;

That starts out as *NULL* to say "This variable has nothing in it at the moment".

Now that was the easy part.  The hard part is adding entries to the list...

A couple of *helper* functions can be of use here.  Let's start by defining a function that will look for a specific entry by name in the list:

    struct sensor *findSensor(const char *name) {
        for (struct sensor *scan = mySensors; *scan; scan = scan->next) {
            if (strcmp(scan->name , name) == 0) {
                return scan;
            }
        }
        return NULL;
    }

That will start off with a pointer variable *scan* pointing to the first entry in the linked list (mySensors).  While it's pointing to a valid entry (not NULL) compare the name to the given string and if they match then return the entry we are pointing to.  Next point to whatever the "next" pointer is pointing to, so you move down the list.

Now to add a sensor:

    struct sensor *addSensor(const char *name, int value) {
        // First look to see if it exists:
        struct sensor existing = findSensor(name);
        if (existing != NULL) { // We found it
            existing->currentValue = value; // Update the value
            return existing;
        }
        // We haven't got it in our list, so create a new entry:
        struct sensor newsensor = (struct sensor *)malloc(sizeof(struct sensor));
        // And fill in the data:
        newsensor->name = strdup(name); // Create a COPY of the string
        newsensor->currentValue = value; // Store the value
        newsensor->next = NULL;
        // IMPORTANT: The new entry must point to NULL to mark the end of the list:
        newsensor->next = NULL;

        // Now where to add it in the list? Is there even a list?
        if (mySensors == NULL) {
            // No? Then we just make our new entry the head of the list:
            mySensors = newsensor;
            return newsensor;
        }
        // Otherwise we need to scan through the whole list to find
        // where the tail of the list is:

        struct sensor *scan = mySensors;
        // While the current entry points to a valid next entry
        while (scan->next) {
            // move on to that next entry
            scan = scan->next;
        }
        // There must be no valid next entry now (scan->next == NULL), so
        //  add our new sensor as the next valid entry:
        scan->next = newsensor;
        return newsensor;
    }

Removing a sensor from the list is a much more involved process (even more than adding a sensor).  You need to "splice" the list around the deleted entry.  I'll add detail on that if you need it, but by the sound of things you won't be removing entries, only adding them.

The routines shown there (I haven't actually tested them, but it is standard code I write all the time) aren't as efficient as they could be.  If you are adding and removing entries all the time and you end up with quite a large list it can take longer and longer to scan right through the list to find the last entry to add to.  If that is the case you can maintain a "tail" pointer that you always update to point to the last added entry whenever you add one.  That can then be used to rapidly add to the end of the list without having to scan through the whole list every time.

Another optimisation if you do a lot of scanning around within a list is to make a *doubly linked list*.  This is just like the linked list above except it works in both directions.  Not only do you store a *next* pointer, you also store a *previous* pointer.  You can now scan in either direction - from head to tail or from tail to head, or hopping around at will inside the list.  That is especially useful if you want to do things like ordering the list alphabetically.


body:
If you only need to add items of a fixed size to your sensor list (i.e. you don't need to delete items or sort them), you can use an uninitialized array large enough for the maximum number of items it will need to hold:

    #define MAXSENSORS 30               // max sensor count
    #define SNAMELEN 12                 // max sensor name length

    struct sensorData {
        char sname[SNAMELEN+1];
        uint16_t svalue;
    };                                  // defines data for 1 sensor

    uint8_t sensorCount = 0;
    struct sensorData listOfSensors[MAXSENSORS]={0}; // array of sensor data, initialized to 0, 0, ...

You'll also need an unsigned int (perhaps only a byte) to keep track of the count of items in the array, which you'll increment every time you add another sensor (up to the maximum number).

I think this is what you meant by "empty array". You would add your next sensor data at `listOfSensors[i]`, then increment i. Likewise, you would search for a sensor in the array from `listOfSensors[0]` to `listOfSensors[i-1]`.


message:
Convert the Serial.Println to string

I'm working with VirtualWire and I'm trying to get a string value out of the Serial.println in the loop. I've tried create a string and add the message[i] , but surprisingly message[i] becomes an int when added. Serial.println outputs the string correctly, but the string that I get from message[i] is just numbers...

    #include <VirtualWire.h>
    byte message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages
    byte messageLength = VW_MAX_MESSAGE_LEN; // the size of the message
    String sensorname;
    void setup(){
      Serial.begin(9600);
      Serial.println("Device is ready");
      // Initialize the IO and ISR
      vw_setup(2000); // Bits per sec
      vw_rx_start(); // Start the receiver
      }
    void loop(){

      if (vw_get_message(message, &messageLength)){
        Serial.print("Received: ");
        for (int i = 0; i < messageLength; i++){
          Serial.write(message[i]);
          sensorname += message[i];
          }
          Serial.println();
          Serial.pintln("Name of sensor: " + sensorname);
          sensorname="";  //Reestart the string
          }
    }

I'm quite new with VirtualWire so I don't know if there is command to get the message and pass it directly to string...Any help will be appreciated!

**EDIT**
I think I dind't express myself well. In my original question I didn't add the String sensor name

The Response I get in the Serial is the following:

    Device is ready
    SensorA
    Name of sensor: 8310111011511111465

My aim is to instead of having as sensorname=8310111011511111465, have sensorname=SensorA

body:
Those numbers are the numerical ASCII representation of the characters.

    83 = S
    101 = e
    110 = n
    ... etc ...

(Find the whole list here: http://www.asciitable.com/)

The reason you are ending up with numbers is because of the *type* of variable you are receiving the data into - a *byte*.

A *byte* stores a number between 0 and 255.  When you add that *byte* to a *String* the compiler assumes you want to append a number, since it is a numerical type that you are using.

If you instead tell it to use a *char* type then the compiler should realise "Ah, this is the numeric representation of a character - I will add the character instead".

You can either change the whole array type:

    char message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages

Or *cast* the variable to be the right type when you append it:

      sensorname += (char)message[i];

Or better still, don't use the String class since it is really too heavyweight and prone to memory issues for use on a little microcontroller.  Stick to C strings. They take a little more getting used to, but are so much more microcontroller friendly.


message:
How does arduino fetch instruction string from sms and execute?

I am working on a project in which i have to send commands using sms (GSM shield) to the arduino uno to control dc motor. What i want to know is that how can i define the instruction strings that i can send in form of sms and arduino uno reads it and executes it.

P.S. I am a total beginner at arduino coding so please help me out.

body:
Your GSM shield will receive the SMS which your Arduino code can retrieve as a string of characters (that description hides a mountain of detail, most of which you won't need to know). It doesn't care what the content of the SMS message is.

Your Arduino code will have to translate from the message text to motor-control commands so you want some text commands that will be easy to parse, but not so trivial that any random message might wrongly be interpreted as legitimate commands.

The digit pair "15" might command motor 1 to speed 5. But you wouldn't want any message with a couple of digits in it to change a motor. (You didn't say you had multiple motors, and if not you can leave that part out).

Let's make the message distinctive enough that it's unlikely to appear in some other context, yet simple enough to distinguish as legitimate. It would be nice if it's simple to thumb-type, too!

"motor,1,5" could convey the same information as the "15" in our first example, doesn't limit you one-digit values, isn't likely to appear in a "Hey Dude, lunch at 12:15?" type of conversation, is easy to parse and isn't too long to type on a tiny keyboard. You could extend it later, so "motor,1,+2" could mean to increase motor 1's speed by two units, "motor,1,off" could mean power it down (not just zero speed), and "motor,all,off", well, that's probably obvious.

Look up the function `sscanf()` [oops: not sprintf()] for one way to parse the incoming strings and collect their data.

Update: sscanf() does the reverse of sprintf(): It reads a string, collects values from it, and assigns them to variables. Search sscanf on the web for a description of its use.
<br>Here is a sample program that reads a few possible SMS messages, checks whether they are motor commands (according to my simple example SMS above), and if it is, assigns the contained values to some variables in your program. You can see by the return values of sscanf() whether and how many conversions it made from each message, thus your code can tell whether a received SMS looks like a motor command, as well as what the command values are:

    /*
     * sscanf example - Uses sscanf to test and collect data from a
     * a command string.
     */

    #include <WProgram.h>

    void test_sscanf(const char *sms);

    // Sample of SMS messages to test whether our sscanf() format string
    // can recognize good ones and reject bad ones. Experiment by adding
    // ones of your own:
    const char *SMS[] =
    {
       "motor,1,5",
       "Hello World,3,2",
       "motor 123 456",
       "moto, 7, 13",
       "motorized, 4, 11"
    };

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

       delay(1000);  // delay for user to launch a terminal (if you're quick)

       // Test each SMS example in the SMS array
       for( uint8_t s = 0; s < sizeof(SMS)/sizeof(char *); ++s ){
          test_sscanf(SMS[s]); // test one SMS string
       }
    }

    void loop() {
       ;   // nothing to do here
    }

    // Tests a sample SMS, prints the number of variables it assigned, and what
    // their values were. '0' means it didn't assign any, probably because the
    // command-word failed to match.
    void test_sscanf(const char *sms)
    {
       int16_t assigned, values[2];

       // Print the SMS and convert it.
       Serial.print("\nSMS: \""); Serial.print(sms); Serial.println("\"");
       assigned = sscanf(sms, "motor,%d,%d", &values[0], &values[1]);

       // Display the results
       Serial.print(assigned);  Serial.println(" values assigned"); // How many values? A good command has 2.
       if( assigned > 0 ){
          for( uint8_t i = 0; i < assigned; ++i){
      Serial.print("value["); Serial.print(i+1); Serial.print("] = "); // print each assigned value
      Serial.println(values[i]);
          }
       }
    }


message:
Simple Arduino Code Not Working

When I upload this code LED at pin 13 goes HIGH and that's it. My goal is to make it blink in the order specified in the array. What am I doing wrong?

    int Array[] = {1,1,1,0,1,0,0,0,1,0,1,0,1,1,0,0,1,0,1,0,1,1,0,0};
    int Data = 13;
    int i = 0;

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

    void loop() {
        int x = Array[i];
        delay(200);
        digitalWrite(Data, x);
        i = i+1;
        if (i==23) {
            i=0;
        }
    }

body:
What you're doing wrong is living your life at a normal speed.

The LED will be blinking, but so fast you can't see it change.

Without adding some delays in there you will just see the LED light up.


message:
Why doesn't the LED turn on in this circuit?

I'm experimenting with buttons and LEDs and I would like my code to change a LED's brightness once a button is pressed. I connect the LED to the PWD digital pin.

My circuit looks like this one:

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

This is the code I'm using:

    int switchPin = 8;
    int ledPin = 11;
    boolean lastButton = LOW;
    boolean currentButton = LOW;
    int ledLevel = 0;

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

    boolean debounce(boolean last) {
        boolean current = digitalRead(switchPin);
        if (last != current) {
            delay(5);
            current = digitalRead(switchPin);
        }
    return current;
    }

    void loop() {
        currentButton = debounce(lastButton);
        if (lastButton == LOW && currentButton == HIGH) {
            ledLevel = ledLevel + 51;
        }
        lastButton = currentButton;

        if (ledLevel > 255) ledLevel = 0;
        analogWrite(ledPin, ledLevel);
    }

Though, the LED never turns on, but the light on the Arduino is on. I made sure the leads of the LED were in the right spot. Why doesn't the LED turn on?

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

body: Because you don't actually *have* a circuit?  One side of the LED doesn't connect to anything.


message:
Not waking up more than once?

I'm trying the following code on an Uno. I'm pulling the high side of a pull down 10K resistor to 5V, but it can only be woken once. Just once. Does anyone know why this might be the case?

It works fine if I use `LOW` for `attachInterrupt` along with a pull-up resistor though. Just not with `RISING` and a pull-down.

    #include <avr/sleep.h>
    #include <avr/power.h>

    int pin2 = 2;

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

      /* Setup the pin direction. */
      pinMode(pin2, INPUT);

      Serial.println("Initialisation complete.");

    }

    void pin2Interrupt(void)
    {
      /* This will bring us back from sleep. */

      /* We detach the interrupt to stop it from
       * continuously firing while the interrupt pin
       * is high.
       */
      detachInterrupt(digitalPinToInterrupt(pin2));
    }

    void enterSleep(void)
    {

      sleep_enable();

      /* Setup pin2 as an interrupt and attach handler. */
      attachInterrupt(digitalPinToInterrupt(pin2), pin2Interrupt, RISING);
      delay(100);

      set_sleep_mode(SLEEP_MODE_PWR_DOWN);

      sleep_mode();

      /* The program will continue from here. */

      /* First thing to do is disable sleep. */
      sleep_disable();
    }

    int seconds=0;
    void loop()
    {
      delay(1000);
      seconds++;

      Serial.print("Awake for ");
      Serial.print(seconds, DEC);
      Serial.println(" second");

      if(seconds >= 3)
      {
        Serial.println("Entering sleep");
        delay(200);
        seconds = 0;
        enterSleep();
      }
    }

body:
For a `RISING` interrupt you never need to disconnect the interrupt to prevent repeat triggering.

A `RISING` interrupt specifically only triggers the once when the input pin transitions from `LOW` to `HIGH` rather than all the time it's in a state like a *level* interrupt.

Attach the interrupt once in setup() and leave it alone after that.  Your interrupt handler routine can be completely empty.  It will only ever be triggered at the exact moment you press the button.  To trigger it again you will just need to press the button again.


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

Probably your switch is bouncing and giving two interrupts. The first wakens it, and the second is lying there waiting until you attach the interrupt again. Then it fires, detaches the interrupt, then you go to sleep, never to awaken.

Clear any pending interrupt **before** doing the attachInterrupt:

    EIFR = bit (INTF0);  // clear flag for interrupt 0

See [Interrupts](http://www.gammon.com.au/interrupts).

It is also wise to have interrupts off while setting up for sleep.

---

Example code:

    #include <avr/sleep.h>

    const byte LED = 13;

    // interrupt service routine in sleep mode
    void wake ()
    {
      sleep_disable ();         // first thing after waking from sleep
    }  // end of wake

    void sleepNow ()
    {
      set_sleep_mode (SLEEP_MODE_PWR_DOWN);
      noInterrupts ();          // make sure we don't get interrupted before we sleep
      sleep_enable ();          // enables the sleep bit in the mcucr register
      EIFR = bit (INTF0);       // clear flag for interrupt 0
      attachInterrupt (0, wake, RISING);  // wake up on rising edge
      interrupts ();           // interrupts allowed now, next instruction WILL be executed
      sleep_cpu ();            // here the device is put to sleep
      detachInterrupt (0);      // stop this interrupt until next time
    }  // end of sleepNow

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

    void loop ()
      {
      sleepNow ();
      digitalWrite (LED, HIGH);
      delay (1000);
      digitalWrite (LED, LOW);
      }  // end of loop

Tested and works OK.

---

Note: Since this is a rising interrupt you should have a **pull-down** resistor on the pin, and you trigger the interrupt by connecting the pin to +5 V.


message:
Can't get software serial to work

So I have two Arduinos (Arduino Nano) and I'm trying to get them to communicate via SoftwareSerial.  I have the 'sending' Arduino's D10 pin connected to the 'recieving' Arduino's D11 pin, and vice versa.  On my sending Arduino, I have the following code:

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(10, 11);

    void setup() {
      pinMode(2, OUTPUT);
      mySerial.begin(9600);
    }

    void loop() {
      if (mySerial.isListening()){
        digitalWrite(2, HIGH);
      }
      mySerial.write(5);
    }

and on my receiving Arduino, I have:

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(11, 10);

    void setup() {
      pinMode(2, OUTPUT);

      Serial.begin(9600);

      mySerial.begin(9600);
    }

    void loop() {
      mySerial.listen();
      if (mySerial.available()>0) {
        digitalWrite(2, HIGH);
        char inByte = mySerial.read();
        Serial.write(inByte);
      }
      digitalWrite(2, LOW);
    }

(with D2 being hooked up to an LED for both).

I can't get it to read anything.  Nothing seems to be available for the receiving Arduino (the LED is off).  What am I doing wrong?

body:
Sender:

    SoftwareSerial mySerial(10, 11);  // Rx, Tx

Receiver:

    SoftwareSerial mySerial(11, 10);  // Rx, Tx

> I have the 'sending' Arduino's D10 pin connected to the 'receiving' Arduino's D11 pin, and vice versa.

So you have the sending Arduino's Rx connected to the receiving Arduino's Rx. Therefore it won't work. You need to connect Rx to Tx.

---

      mySerial.listen();

You don't need that in this simple example.


message:
Storing array in PROGMEM

I have an array of a lot of numbers (1 and 0) but i can't store them since arduino does not have enough space. How can i save an array of example 00110 in PROGMEM, then read from PROGMEM and set x to be equal lets say, third int in the array?

body:
Store them with `const byte PROGMEM` with bit 0 as MSb and bit 7 as LSb per byte. E.g. 011100100101001010101011 would become `const byte[] var PROGMEM {0x72, 0x52, 0xab}`

Use the following macro to retrieve them (untested):

    #define loadbit(mem, pos) ((pgm_read_byte(&(mem[pos / 8])) >> (7 - (pos % 8))) & 0x01)

So if you had `const byte[] data PROGMEM {0x72, 0x52, 0xab};` you would call `loadbit(data, 3)` and it would return bit 3 starting with 0 on the left, i.e. `1`.

Naturally if you needed more than one bit at a time there are probably situation-specific routines that could be used, but without knowing anything about the actual program the above will work.


body:
As noted in Ignacio's answer, you can pack your bits of data into bytes and access them via `pgm_read_byte()` calls.  If (for coding convenience, not for efficiency) you prefer to pack the bits into larger units, you can use `word` and `dword` access functions, as listed in [AVR pgmspace.h](http://www.nongnu.org/avr-libc/user-manual/group__avr__pgmspace.html) documentation.  The `_near` and `_far` suffixes denote 16 or 32 bit pointers, respectively; for an Uno with its 32K flash memory, `_near` is always suitable.  See [PROGMEM documentation](https://www.arduino.cc/en/Reference/PROGMEM) at arduino.cc for further discussion.

Here's an example program that accesses and prints data from program memory in 16-bit chunks:

    void setup() {
      Serial.begin(115200);         // initialize serial port
    }
    int k=0;
    const uint16_t fnums[] PROGMEM {191, 272, 353, 434, 515, 646, 767, 888};
    void loop() {
      uint16_t b = pgm_read_word_near(fnums+k);
      Serial.print(k);  Serial.print(" ");
      Serial.print(b);  Serial.println();
      k = (k+1)%8;
      delay(1000);
    }

To pack your 4000 bits of data in the first place, write a C or Python program that runs on a host computer and writes out array definitions that you can cut and paste into a sketch.  Here's an example (in Python) that packs bits into bytes:

    data = [1,1,0,0,0,1,0,1,0,0,1,0,1,0,1,1,0,0,1,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,1,0,1,1,1,1,1,1,0,0,0,1,0,1,0,0,0,1,1,1,1,0,0,1,1,1,0,1,1,1,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,1,0,1,0,1,0,0,1,0,1,0,1,0,1,0,1,0,0,0,0,0,1,1]

    first = 1; byt = 0
    for i, b in enumerate(data):
      if i%8==0:
        if first:
           print 'const uint8_t fnums[] PROGMEM {',
           first = 0
        else:
           print '{},'.format(byt),
           byt = 0
      byt = (byt<<1) | b  # add bit into byte being built

    print byt<<(8-i%8), '};'

Here is what the program produces:

    const uint8_t fnums[] PROGMEM { 197, 43, 32, 200, 47, 197, 30, 119, 153, 37, 180, 117, 48, 218, 214, 212, 170, 262 };

If you want that code to instead pack bits into 16-bit words, change 8 to 16 in four places.  Note, the code stores bits in the “bit 0 as MSb and bit 7 as LSb” order mentioned in Ignacio's answer.  Thus, `data[0]` is stored in the high bit of `fnums[0]`, `data[8]` is stored in the high bit of `fnums[1]` , and so forth.


body:
Building on the excellent other answers by jwpat7 and
Ignacio Vazquez-Abrams, you could conceivably convert your bits into a table using Lua:

<!-- language-all: lang-lua -->

    data = { 1,1,0,0,0,1,0,1,0,0,1,0,1,0,1,1,0,0,1,0,0,0,0,0,1,1,0,0,1,
             0,0,0,0,0,1,0,1,1,1,1,1,1,0,0,0,1,0,1,0,0,0,1,1,1,1,0,0,1,
             1,1,0,1,1,1,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,1,0,1,1,0,1,0,
             0,0,1,1,1,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,1,1,0,1,
             0,1,1,0,1,1,0,1,0,1,0,0,1,0,1,0,1,0,1,0,1,0,0,0,0,0,1,1 }

    output = 0
    bit = 0

    for _, num in ipairs (data) do
      assert (num == 0 or num == 1, "Number must be 0 or 1")
      output = (output * 2) + num
      bit = bit + 1
      if bit >= 8 then
        io.write (output .. ", ")
        output = 0
        bit = 0
      end -- if
    end --for

    print ""

<!-- language-all: lang-none -->

Output from above:

    197, 43, 32, 200, 47, 197, 30, 119, 153, 37, 180, 117, 48, 218, 214, 212, 170, 131,

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

Now you can make a simple function to pull a particular bit out of PROGMEM:

    const byte myTable [] PROGMEM = {
      197, 43, 32, 200, 47, 197, 30, 119, 153, 37, 180, 117, 48, 218, 214, 212, 170, 131,
      };

    bool getBit (const unsigned int which)
      {
      const unsigned int whichByte = which / 8;
      const byte whichBit = which & 0x07;
      return bitRead (pgm_read_byte (&myTable [whichByte]), 7 - whichBit);
      }  // end of getBit

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

      for (int i = 0; i < sizeof (myTable) * 8; i++)
        {
        Serial.print (int (getBit (i)));
        Serial.print (", ");
        }
      Serial.println ();
      }  // end of setup

    void loop ()
      {
      }  // end of loop

Output from above:

<!-- language-all: lang-none -->

    Starting
    1,1,0,0,0,1,0,1,0,0,1,0,1,0,1,1,0,0,1,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,1,0,1,1,1,1,1,1,0,0,0,1,0,1,0,0,0,1,1,1,1,0,0,1,1,1,0,1,1,1,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,1,0,1,0,1,0,0,1,0,1,0,1,0,1,0,1,0,0,0,0,0,1,1,


message:
Can I automatically loop inside a library?

I want to write a little library;

the unlibrarized functionality does:

checking in every loop-cycle some inputs,

doing some calculations with it

and finally setting a boolean to either true or false.

**How do I periodically check the inputs inside the library?**

I know that I could add a function-call  to the library in the loop()-function. But I would prefer to just check the boolean in the loop.

**Is there a way, to instantiate a class and start an periodically function by doing so?** And if, how does this constant checking affect/coexist with my 'normal' loop()-function?

body:
Generally speaking, no, you can not take control of the processor away from the main "thread" in a library. The normal solution is to provide an `update` method or something like that. you could do the calculations in a function that returns your boolean answer, then the loop code is basically the same with or without asynchronous updating.

If you can use interrupts to read your input, either as an external interrupt or on an internal timer interrupt, then what you want could be achieved because the interrupt would take control away from the main execution context and give it to you.

Interrupt routines need to be fast and simple though, and it makes the "cost" of using the library higher, since there is a limited number of interrupts/timers and other libraries may require the one you code yours to use.

Of course, the more powerful arduinos that actually run an os will have support for multiprocessing which you could leverage to get the behavior you want. This answer is intended for a standard AVR based arduino (uno, mega, etc.)


body:
> I know that I could add a function-call to the library in the loop()-function. But I would prefer to just check the boolean in the loop.

What's the difference?

In the `loop` you can call something like:

    void loop ()
      {
    ...
      if (mylibrary.ready ())
        {
        // it's time to act!
        }
    ...
      }

You can make a function, that returns a boolean type, which tells you if the thing you need to do is ready. That function *does the checking* before returning true or false.

After all, you are planning to check the boolean periodically, presumably often enough to notice it changing, why not have that be the point of noticing whatever-it-is you need to notice?


message:
Arduino crashed my computer when I plug in the USB cable

I have a 2008 Mac that hardly ever crashes. But from time to time (not always) it crashes (the whole computer shuts down as if the power has been cut off) when I plug in an Arduino via USB.

What could cause this?

----

I've done some testing and the constant in when this occurs seems to be a cheap PIR sensor from eBay. It works some of the time.

Should I get another sensor? Or is there something about PIR sensors that makes them prone to this? It has a lot of caps... Is there another kind of motion sensor?

body:
It could possibly be that there is a fault that is causing a short circuit. This short circuit could be in the board itself or the USB cable that connects the Arduino. The USB port on the Mac should have protection to protect against a short circuit. Your comments have indicated that you have tested for a short and found none - but this is helpful for others that are looking for a solution.

In your comments you mention that you solved this by changing the positive rail of your potentiometer from 3.3V rail to the 5V rail.


body:
I had this problem with a Chinese knock-off of an Arduino Nano -- looks like it was actually because I had previously installed some CH341 drivers that no longer work with Sierra.

Removing those drivers (`sudo rm -r /Library/Extensions/usbserial.kext`) stopped the crash (full computer shutdown when I plugged in the Arduino, even through an externally powered USB hub), but unfortunately my Mac doesn't seem to recognize the Arduino.

It looks like there is a newer version of the driver (1.4, 2017-01-11,  [downloadable from here](http://www.wch.cn/download/CH341SER_MAC_ZIP.html)), or the 1.3 version is [available as a homebrew cask](https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver) if you tap that repo.

I am a little wary about installing a driver from a random Chinese site. If you want, you can unzip the driver and unpackage the `.pkg` file with `pkgutil --expand package-name.pkg destination-folder`. There are a couple subfolders including a `Payload` that you can inspect a little with `zcat` -- way over my head.

Alternatively, it looks like [this repo](https://github.com/z4yx/osx-ch341-serial) may have a C++ driver that may work.


body: As n8henrie said this is an issue regarding drivers with Mac OS. I updated to Mac OS Mojave (Full disclosure I run a Hackintosh system) and plugging in the arduino nana would cause a massive kept stall causing my computer to loop (if playing a video it would loop back and forth) and I’d need to turn off the PSU in order to successfully boot. However by deleting the current drive I used (CH341) the board would no longer do this (note- I tried 3 boards from different sellers, with 1 genuine and 2 Chinese) in High Sierra this did not happen however


message:
High power consumption during power down mode

I try to use power down mode to extend battery life, but no matter what sleep library I use, the power consumption never goes below 3.4-3.6 mA. I'm using a chinese pro mini board with VCC input (but using the RAW results the same).

avr/power sketch:

    #include <avr/power.h>
    #include <avr/sleep.h>

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

      // Ensure no floating pins
      for(i=0; i<20 ; i++)
      {
        pinMode(i, OUTPUT);
        digitalWrite(i, LOW);
      }

      // Power-down board
      set_sleep_mode(SLEEP_MODE_PWR_DOWN);

      sleep_enable();

      // Disable ADC
      ADCSRA &= ~(1 << ADEN);

      // Power down functions
      PRR = 0xFF;

      // Enter sleep mode
      sleep_mode();
    }

    void loop()
    {
    }

rocketscream/Low-Power sketch:

    #include <LowPower.h>
    void setup() {
    }

    void loop() {
      LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
    }

body:
I tried your first sketch on my "bare-bones" board.

[![Bare-bones board][1]][1]

With the sketch exactly as written, it used 197 µA.

I wondered why it was that high, so I commented out this line:

      Serial.begin(9600);

That reduced consumption to 122 nA.

See [Power saving techniques for microprocessors](http://www.gammon.com.au/power).

You need to get rid of any "power" LEDs, and disconnect any voltage regulators. If you want really low consumption you need to have minimal hardware.

Of course, if you *need* the voltage regulator, well so be it. But don't expect 100 nA consumption if you use it.

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


message:
AVR+Arduino ADC problem

I  have connected a circuit to analog pin 0 in the Arduino.I have this code ,which I understand partially(online resources).The problem is that it prints nothing neither on Tera Term nor on Cool Term .Where am I mistaking ?(I am new to AVR programming).Here is the code:

      #include<stdio.h>
     void InitADC()
     {
     ADMUX=(1<<REFS0);// For Aref=AVcc;
     ADCSRA=(1<<ADEN)|(7<<ADPS0);
      }

     uint16_t ReadADC(uint8_t ch)
     {

        //Select ADC Channel ch must be 0-7
         ch=ch&0b00000111;
         ADMUX|=ch;

         //Start Single conversion

         ADCSRA|=(1<<ADSC);

          //Wait for conversion to complete
          while(!(ADCSRA & (1<<ADIF)));

          //Clear ADIF by writing one to it
          ADCSRA|=(1<<ADIF);

         return(ADC);
    }

    int main()

      {

    uint16_t adc_value;

    InitADC();

    while(1)

    {

      adc_value = ReadADC(0);
      printf("%d",adc_value);

      }

       return 0;

      }

body:
Your code compiles, but as Gerben said, the printf won't do anything in its current state, as no output handlers are defined for it. Why go to all that trouble when you can do this?

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

    void loop()
      {
      uint16_t adc_value;
      adc_value = analogRead (0);
      Serial.println (adc_value);
      delay (100);  // stop output spamming your monitor
      }

---

You could conceivably make `printf` work by following the tutorial here: <http://playground.arduino.cc/Main/Printf>

However I don't really see the point, when what I posted is much easier.

---

> If performance is an issue, you might want to use the "advanced" code.

That "advanced" code above doesn't give you any more performance, because is still blocks. You can do a non-blocking version easily and readably enough:

    const byte adcPin = 0;  // A0

    bool working;

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

      ADCSRA =  bit (ADEN);   // turn ADC on
      ADCSRA |= bit (ADPS0) |  bit (ADPS1) | bit (ADPS2);  // Prescaler of 128
      ADMUX =   bit (REFS0) | (adcPin & 0x07);  // AVcc
      }  // end of setup

    void loop ()
      {
      if (!working)
        {
        bitSet (ADCSRA, ADSC);  // start a conversion
        working = true;
        }

      // the ADC clears the bit when done
      if (bit_is_clear(ADCSRA, ADSC))
        {
        int value = ADC;  // read result
        working = false;
        Serial.println (value);
        delay (500);
        }

      // do other stuff here

      }  // end of loop

Now **that** code (which admittedly fiddles with the registers) doesn't block so you could be doing other things during the conversion. I don't see any reason you wouldn't use that on a commercial product.

See [ADC conversion on the Arduino (analogRead)](http://www.gammon.com.au/adc) for more details.


message:
Very easy Arduino code challenge for you brainiacs to solve

I've searched the forum for similar problems and still can't see my obvious issue. I'm working on a simple Halloween prop and I'm using an Arduino for the first time. I've tested each individual 'event' (i.e. fog machine, mp3, actuator, and LED strip) with a loop and all four have worked on continuous loop with no issue.

As soon as I combine them all together, the program runs successfully exactly one time. After that final 10 second delay, when I expect the program to start the loop again, it crashes. If it helps, right during the start of the next loop, the relay light turns on on the relay board for RELAY_1_A and sort of just flickers while the actuator hums. I usually shut it down quickly at this point. As soon as I turn the system back on, it successfully runs through another iteration until the loop hangs.

I'm happy to provide pictures or even a video of the issue if that helps. My guess is that you guys will spot my coding issue right away. Maybe some kind of memory overflow or something like that.

I know my code could be much more efficient but I'm just looking for the glaring problem that is keeping the loop from working.

    #include <SPI.h>
    #include <SdFat.h>
    #include <SdFatUtil.h>
    #include <SFEMP3Shield.h>

    const int RELAY_1_A = 7; //the one with the issue
    const int RELAY_1_B = 8;

    SdFat sd;
    SFEMP3Shield MP3player;
    void setup() {
      // initialize the digital pins as an output.
      pinMode(10, OUTPUT); //Fog machine on Relay1 on 5V relay board
      pinMode(3, OUTPUT); //LED strip off breadboard MOSFET
       pinMode(RELAY_1_A, OUTPUT); //12V relay for actuator on Relay1 on 12V relay board
       pinMode(RELAY_1_B, OUTPUT); //12V relay for actuator on Relay2 on 12V relay board

      //start the shield
      sd.begin(SD_SEL, SPI_FULL_SPEED);
      MP3player.begin();
      MP3player.setVolume(10, 10);
    }

    void loop() {
      MP3player.playTrack(2);  // Play MP3. Track 1 is coffin and track 2 is bird
      delay(5000);              // wait for 5 seconds
      digitalWrite(10, LOW);   // Turns ON fog machine
      delay(3000);
      digitalWrite(10, HIGH);   // Turns OFF fog machine
      digitalWrite(3, HIGH);   // Turn the LED on (HIGH is the voltage level)

      delay(5000);              // wait for 5 seconds

      retractActuator();       //Open coffin
      delay (9000);
      stopActuator();      //Close coffin
      delay (9000);
      extendActuator();      //Close coffin
      delay(8000);
      digitalWrite(RELAY_1_B, HIGH);  //Turns off this relay during the wait period before next loop

      digitalWrite(3, LOW);    // Turn the LED off by making the voltage LOW
      delay(10000);              // wait for 20 seconds

    }
    void extendActuator() {
      //Set one relay one and the other off
      //this will move extend the actuator
      digitalWrite(RELAY_1_A, HIGH);
      digitalWrite(RELAY_1_B, LOW);
    }

    void retractActuator() {
      //Set one relay off and the other on
      //this will move retract the actuator
      digitalWrite(RELAY_1_A, LOW);
      digitalWrite(RELAY_1_B, HIGH);
    }

    void stopActuator() {
     //Set both relays off
     //this will stop the actuator in a braking
     digitalWrite(RELAY_1_A, HIGH);
     digitalWrite(RELAY_1_B, HIGH); }

body:
You are attempting to use IO pins that are already in use by the MP3 shield.

According to your subsequent research, only digital pins 0,1,5, and 10 are available for use.

You should shy away from using pins 0 and 1 since they are also connected to the computer through the USB interface and are used for uploading sketches.  You will find that either you can't upload sketches with the relays connected to those pins, or the relays will "randomly" switch on and off while you're uploading a sketch.

Don't forget that the analog pins A0-A5 can also be used as digital pins, so you can quite happily drive your relays using any of those.


message:
Can Arduino Uno's serial handle to foward push through 1-wire protocol?

**tl;dr** on on digital ouput/input I would like to communicate with a 1-wire device, whose protocol requires precision to ~15 microseconds. My question is if Arduino Uno's serial communication can be as quick as to support to map the digital pin via serial->USB to my host computers app which should implement the 1-wire protocol?

**long version**
The mode in which I thought to use my Arduino was, to attach it to a host computer and run the logic of what should be done on the host computer, having the Arduino only receive the data (for the pins) and return the state of the pins.

The challenge which prompts me to this question is that the Serial communication is not really that quick, compared to the timing requirement of some protocols (e.g. 1 wire) I wish to implement.
For example: 1-wire-protocol's timing requirements (i.e. range of micorseconds) could easily be kept from code running on the Arduino Uno's Atmega328 directly, which at 16Mhz and assumed 2 cycles per command would allow somewhat a resolution of 2/16Mhz = 0,125 us.

If alternatively the data/instruction for the 1-wire protocol should be mapped via the serial interface to an application running on an PC attached to the Arduino I wonder if the time requirements of the 1-wire protocal can be reached?

It boils down to a question if the Serial communication can have a temporal granularity as small as the about 1 to 15 microseconds needed to implement the 1-wire protocol - not within arduino itself - but in the attached PC's application.

body:
Ok, so there's two issues at stake here.

1. Can the Arduino generate a 1-wire protocol with enough accuracy?
2. Can you transfer the data fast enough through the UART to tell it to do that generation?

You can't just stream a 1-wire protocol through serial and expect it to work.  The low-level serial protocol would very much get in the way.  So you have to send instructions to the Arduino to say "Raise the IO pin" and "Lower the IO pin" and "Tell me when the IO pin changes level", and "Set the IO pin to input" etc.

Each of those actions would be a discrete item that you would have to send.  Given that you could have a single byte per action (send "I" for set to input, send "O" for set to output, send "L" for set to low, etc - Arduino sends "H" if the pin goes high, or "L" if it goes low, etc), what kind of response could you expect?

Well, at 8 bits + start + stop per byte (so 10 bits) at a good fast rate (say 1MBaud), you would expect one byte to take (1/(1000000/10) = 0.00001s (10µs) to transfer.  That's raw transfer speed.  On top of that you then have to add the processing of that incoming data - the Arduino adds it to a circular buffer to allow your sketch to read it, and that takes time, and your program then interpreting it, you could expect a latency of say 15µs.  At maximum stream rate (no breaks between characters being sent at all) you would have a basic granularity of 10µs (processing the last incoming character while the next one is being received).

That's not counting any other factors such as the UART buffers on your computer, latency before the character even gets to the USB port's endpoint, etc.

So all in all there *might* be a slim chance that you could do it, but it would be *very* slim and not easy to achieve a stable result.

Far better would be to implement the 1-Wire protocol on the Arduino and just send/receive the control information to tell it to go ahead and do the work and return the results.  After all, that's what the Arduino is designed for - low level interfacing like that.


body:
Your idea seems wrong-headed, if I may say so without giving offence.

The Arduino is quite capable of generating 1-wire protocol. It certain reads it easily enough with bit-banging.

Trying to send down HLHLHHHLL through serial because your PC is "more powerful" is just not the right way of doing it. Next you'll be wanting to generate PWM on the PC and have the Arduino relay it to an output pin.

Remember, the Arduino (Uno) runs at 16 MHz. The original IBM PC ran at 4.77 MHz (if I remember correctly) so you can regard the Arduino as being as powerful as an early PC.

The simple solution is to send from the PC the data you actually want communicated by 1-wire, and let the Arduino do the actual bit-banging.


body:
It certainly is possible for an Arduino to do this.  For example, source code for Atmel's implementations of [1-Wire protocol](https://en.wikipedia.org/wiki/1-Wire) via bit-banging, via polling UART, and via interrupt-driven UART, is available at [github.com](https://github.com/semicontinuity/embedded/tree/master/target/card-terminal/firmware/one-wire-thermometer).

There is a 21-page PDF file, [doc2579.pdf](http://www.atmel.com/images/doc2579.pdf), available at Atmel.  It documents how the different implementations work.

However, the notion of communicating faster than serial via the 1-Wire protocol seems like a mistaken notion.  As I understand it, the serial implementations above use one serial character per 1-Wire bit, so necessarily are slower than serial.


message:
how many processor cycles/time does it minimaly take to transmit 1 Byte via Serial?

My understanding has been that the Serial transmission is indeed done (on the Arduino Uno) via the pins named `TX->1` and `RX<-0`?
With this I assume that the Atmega has a machine code that would allow in 1 or processor cycles (125 or 62.5 ns) to set a byte (i.e. Port byte `DDRD`) as to forward exactly one bit of information for further processing to the `ATmega16U2` "serial to USB" chip?

If this is true I would expect that 1 Byte = being 8 bits would require a discouragingly slow 8 to 12 cpu cycles (500ns to 1us)? Is this true?

body:
No, it is not true.

You are assuming (wrongly) that the CPU is doing the UART communication.  It isn't.

The UART is a completely separate piece of hardware inside the chip.  It runs by itself.  The CPU merely places the byte to transfer into a *special function register* (*SFR*).  The UART then takes that and clocks it out through the IO pins at the right rate for the serial communication.  While that is going on the CPU is free to perform other operations.

The CPU can then either consult another *SFR* to determine if the transmission has finished, or utilize an interrupt that the UART will trigger when the transfer has been completed.


body:
According to the datasheet:

[![Baud rates at 16 MHz][1]][1]

Running at 16 MHz (as the Uno does) you can get up to 2 Mbps.

> If this is true I would expect that 1 Byte = being 8 bits would require a discouragingly slow 8 to 12 cpu cycles (500ns to 1us)? Is this true?

For a bit or a  byte? At 2 Mbps that is a bit every 8 clock cycles.

>  would you know what would the UART be?

The UART is built into the processor chip. I suggest you read the datasheet.

>  I thought it was unable to tell more than 16 million times a second something to the UART, which then could have baud rates higher than what could be indicated by the Atmega328 on the Uno, right?

You can't do *anything* more than 16 million times a second at 16 MHz. And the clocking out of bits (in SPI, serial, or I2C) itself requires clock cycles, although they are done in parallel with the processor instructions by the hardware.

---

This is related to your other thread <https://arduino.stackexchange.com/questions/16032/can-arduino-unos-serial-handle-to-foward-push-through-1-wire-protocol> isn't it? Your end objective, I am guessing, is to try to implement 1-wire reading/writing via sending each bit via serial. This is just not the right way to achieve that objective.

In fact this thread in particular is coming across as an [X-Y problem](http://xyproblem.info/) - your stated objective of wanting high-speed serial, is not really the problem you are trying to solve, is it?

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


message:
Bluetooth Stream to USB

I want to make a device that will take a Bluetooth stream and play it on speakers via the USB port for speakers that do not have Bluetooth.

I think it may be possible by taking the stream and using an Arduino to convert the stream to a virtual file so that the speaker will see the USB as a mass storage and play the file.

I am not sure that is just an idea, any thoughts or solutions?

body:
If your target is a USB audio device - like a USB headset or USB speakers (NOT an MP3 player with USB interface) then you could connect it to something which can act as a USB host with USB audio device drivers.  That means *not* an Arduino, but something much more powerful like a Raspberry Pi or BeagleBone Black for instance.

If your target is basically an MP3 player that allows you to connect a USB stick with songs on it then you're completely out of luck.  There's this small thing called *time* that gets in your way.  You can't stream data to something that expects the data to already be there. You can't seek in a file that doesn't exist until the moment you try to read from it. Also you have to act as if you were a USB memory stick, and that's not easy, and certainly not something an Arduino can do. Even things like the Pi would have a lot of difficulty in managing that since they are hosts, not devices, as far as USB is concerned.

The key word here is *stream*.  Your target as to be able to receive a *stream* of data rather than request blocks of data from a file.  USB audio *devices* can do that, but USB audio *hosts* cannot.