message:
Reading a photoresistor

I have a wire with a 0-5v current. I want to detect if the current is there or not (HIGH/LOW.)

I'm using an optocoupler to avoid putting too much current into my micro, as it is only a 3.3V micro. I'm nervous about powering this on as one of my other micros stopped working although it's not clear if it could have been the circuit?

![enter image description here][1]
I could not find my optocoupler in fritzing. This is it:
http://www.amazon.com/gp/product/B00CGXK1RG?psc=1&redirect=true&ref_=oh_aui_detailpage_o07_s00

This is my plan.

![The microcontroller is a spark/particle core. It the yellow wire connects to the analog/digital pin A6. The screw terminals connect to the wire with the 5v current that I'm trying to detect.][2]

The microcontroller is a spark/particle core 3.3v. It the yellow wire connects to the analog pin A6. The screw terminals connect to the wire with the 5v current that I'm trying to detect.

I based my circuit on this:

![enter image description here][3]

But I don't know if it will do the same thing.

![enter image description here][4]

  [1]: https://i.stack.imgur.com/hnbMR.jpg
  [2]: https://i.stack.imgur.com/aUsOB.jpg
  [3]: https://i.stack.imgur.com/sL3r6.jpg
  [4]: https://i.stack.imgur.com/D1vAE.jpg

body:
Wouldn't this be simpler?

![3.3v voltage detector][1]

*Note: amended answer increases R1 to 10 k.*

The 10 k resistor limits current to 0.17 mA. The 3.3 V zener diode clamps the input voltage to 3.3 V (I measured 2.3 V on mine so that is well within spec). The other end of the zener diode goes to the Arduino ground pin.

I originally had R1 as 1 k however if you had a high voltage input (like 20 V) it didn't quite clamp the pin to 3.3 V (more like 3.8 V). This is a bit high for an input pin, so I tried 10 k instead.

This gives:

* For an input voltage of 5 V -> 2.3 V on the Arduino input
* For an input voltage of 10 V -> 2.6 V on the Arduino input
* For an input voltage of 20 V -> 2.9 V on the Arduino input
* For an input voltage of 30 V -> 3.1 V on the Arduino input

This is all within spec for the Arduino.

Now the question is, will 2.3 V on the input pin register as HIGH? The answer is "yes" because high is considered to be 0.6 * VCC.

    3.3 * 0.6 = 1.98

Thus any voltage of 1.98 or above is considered HIGH, and it will successfully read 2.3 V as high.

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


sender: user

sender: assistant

body:
Based on the revised information given above I present a different answer. Use the opto-coupler as shown here:

Your kettle LED will be in series with the optocoupler (note the polarity, not reversed like in your question).

If the LED is on the transistor in the PC817 will conduct and the Arduino pin will be LOW. If the LED is off the transistor will not conduct and the Arduino pin will be HIGH.

![enter image description here][1]

Note: The Arduino pin will be the reverse of the kettle LED.

I'm leaving the other answer there because I think it is a reasonable answer to the question of "detect a voltage".

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


message:
Does restarting Yún configuration mess up Arduino or its SD card?

I noticed something odd recently - a Yún, that was working previously, wouldn't connect.

After logging in to the web setup, setting the access point and password (which hadn't changed), and save & restart, it connected. Unfortunately, it still doesn't work, and after ssh into it, I find I cannot `ls /mnt/sd/` or `sda1`. It just sits there, requiring Ctrl+C, and gives no output.

Did I reset the Arduino or Linux somehow by setting up access point again, or could my SD card be broken after months of heavy logging?

body: It sounds like your SD card has likely failed. Try connecting it to a computer with an SD card reader. If it works at all, back it up immediately if you have files you wish to keep. Then try reading and writing files on it. Also if you have a spare SD card, try to use that in the Yun after setting it up appropriately. That should help narrow down the cause to either the Yun or the SD card.


message:
Using an Arduino as an LED controller for an arcade stick

I'm attempting what seemed to be a rather simple problem at first glance, but due to my limited knowledge of Arduino workings I need some help. I'm trying to use button outputs from a PS360+ arcade controller. Each of the button terminals output +5V, and is meant to be connected through a button to the grounds on the PS360+.

  What I want to do is have an Arduino somewhere in between the button output and ground on the PS360+, to control and animate LEDs. What I've done so far is connect the VCC of the PS360+ to the Arduino's VIN and the ground of the Arduino to the PS360+'s button ground, which powers the Arduino. I then have a button output from the PS360+ going into the button, and the button's ground is connected to an Arduino pin. That Arduino pin's mode is set to INPUT. I then have another pin with an LED which is set to the value of the input pin.
  For some reason, the Arduino seems to get random input from the button(Though it does seem to react somewhat to buttons presses), and the PS360+ does not recognize the button press. Setting the input pin to pullup mode has even less result, and never reads low.

Anybody got any ideas? Here's my current circuit diagram. 1P is a +5V output. I think that it's an internal pull-up pin like the Arduino's, but I am not certain. ![Circuit Diagram][1]

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

And my current code:

    int buttonlisten = 22;
    int led = 53;
    int val = 0;

    void setup() {
      pinMode(led, OUTPUT);
      pinMode(buttonlisten, INPUT);
    }

    void loop() {
      val = digitalRead(buttonlisten);
      digitalWrite(led, val);
    }

Thanks!

body:
I think the idea of putting the arduino between the button and ground is the problem here — `1P` appears to be the input for the controller button, and you can't expect to take an 'input' from the button on *both pins at once*.

Try connecting one lead of the button back to its ground, and the other to `1P` (as it would be originally I assume). Then solder/connect another lead from the button's non-grounded pin to an arduino pin designated as `INPUT_PULLUP`.

This way you have two pulled-up input pins connected to the same button pin, which are both pulled low (since Arduino & PS360+ share `GND`) when the button is pressed.


message:
Embedded-c, schedule a function?

Simple question, of course if you do this

    FunctionA();
    Delay(1000);
    FunctionB();
    FunctionC();

it will call A, then wait a second, then call B, then call C.

How does one do this? ...

    FunctionA();
    .. Invoke FunctionX one second from now ..
    FunctionB();
    FunctionC();

So, I want it to do A, then without stopping continue to B and then C.  Later (one second later) it will do X.

Of course, in c# you'd just use a coroutine, in Android you'd use a Handler or whatever.

Surely there's a command along the lines of .. invoke in .. 2000 .. method.

Really sorry for the basic question, experts, I am damned if I can find this anywhere. Thanks!

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

> Surely there's a command along the lines of .. invoke in .. 2000 .. method.

Not "a command" but you can make up something like that easily enough. Example:

    // Function scheduler demo
    // Author: Nick Gammon
    // Date: 11 July 2015

    typedef void (*GeneralFunction) (); // function pointer type

    GeneralFunction wantedFunction = NULL;  // function to call
    unsigned long functionTimerStarted;     // when the timer started
    unsigned long delayPeriod;              // how long to wait (ms)

    void functionA ()
      {
      Serial.println ("Function A");
      }  // end of functionA

    void functionB ()
      {
      Serial.println ("Function B");
      }  // end of functionB

    void functionC ()
      {
      Serial.println ("Function C");
      }  // end of functionC

    void functionX ()
      {
      Serial.println ("Function X");
      }  // end of functionX

    void scheduleFunction (GeneralFunction f, unsigned long when);  // prototype
    void scheduleFunction (GeneralFunction f, unsigned long when)
      {
      wantedFunction = f;
      functionTimerStarted = millis ();
      delayPeriod = when;
      }  // end of scheduleFunction

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

      functionA ();  // call this now
      scheduleFunction (functionX, 2000);  // call this later
      functionB ();  // call this now
      functionC ();  // call this now

      }  // end of setup

    void loop ()
      {
      // see if time to call the delayed function
      if (wantedFunction && millis () - functionTimerStarted >= delayPeriod)
        {
        wantedFunction ();
        wantedFunction = NULL;  // don't call it again
        }  // end of if time up

      // do other wanted stuff here

      }  // end of loop

This uses:

* A function pointer to remember which function to call in the future.
* A global variable to remember when you wanted this timing interval to start.
* A global variable to remember how long to wait.

In setup() I called a function to save this information for future use:

      scheduleFunction (functionX, 2000);  // call this later

Then in loop() we see if the time is up, and then call the function.

This example just calls functions with no arguments, things will get more complex if you want to call a function with an argument. It would even be possible to remember the argument, but it may be unnecessarily complicated to explain how to do that, since your example did not ask for it.

You could also even schedule multiple functions, but again, showing all that adds to the complexity of the explanation.

For more information about function pointers, see [Function pointers / function callbacks / function variables](http://www.gammon.com.au/callbacks).


message:
Converting float to String

How can I convert a `float` value into a `String` object without implementing any library?

I'd like to avoid using `char` array.

body:
If you want to do it manually, rather than using the standard tools (`dtostrf()` for example) then you need to think mathematically.

A floating point number is made up of two distinct parts - the *integer* part and the *decimal* part.

For instance the number `123.4567` is made up of the integer part 123 and the decimal part 4567.  Chopping off the integer portion is simple to do, and if that happens to be just one digit then you can simply add that as the first digit of your output.  In this case, though, it isn't.

So what to do?  Simple: keep dividing the number by 10 until it is just one digit.  But *be sure to count the number of times you divide by 10*.  So the example above would end up as 1.234567 with a divide count of 2.  This is the same as the scientific representation, 1.234567×10².

So now you have it divided you can chop off the integer (just cast it to an int), add that integer part to your string, then remove it from the source number.  So you end up with "1" and 0.234567 and a count of 2.

Now multiply by 10 and subtract one from your count, so you get 2.34567 and a count of 1.  Grab the integer portion and add it to your string, then remove it from your number.

Keep repeating until your count is 0, at which point you have now done all the integer portion - so you can now add a "." to your string.

You now just keep repeating the same process again and again until the *absolute* value of the count equals the number of decimal places you want to print.

For negative numbers you should start by placing a "-" in your string, then taking the *absolute* value of the number (the number as a positive).

Or you just use the standard library function `dtostrf()`.


message:
Arduino webserver: faster alternative to "indexof" for parsing GET requests?

I have a webserver successfully running on an Arduino Mega, but I'm trying to make sure it's parsing the GET requests in the fastest way possible. This is what the relevant code for the GET requests looks like:

    String readString;
    EthernetClient client = server.available();
    if (client) {
      while (client.connected()) {
        if (client.available()) {
          char c = client.read();

        if (readString.length() < 20) {
          readString += c;
        }
        ...
        ...
          if (readString.indexOf("?a1o") >0){
            mySwitch.send(a1o, 24);
          }
          if (readString.indexOf("?a1c") >0){
            mySwitch.send(a1c, 24);
          }

The sketch checks for 40 possible GET variables. I'm running it as a local webserver with the address: http://192.168.0.180.

-Is there a command faster than "indexOf" that I could be using?

-I saw some information suggesting that sometimes "parseInt" can be faster. Is there any way for me to make that work even though my local base URL is already full of integers? I would be willing to convert the commands into integers (like "11" instead of "a1o") if there was a way to use parseInt or another faster command with it.

Thanks!

body:
Well, for fast parsing I wouldn't use String for a start. I've written an example (below) which does away with the String class, and also demonstrates parsing the line once.

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

    // Enter a MAC address and IP address for your controller below.
    byte mac[] = {  0xB3, 0x8D, 0x72, 0x1D, 0xCE, 0x91 };

    // Our IP address
    IPAddress ip(10,0,0,241);

    // Initialize the Ethernet server library
    // with the IP address and port you want to use
    // (port 80 is default for HTTP):
    EthernetServer server(80);

    void setup()
      {
      // Open serial communications and wait for port to open:
      Serial.begin(115200);
      while (!Serial) { } // wait for serial port to connect.

      // start the Ethernet connection and the server:
      Ethernet.begin(mac, ip);
      server.begin();
      Serial.print(F("Server is at "));
      Serial.println(Ethernet.localIP());
      }  // end of setup

    // how much serial data we expect before a newline
    const unsigned int MAX_INPUT = 100;
    // the maximum length of paramters we accept
    const int MAX_PARAM = 10;

    // Example GET line: GET /?foo=bar HTTP/1.1
    void processGet (const char * data)
      {
      // find where the parameters start
      const char * paramsPos = strchr (data, '?');
      if (paramsPos == NULL)
        return;  // no parameters
      // find the trailing space
      const char * spacePos = strchr (paramsPos, ' ');
      if (spacePos == NULL)
        return;  // no space found
      // work out how long the parameters are
      int paramLength = spacePos - paramsPos - 1;
      // see if too long
      if (paramLength >= MAX_PARAM)
        return;  // too long for us
      // copy parameters into a buffer
      char param [MAX_PARAM];
      memcpy (param, paramsPos + 1, paramLength);  // skip the "?"
      param [paramLength] = 0;  // null terminator

      // do things depending on argument (GET parameters)

      if (strcmp (param, "foo") == 0)
        Serial.println (F("Activating foo"));
      else if (strcmp (param, "bar") == 0)
        Serial.println (F("Activating bar"));

      }  // end of processGet

    // here to process incoming serial data after a terminator received
    void processData (const char * data)
      {
      Serial.println (data);
      if (strlen (data) < 4)
        return;

      if (memcmp (data, "GET ", 4) == 0)
        processGet (&data [4]);
      }  // end of processData

    bool processIncomingByte (const byte inByte)
      {
      static char input_line [MAX_INPUT];
      static unsigned int input_pos = 0;
      switch (inByte)
        {
        case '\n':   // end of text
          input_line [input_pos] = 0;  // terminating null byte
          if (input_pos == 0)
            return true;   // got blank line
          // terminator reached! process input_line here ...
          processData (input_line);
          // reset buffer for next time
          input_pos = 0;
          break;

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

        default:
          // keep adding if not full ... allow for terminating null byte
          if (input_pos < (MAX_INPUT - 1))
            input_line [input_pos++] = inByte;
          break;
        }  // end of switch
      return false;    // don't have a blank line yet
      } // end of processIncomingByte

    void loop()
      {
      // listen for incoming clients
      EthernetClient client = server.available();
      if (client)
        {
        Serial.println(F("Client connected"));
        // an http request ends with a blank line
        boolean done = false;
        while (client.connected() && !done)
          {
          while (client.available () > 0 && !done)
            done = processIncomingByte (client.read ());
          }  // end of while client connected

        // send a standard http response header
        client.println(F("HTTP/1.1 200 OK"));
        client.println(F("Content-Type: text/html"));
        client.println(F("Connection: close"));  // close after completion of the response
        client.println();   // end of HTTP header
        client.println(F("<!DOCTYPE HTML>"));
        client.println(F(""));
        client.println(F(""));
        client.println(F("<title>Test page</title>"));
        client.println(F(""));
        client.println(F(""));
        client.println(F("
My web page
"));
        client.println(F("
Requested actions performed"));
        client.println(F(""));
        client.println(F(""));

        // give the web browser time to receive the data
        delay(10);
        // close the connection:
        client.stop();
        Serial.println(F("Client disconnected"));
      }  // end of got a new client
    }  // end of loop

The incoming lines from the client are captured in a static buffer. This eliminates issues with memory fragmentation (caused by using String).

`processIncomingByte` is called for each byte from the client. Once an entire line is assembled it calls `processData`. If that finds a "GET " line it calls `processGet`. That looks for the parameters on the GET line. The GET line looks like this:

    GET /?bar HTTP/1.1

So we need to get between the "?" and the next space, to get the parameter ("bar" in this case). This can be accomplished by finding their positions with `strchr`.

Finally (as a simple example) I tested with strcmp for a direct match on various words. You could probably make that more efficient but I doubt it would matter much.


message:
Number of elements in an array char

What kind of function can I use to know how many elements are in an array char?

sizeof() gives the number of 'spaces' available so it doesn't work for me.

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

You want `strlen`.

    char foo [100] = "bar";
    Serial.println (strlen (foo));   // --> prints 3


body:
I know you have your answer from @NickGammon, but I'd just like to add a bit more in-depth information about how all this works.

`sizeof()` is not a function in the normal sense of the word.  It is an operator which gives you the number of bytes of memory allocated to whatever you pass to it.  If you pass it an array then it returns the number of bytes that array has available to it.  If you pass it a pointer to an array then it returns the size of that pointer, not the size of the array.  If you pass it an integer variable it returns the number of bytes used by that integer variable (2 on an 8-bit system like AVR, 4 on a 32-bit system like the Due).

So some examples:

    char array[50] = "hello";
    // sizeof(array) = 50.
    char *array_p = array;
    // sizeof(array_p) = 2 or 4 depending on architecture.
    char single = 'a';
    // sizeof(single) = 1.
    char string[] = "hello";
    // sizeof(string) = 6 (5 letters plus \0) - it allocates the memory at compile time to fit the string

Now `strlen()`.  How exactly does that differ from `sizeof()`?  Simply put, `strlen()` counts the number of characters in a character array up until it reaches the character `\0` which is the "NULL" terminating character of a C string.  Let's take the examples before but use strlen instead:

    char array[50] = "hello";
    // strlen(array) = 5.
    char *array_p = array;
    // strlen(array_p) = 5.
    char single = 'a';
    // strlen(single) = ERROR!  strlen() doesn't operate on single characters.
    char string[] = "hello";
    // strlen(string) = 5.

You notice it always returns the number of characters in the string up to, but not including, the trailing `\0` character.

In its simplest form the `strlen()` function might look like this:

    int strlen(const char *data) {
        int c = 0;
        const char *p = data;
        while (*p) {
            c++;
            p++;
        }
        return c;
    }

Basically it starts at the first character in the string (`*p = data`), examines if it's a `\0` or not (`while (*p)`), increments the count of characters (`c++`) and moves on to the next character in the string (`p++`).

If you want to iterate through your string in your program you could call `strlen()` first to get the number of characters in the string then use that value in a loop.  That is a bit wasteful, since `strlen()` first iterates through the string, so you end up iterating through it twice.  It is far more efficient to learn how best to step through each character in the string until you find the terminating character, such as how the `strlen()` function uses the *pointer* to move through memory.  You can also see just how vital it is that you ensure the `\0` character exists at the end of the string, otherwise how will functions like `strlen()` know when to stop?  They can't know how long the string is (`sizeof()` will return the size of the pointer it is passed, not the size of the array), so they have to have some kind of manual marker, and the convention in C is to use `\0`.

Note that Arduino's `print()` functions actually do it very inefficiently.  If you do something like:

    char message[] = "Hello";
    Serial.println(message);

It will actually do quite a lot of work it doesn't *really* need to.  Taken step by step it:

1. calls println(message)
2. which calls write(message)
3. which gets the string length with strlen(message)
4. and calls write(message, length)
5. which then loops from 0 to length-1 sending each character of message to write() in turn.
6. finally prints the `\r\n` for the new-line.

So it actually ends nested around 4 functions deep, and iterates the entire string twice. A classic example of how to waste processing time.  By iterating through the string once looking for the `\0` character in the `write(message)` function (step 2) it would operate at least twice as fast.  Good old Arduino...


message:
How to program for two Arduinos with different code but share one same .h?

I am now programming for two Arduinos. One is used as Tx and the other is Rx. Of course they are programmed by different codes, but they share some same .h files I programmed(let's say 'share.h'), which are not libraries and shouldn't be put in Arduino's 'library' folder.

So I put 'share.h' and main.ino in one folder, and the ino is like:

    #include "share.h"
    #define TX
    #ifdef TX
    void setup(){...something for Tx...}
    void loop(){...}
    #else
    void setup(){...something for Rx...}
    void loop(){...}
    #endif

The shortage is that every time I want to update my code to the two unos, I have to: first change the board port to 40(the Tx uno) in ide, add the `#define` line, and upload. Then I have to change port to 42(the Rx one), comment the `#define` line and upload. So inconvenient!

So do you have any good ideas? Much appreciation!

body:
Because you're using Windows there is no easy way of doing what you want to do.

If you were on Linux or OS X you would be able to create a *symbolic link* so that your shared file can exist in more than one location:

    $ ln -s /path/to/real/share.h share.h

On Windows there is then just two options that I can think of:

1. Turn your shared file into a library.  I don't know why you are so adverse to this, since it is by far the simplest option.  Just create a folder "MyProjectShared" in your libraries folder, then name you shared header "MyProjectShared.h" within that folder.  Then `#include <MyProjectShared.h>`.  Of course, choose a sensible name not MyProjectShared.

2. Change to a different IDE that will allow you to add include locations.  One example is my [UECIDE](http://uecide.org/beta) which allows you to add the line:

     #pragma parameter board.flags=-IC:/Path/To/Other/Includes

to the top of your sketch, which adds another location to find header files while compiling.

Another thought has just occurred to me.  If the two sketches are side by side in a folder (say Arduino/Sketch1 and Arduino/Sketch2) then you may be able to use a relative path.

In Sketch2, do:

    #include "../Sketch1/share.h"


body:
I confronted this exact issue a little while back when writing some sketches that hard shared information. In particular [github.com/nickgammon/arduino_sketches](https://github.com/nickgammon/arduino_sketches)

Whilst another IDE may help, I wanted to make my sketches usable by people with the default IDE.

There are a few (annoying) issues here:

* You can't use relative folders as suggested in another answer, because the IDE copies your *current* sketch folder to a temporary folder and compiles from there. It won't copy other nearby folders that happen to be mentioned in .h files.

* You can make soft links (in Linux anyway) as suggested, however that makes it hard to do Git control on them. My first attempt had the link (only) appear in GitHub, which meant that the links didn't compile, once you downloaded them (via the .zip file option in GitHub).

* I switched to hard links, but then had another issue. If you edit a file in the IDE, and save it, evidently this becomes a new file, and so the files in other folders, which are now hard-linked, have the older version and not the newer version.

---

The best solution I could come up with (and I am open to suggestions) was to have a "master" sketch - which has the "real" files you want to include. The other folders have links to them. However if you change the master folder you have to recreate the hard links. I wrote a shell script to do that, but it is still an ugly solution. However since it is a manual process anyway, under Windows you could simply make a copy of the files, when you change the master one.

The other (simpler) alternative would be to make a library, and then simply change the files in that library. That gives you better Git management. The only thing is that you have to edit the library, and then go and test the sketch. It's not that bad.

> And I found that after I added the h as library, no matter how I change the content of the h, the first version is always used in ide.

That shouldn't happen unless the IDE doesn't expect the library to change in-between compiles. If that is the case, even the library idea has flaws.


body:
Thanks to everybody, now I get a better solution. It is changing the `build path` to our working directory, and then we can use relative path!

Here are the deatiled steps:

1. Click IDE's `File-Preferences` and find where it storages `preferences.txt`. Mine is at `C:\Users\Administrator\AppData\Roaming\Arduino15\preferences.txt`
2. In the txt file add this line: `build.path=D:\MyProject\ArduinoBuild`. This means let Arduino put the temp files in this directory, such as the `.h` waiting to compile.
3. Because the `.h` Arduino automatically generated from our `.ino` is in `ArduinoBuild` directory, you can now use `#include "./../Share/SomeShare.h"` in order to include the `D:\MyProject\Share\SomeShare.h`

Here is the same question asked in another stackexchange board: [Here][1]

  [1]: https://stackoverflow.com/questions/31357207/how-to-program-for-two-arduinos-with-different-code-but-share-one-same-h/


body:
Ok, first of all you have to answer this question:

> How can I tell the compiler what program it should compile?

**The first** (and easiest) solution is to have the preprocessor to this job. It's just a matter of writing two `/`...

Personally, instead of wrapping everything in an `ifdef`, I would have done something like

    #include "share.h"
    #define TX
    #ifdef TX
    #define setup_tx() setup()
    #define loop_tx() loop()
    #else
    #define setup_rx() setup()
    #define loop_rx() loop()
    #endif

    void setup_tx(){...}
    void loop_tx(){...}

    void setup_rx(){...}
    void loop_rx(){...}

This way I could put the two different setup/loop pairs in two different files (e.g. tx.ino and rx.ino). Moreover the `ifdef` block can be moved in an h file.

NOTE: I'm not sure wheter the function redefinition works well, because I never tried it. If it doesn't work you can try doing the opposite (i.e. `#define setup() setup_tx()` and so on) or, in the end, make single-line functions (i.e. `void setup(){setup_tx();}` and so on).

**Another** solution can be applied if the processors are different. For instance if you have an Arduino UNO as transmitter and an Arduino Mega 2560 as a receiver, you could write:

    #ifdef __AVR_ATmega2560__
    - receiver functions
    #else
    - transmitter functions
    #endif

But this would require you to switch processor along with the port.

The **third** solution is to place the shared h file in an include directory. You can do this by using a common include dir:

> The include path includes the sketch's directory, the target directory (<ARDUINO>/hardware/core/<CORE>/) and the avr include directory (<ARDUINO>/hardware/tools/avr/avr/include/), as well as any library directories (in <ARDUINO>/hardware/libraries/) which contain a header file which is included by the main sketch file.

(See [here][1])

You can also pass the `-Idir` option to avr-gcc to include also `dir` in the include dirs list, but this requires you to change the boards.txt file.

The **last** solution I can think at is to compile both programs, load the same files on both arduinos and then choose at runtime what is the correct program to use by assinging a pin to the "choice of program" function.

For instance you assing pin 8 to this function. On the TX board you connect pin 8 to VCC, while on the RX board you connect it to GND. Then the program is:

    #include "share.h"

    // Loop function callback (to speed things up)
    typedef void (*loopfunction)();
    loopfunction currentloop;

    const int RXTX_PIN = 8;

    void setup()
    {
        pinMode(RXTX_PIN,INPUT);
        if (digitalRead(RXTX_PIN))
        {
            setup_tx();
            currentloop = loop_tx;
        }
        else
        {
            setup_rx();
            currentloop = loop_rx;
        }
    }

    void loop()
    {
        currentloop();
    }

    void setup_tx(){...}
    void loop_tx(){...}

    void setup_rx(){...}
    void loop_rx(){...}

IMHO the best solution is the first one, i.e. the define one. But... You should choose the best for your particular problem.

Bye

  [1]: https://www.arduino.cc/en/Hacking/BuildProcess


body:
You can feed the compiler a [command-line switch][1], `-D<define_name>`, so for your TX you could have a project that has `-DTX` and for the RX `-DRX`.

Then you can share the code between the two projects and you don't need to change the code when you're compiling.

  [1]: https://gcc.gnu.org/onlinedocs/gcc/Preprocessor-Options.html


body:
You could also use:

in transmitter.ino
#define TX 1
#include "share.h"

in receiver.ino
#define RX 1
#include "share.h"


message:
SD Library writing char in a file

I'm trying to write into a file using this code from the example of the library:

    String dataString = "";
    int sensor = 0;
    dataString += String(sensor);
    dataString += ",";
    sensor +=1;

    File dataFile = SD.open("datalog.txt", FILE_WRITE);
    if (dataFile) {
      dataFile.println(dataString);
      dataFile.close();
    }
I have a char array that I want to write in the file, but it works only with String objects apparently. What can I do?

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

You can write char arrays? What makes you think you can't? Example:

    char dataBuffer [80];
    strcpy (dataBuffer, "Hello, world");

    File dataFile = SD.open("datalog.txt", FILE_WRITE);
    if (dataFile) {
      dataFile.println(dataBuffer);
      dataFile.close();
    }


body:
Try using ``dataFile.write(arrayName);``

https://www.arduino.cc/en/Reference/FileWrite


message:
How to test Arduino board?

A little history: I have two Arduino Uno and I couldn't program them by IDE, I got these errors:

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

So I googled it for a while and I suspect of missing bootloader on atmega micro on the board, as I don't have AVR programmer I programmed both Arduinos with Raspberry Pi and Arduino IDE tool through ICSP pins.

It (burning bootloader) runs perfectly on both Arduino. One of them got fixed and got back to normal, but the other one gave me same error, so I changed their Atmega micro, but same result. Second Arduino (bad one) can't transfer program to AVR even with other one (good one) AVR so both AVRs on the boards are good.
The program (blink LED) run even on the bad Arduino and pin 13 blink.

My questions are:

How could I test the suspected Arduino board? Is the second Atmel micro near usb female port need bootloader too?

> **Update 1**: I follow [this tutorial][1] but my Arduino couldn't go to DFU
> mod by shorting the pins. When I connect those pins led pin 13 not blink and lsusb command show Arduino not Atmel.

> **Update 2** : I went through [this question][2] and [this
> troubleshoot][3] to upload bootloader to Atmel USB device but my
> second Arduino (bad one) didn't respond and gave me this error :

    Atmega chip detector.
    Written by Nick Gammon.
    Version 1.17
    Compiled on Jul 13 2015 at 11:14:35 with Arduino IDE 105.
    Attempting to enter ICSP programming mode......................................................
    Failed to enter programming mode. Double-check wiring!
    Programming mode off.

> Is it possible my Atmega16U2 chip is burned?
>
> **Update 3** : I do reach the point that I am pretty sure Atmega16U2 is
> dead and it isn't responding to its ICSP pins and it blocks any USB to AVR connection. I check the wiring and I
> test it on good Arduino and its sequence are correct and it works on good one. Now what can I
> do, as Atmega16U2 is not rechangeable, should I throw bad Arduino away?

  [1]: http://bartruffle.blogspot.com/2013/09/dfu-programming-atmega16u2-on-arduino.html
  [2]: https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno
  [3]: http://www.gammon.com.au/bootloader

body: does the built-in arduino LED light up?? If yes try connecting your arduino in another uno usb port or try pressing the reset button on your arduino uno.


body:
This answer is for your 3dr Update - should you throw it away?
I'd say no, if you are comfortable with using the Raspberry PI as programmer, as you already did.
You will not be able to use the USB-based programming, nor you will be able to emulate USB peripherals, but that's it.

Everything else will (or should) work normally, so why would you throw it away? :-)

I also suggest you grab the stronger magnifying lens you can find and have a look at the soldering of all the components. Especially those connected to the Atmega16U and the chip itself. Maybe it's not broken, but there is some short caused by conductive debris or by some excess of soldering material. If that's the case, it might be easy to remove it.


message:
Separate ATmega 2560 - turn on a single LED - troubleshooting

I have got my own PCB with "some stuff" on it and first I want to make it run a simple "turn on LED".

My setup:

 - Atmega 2560
 - LED connected to PE4 (D2 in Arduino language) => PE4 - LED - 1K resistor - 5V
 - ceramic resonator (CSTCE16M0V53-R0 16MHZ) connected to XTAL1 + XTAL2 with 1MOhm resistor in between
 - all VINs are pulled to GND with capacitors

![resonator VINs GNDs][1]
![RESET circuit][2]
![status LEDs][4]

Upload is working through ICSP (MISO, MOSI, SCK, RESET, 5V, GND) with an USBasp

Here is my **Arduino sketch**, which I upload through the Arduino software:

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

    void loop() {
      digitalWrite(2, LOW);
    }

I checked the fuses on the Atmega as well:

    avrdude: safemode: lfuse reads as FF
    avrdude: safemode: hfuse reads as D8
    avrdude: safemode: efuse reads as FD
    avrdude: safemode: Fuses OK (H:FD, E:D8, L:FF)

avrdude uploads successfully: *(output truncated!)*

    avrdude: auto set sck period (because given equals null)
    avrdude: AVR device initialized and ready to accept instructions
    Reading | ################################################## | 100% 0.01s
    avrdude: Device signature = 0x1e9801
    avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
             To disable this feature, specify the -D option.
    avrdude: erasing chip
    avrdude: auto set sck period (because given equals null)
    avrdude: writing flash (1518 bytes):
    Writing | ################################################## | 100% 5.47s
    avrdude: 1518 bytes of flash written
    avrdude: reading on-chip flash data:
    Reading | ################################################## | 100% 3.45s
    avrdude: verifying ...
    avrdude: 1518 bytes of flash verified

    avrdude done.  Thank you.

Problem: the LED doesn't work. It is OFF all the time.

Any ideas why it is not working?

  [1]: https://i.stack.imgur.com/c8hIN.png
  [2]: https://i.stack.imgur.com/ZeKns.png
  [3]: https://i.stack.imgur.com/fzOr2.png
  [4]: https://i.stack.imgur.com/UP9Az.png

body:
You are saying that the LED lights if you write LOW to it.

>  I need to pull the output pin to LOW to make the LED work

That's exactly what you expect.

![LED wiring][1]

Since the other end of the LED is wired to +5 V, then you need to drive the pin low to have a voltage difference over the LED, and for it to light.

---

> I double checked the Atmega and it is a ATmega2560V, which is rated for 8Mhz. Any chance to fix this with the existing PCB? Change the Fuses to use the internal clock?

Yes, I suggest you do that.

Look at [Engbedded Atmel AVR® Fuse Calculator](http://www.engbedded.com/fusecalc) to see what to set them to. I suggest the internal 8 MHz oscillator.

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


message:
Arduino Mega PWM pins stop working for LEDs once servo is attached?

I can get LEDs to fade properly using PWM on pins 44-46 on the Mega2560 when I don't have a servo attached, but once I "attach" the servo in the code, then PWM pins 44-46 don't work for PWM. They can still work with digitalWrite, but not with analogWrite.

This is the code:

    #include <Servo.h>
    Servo myservo;
    int led = 46;

    void setup()  {
      myservo.attach(3);
      pinMode(led, OUTPUT);
      analogWrite(led, 60);
    }

    void loop()  {}
If I comment out the "myservo.attach(3);" line, then PWM works for the LED pin. Otherwise the LED stays off. Why would PWM on pins 44-46 stop working once the servo is attached?

body:
Looks like the mega has some clever [servo handling features][1]. Servo control always uses a timer of some sort and can conflict with the pwm timer. The first 12 servos knock out pins 44,45,46 ...

> For Arduino Mega it is a bit more difficult. The timer needed depends on the number of servos. Each timer can handle 12 servos. For the first 12 servos timer 5 will be used (losing PWM on Pin 44,45,46). For 24 Servos timer 5 and 1 will be used (losing PWM on Pin 11,12,44,45,46).. For 36 servos timer 5, 1 and 3 will be used (losing PWM on Pin 2,3,5,11,12,44,45,46).. For 48 servos all 16bit timers 5,1,3 and 4 will be used (losing all PWM pins).

  [1]: https://arduino-info.wikispaces.com/Timers-Arduino


message:
How does one design for the power on transient conditions?

Following on from the question [Reset an Arduino UNO by an command (software)][1] and the excellent [answer][2] provided by [mpflaga][3], the comment addressing option (1) suggests that there are design considerations for connecting an output pin to the RESET pin.

> Option 1. or a variant can be a clean enough way to do this as long as
> power on transient conditions are designed for.
- [Russell McMahon][4]

or more ominuously

> From everything I've read, the first option is not recommended. - [sachleen][5]

Could someone tell me exactly what those considerations are? Is it that it is not as simple as connecting the two with a jumper cable - is additional circuitry (i.e. an RC timer) required, or is there a software solution?

I find the latter option unlikely as the device is rebooting, so unless the software fix is to ignore hardware interrupts (since a RESET is simply that, and the state of the output pins is unlikely to be known, or stable at reboot) for a few mS after reboot, I presume that a hardware fix is required.

  [1]: https://arduino.stackexchange.com/questions/1477/reset-an-arduino-uno-by-an-command-software
  [2]: https://arduino.stackexchange.com/questions/1477/reset-an-arduino-uno-by-an-command-software#answer-1478
  [3]: https://arduino.stackexchange.com/users/60/mpflaga
  [4]: https://arduino.stackexchange.com/users/6959/russell-mcmahon
  [5]: https://arduino.stackexchange.com/users/11/sachleen

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

Atmel specifically recommend against driving /RESET low from an output pin, because the first thing that the reset process does is set all pins to high impedance, thus cancelling the reset pulse before the recommended reset pulse length has elapsed.

The recommended use of the watchdog timer does not suffer from these limitations. It is *designed* to reset the board (or there would be no purpose to having it) and it does a proper reset (unlike jumping to address 0x0000).

---

### Reference

[Atmel knowledge base - Software Reset](http://atmel.force.com/support/articles/en_US/FAQ/Software-Reset)

> If you want to perform a software reset of your AVR you should use the internal Watchdog. Simply enable it and let it time out. When the Watchdog triggers it resets the program counter back to 0, clears all the registers and performs all the other tasks. This operation gives the same result as pulling the RESET line low.
>
> You should not try to:
>
>   - Use another pin of the AVR to pull the external RESET line. The pins of the AVR are tristated halfway through the minimum reset time, this releases the RESET line and hence nothing happens.
>
>   - Jump to program location 0. Jumping to program location 0 does not clear all the registers and hence you do not have a "clean" reset.

---

Their suggested code to reset the processor:

    #include <avr/io.h>
    #include <avr/wdt.h>

    #define Reset_AVR() wdt_enable(WDTO_30MS); while(1) {}

    int main(void)
    {
    Reset_AVR();
    }


message:
Read an analog signal without changing it? Or should I start over?

![The kettle, spark core, relay][1]

Hi! I'm still working on [my kettle project](https://arduino.stackexchange.com/questions/13364/reading-a-photoresistor). I want to obtain the kettle temp from the existing thermometer. I'm able to do this, but much like trying to look at an electron my circuits all reduce the voltage going to the kettle control board. This means the kettle's microcontroller ([SN8P2722  SONiX][2]) acts as if the kettle is cooler than it really is.

![5v control board.][3]

I don't think there is an *easy* way to program this microcontroller (if there is I'd love to know) -- I suspect the bad temp data will lead to overheating and hot water all over my kitchen.

![enter image description here][4]

Is there any way to passively obtain the voltage? I've been looking into the way that voltmeters work. Is this the right idea? is there a breakout board for this?

I really wanted to have the existing buttons still work as they always have. I've done this with power. I can press it remotely or on the kettle and I can tell of the kettle is on or off both on the control panel and remotely.

![enter image description here][5]

I can press all the other buttons remotely but I can't tell if it's working without knowing the kettle temp.

Maybe I should try to replace the entire control board? What would be easier? I'm something of a beginner.

  [1]: https://i.stack.imgur.com/vdrgJ.jpg
  [2]: http://www.atech.com.tw/\product\sonix\8bit\SN8P27 Series\SN8P2722_V11.pdf
  [3]: https://i.stack.imgur.com/S2LGM.jpg
  [4]: https://i.stack.imgur.com/OLk5N.jpg
  [5]: https://i.stack.imgur.com/uutUW.jpg

body: A JFET op amp such as the TL071 has an input impedance in the hundreds of gigaohms or higher. Using one to buffer the voltage should allow you to sample it without much interference to the existing circuit.


message:
Arduino code cannot continute process

Two days ago, my code is working fine on the arduino board. But yesterday, and today I tried so many time to upload the arduino code, which contains 1000 lines of code. It was successfully uploaded the code into arduino. But it only upload half code into arduino when I saw the serial monitor results (I use serial println(); test where the code is located. ) I am so confusing, why the code is working fine two days ago. but later, only half code being used. Please help.

Here is the memory I left when I uploaded it.

Sketch uses 48,314 bytes (19%) of program storage space. Maximum is 253,952 bytes.
Global variables use 2,603 bytes (31%) of dynamic memory, leaving 5,589 bytes for local variables. Maximum is 8,192 bytes.

    Here is the code it stuck :
       Get Parameters
    //
    //  This function reads the information from the SD card for a given monitoring
    //  site.
    //
//

    int getParameters(){
      String lowerLimit, upperLimit;

       char buffer[36];
      char newChar;
      int index, index1, index2, index3, line, theLength, numSensors;
      myFile.setTimeout(2000);
      line = 0;
      while (myFile.available()) {
        index = 0;
        do{
          newChar = myFile.read();
          buffer[index] = newChar;
          index += 1;
        }
        while(newChar != 10);
        buffer[index] = 0;
        theLines[line] = buffer;
        Serial.print(theLines[line]);
        //here the result is something like this
        //theLines[0] , class 111
        //theLines[1] , 192.168.1.10
        //theLines[2] , Mac Address

        line += 1;
      }

    //so it is working fine above the code. But here is the problem stuck.
    //the code cannot go through the rest of the code below. Nothing happened!!!
      for (int line = 0; line < 10; line++){
        Serial.print(theLines[line]);

      }

body:
A portion of your code is shown below.

      myFile.setTimeout(2000);
      ....
      while (myFile.available()) {
        index = 0;
        do {
          newChar = myFile.read();
          buffer[index] = newChar;
          index += 1;
        } while(newChar != 10);
       ....
      }

Apparently your code is accepting and printing several lines of option setting text and then hangs up in the code extract shown above.

Suppose, for example, one extra character appears after the supposedly-last linefeed character.  Your `while (myFile.available())` loop will run again.  It will store the extra character, then try to read another character.  If another character isn't available, `newChar = myFile.read();` will return a -1 that your code will store.  That will happen repeatedly,  clobbering RAM.

To see if this is what's happening, you could change `while(newChar != 10);` to (eg) `while(newChar != 10 && index<36);`.  If the code then stops hanging up, look into where the extra character is coming from.


message:
Implementing DES or AES Encryption with DateTime Synchronization on Uno

We are trying to implement AES or DES encryption using an Arduino Uno.

We have a keypad module attached that will be used to input integers. A String should be generated based on the entered data and encrypted using AES or DES.

We have tried several online libraries with no success due to the constraints put on the "plain text" size.

An example pseudo-code for the above:

    string key = "This is a key";
    string plain = "This is the keypad input" + keypadInput + "and some other random stuff"; <- This should have any size.

    var cipher = AES.encode(plain, key);
    print(cipher);

    var decoded = AES.decode(cipher, key);
    print(decoded);

Could someone please point to the right direction on how to do this?

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

> We have no experience with the byte[] objects and whatnot.

Might be time to do a few tutorials. You won't get far programming if you don't learn how to use arrays.

The **string** class is part of the STL (Standard Template Library) which does not come pre-installed on the Arduino (however you can download it if you want to).

[The Standard Template Library (STL) for AVR with C++ streams ](http://andybrown.me.uk/ws/2011/01/15/the-standard-template-library-stl-for-avr-with-c-streams/)

---

Briefly, however you could do something like this:

    char key [20] = "This is a key";
    char keypadInput [16];  // whatever they entered

    char plain[80];

    strcpy (plain, "This is the keypad input");
    strcat (plain, keypadInput);
    strcat (plain, "and some other random stuff");

The example code doesn't have any size checking. You would want to make sure that you don't put more than 79 characters into "plain" (to allow for the terminating 0x00 character). For example, look up **strncat**.

---

> Can you please elaborate on how DES or AES as described in the question can be implemented?

Have you done much research? Have you Googled `Arduino AES encryption` like I just did? I got this as the first hit:

[Topic: new AES library - Arduino Forum](http://forum.arduino.cc/index.php?topic=88890.0)

> I've written an AES (Advanced Encryption Standard) library for Arduino.  It supports 128, 192 and 256 bit key sizes.  Code space overhead is about 4KB I think, each instance requires 240 bytes RAM for subkeys.  Fairly tightly coded and checked against official test vectors for ECB mode.  Also CBC mode supported.

---

> It seems that if value of plain is larger than 16 characters the library will encrypt the first 16 characters only... Is this an Arduino Uno limitation?

I don't want to seem unhelpful, but you really should do some research before asking these questions. From [Wikipedia - Advanced Encryption Standard (AES)](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard):

> AES is a variant of Rijndael which has a fixed block size of 128 bits, and a key size of 128, 192, or 256 bits.

A "fixed block size of 128 bits" means you encrypt 128 bits at a time, that is, `128/8 = 16 bytes`.

So no, it is not an Arduino Uno limitation, it is the way AES works.

---

Also see [Wikipedia - DES](https://en.wikipedia.org/wiki/Data_Encryption_Standard).

>  In the case of DES, the block size is 64 bits.

So DES does 8 bytes at a time.

---

What you can do with a password is to **hash** it, for example: [Secure Hash Algorithm](https://en.wikipedia.org/wiki/Secure_Hash_Algorithm) or [MD5](https://en.wikipedia.org/wiki/MD5) (amongst others). These algorithms take a variable length string and return a fixed "hash". In the case of MD5 the output is a 128-bit field.

You could then encrypt that 128-bit hash, if you want to keep it a secret.

---

> Would encrypting the 16 bytes and then append the next 16 bytes and so on result to the same output as if the whole plain text was encrypted in the first place in one go?

The suggestion by @BrettAM was, if you want to encrypt more than 16 bytes, do them 16 bytes at a time, padding if necessary the final block.

eg.

    AAAAAAAAAAAAAAAA BBBBBBBBBBBBBBBB CCCCCCCCCC000000
          encrypt        encrypt          encrypt
    LLLLLLLLLLLLLLLL MMMMMMMMMMMMMMMM NNNNNNNNNNNNNNNN
          decrypt        decrypt          decrypt
    AAAAAAAAAAAAAAAA BBBBBBBBBBBBBBBB CCCCCCCCCC000000

In this example the final block was padded with zeros. Now the receiving end decrypts in 16-byte blocks.


message:
deprecated conversion from string constant to 'char*'

What does this error means?
I can't solve it in any way.
> warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

body:
Either stop trying to pass a string constant where a function takes a `char*`, or change the function so that it takes a `const char*` instead.

String like "random string" are constants.


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

Example:

    void foo (char * s)
      {
      Serial.println (s);
      }

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();
      foo ("bar");
      }  // end of setup

    void loop ()
      {
      }  // end of loop

Warning:

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

    sketch_jul14b.ino: In function ‘void setup()’:
    sketch_jul14b.ino:10: warning: deprecated conversion from string constant to ‘char*’

The function `foo` expects a char* (which it can therefore modify) but you are passing a string literal, which should not be modified.

The compiler is warning you not to do this. Being deprecated it might turn from a warning into an error in a future compiler version.

---

Solution: Make foo take a **const** char *:

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

    void foo (const char * s)
      {
      Serial.println (s);
      }

---

>  I don't get it. Do you mean *can not* be modified?

Older versions of C (and C++) let you write code like my example above. You could make a function (like `foo`) that prints something you pass down to it, and then pass down a literal string (eg. `foo ("Hi there!");`)

However a function that takes `char *` as an argument is allowed to modify its argument (ie. modify `Hi there!` in this case).

You might have written, for example:

    void foo (char * s)
      {
      Serial.println (s);
      strcpy (s, "Goodbye");
      }

Unfortunately, by passing down a literal, you have now potentially modified that literal so that "Hi there!" is now "Goodbye" which is not good. In fact if you copied in a longer string, you might overwrite other variables. Or, on some implementations you would get an access violation because "Hi there!" might have been put in read-only (protected) RAM.

So the compiler-writers are gradually [deprecating](https://en.wikipedia.org/wiki/Deprecation) this usage, so that functions to which you pass down a literal, must declare that argument as `const`.


body:
As is my wont, I'm going to provide a bit of background technical information into the whys and wherefores of this this error.

I'm going to inspect four different ways of initializing C strings and see what the differences between them are.  These are the four ways in question:

    char *text = "This is some text";
    char text[] = "This is some text";
    const char *text = "This is some text";
    const char text[] = "This is some text";

Now for this I am going to want to change the third letter "i" into an "o" to make it "Thos is some text".  That could, in all cases (you would think), be achieved by:

    text[2] = 'o';

Now let's look at what each way of declaring the string does and how that `text[2] = 'o';` statement would affect things.

First the most commonly seen way: `char *text = "This is some text";`.  What does this literally mean?  Well, in C, it literally means "Create a variable called `text` which is a read-write pointer to this string literal which is held in read-only (code) space.".  If you have the option `-Wwrite-strings` turned on then you get a warning as seen in the question above.

Basically that means "Warning: You have tried to make a variable that is read-write point to an area you can't write to".  If you try and then set the third character to "o" you would in fact be trying to write to a read-only area and things won't be nice.  On a traditional PC with Linux that results in:

> Segmentation Fault

Now the second one: `char text[] = "This is some text";`.  Literally, in C, that means "Create an array of type "char" and initialize it with the data "This is some text\0". The size of the array will be big enough to store the data".  So that actually allocates RAM and copies the value "This is some text\0" into it at runtime.  No warnings, no errors, perfectly valid.  And the right way to do it *if you want to be able to edit the data*.  Let's try running the command `text[2] = 'o'`:

> Thos is some text

It worked, perfectly.  Good.

Now the third way: `const char *text = "This is some text";`.  Again the literal meaning: "Create a variable called "text" that is a *read only* pointer to this data in read only memory.".  Note that both the pointer and the data are now read-only.  No errors, no warnings. What happens if we try and run our test command?  Well, we can't.  The compiler is now intelligent and knows that we are trying to do something bad:

> error: assignment of read-only location ‘*(text + 2u)’

It won't even compile.  Trying to write to read-only memory is now protected because we have told the compiler that our pointer is to read-only memory.  Of course, it doesn't *have* to be pointing to read-only memory, but if you point it to read-write memory (RAM) that memory will still be protected from being written to by the compiler.

Finally the last form: `const char text[] = "This is some text";`.  Again, like before with `[]` it allocates an array in RAM and copies the data into it.  However, now this is a read-only array.  You can't write to it because the pointer to it is tagged as `const`.  Attempting to write to it results in:

> error: assignment of read-only location ‘*(text + 2u)’

So, a quick summary of where we are:

This form is completely invalid and should be avoided at all costs.  It opens the door to all sorts of bad things happening:

    char *text = "This is some text";

This form is the right form if you are wanting to make the data editable:

    char text[] = "This is some text";

This form is the right form if you want strings that won't be edited:

    const char *text = "This is some text";

This form seems wasteful of RAM but it does have its uses.  Best forget it for now though.

    const char text[] = "This is some text";


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

To elaborate on Makenko's excellent answer, there is a good reason why the compiler warns you about this. Let's make a test sketch:

    char *foo = "This is some text";
    char *bar = "This is some text";

    void setup ()
      {
      Serial.begin (115200);
      Serial.println ();
      foo [2] = 'o';     // change foo only
      Serial.println (foo);
      Serial.println (bar);
      }  // end of setup

    void loop ()
      {
      }  // end of loop

We have two variables here, foo and bar. I modify **one** of those in setup(), but see what the result is:

    Thos is some text
    Thos is some text

They **both** got changed!

In fact if we look at the warnings we see:

    sketch_jul14b.ino:1: warning: deprecated conversion from string constant to ‘char*’
    sketch_jul14b.ino:2: warning: deprecated conversion from string constant to ‘char*’

The compiler knows this is dodgy, and it is right! The reason for this is, that the compiler (reasonably) expects that string constants don't change (since they are constants). Thus if you refer to the string constant `"This is some text"` multiple times in your code it is allowed to allocate the **same** memory to all of them. Now if you modify one, you modify all of them!


body:
I have this compilation error:

    TimeSerial.ino:68:29: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
       if(Serial.find(TIME_HEADER)) {

                             ^

Please replace this line:
`#define TIME_HEADER  "T"   // Header tag for serial time sync message`

with this line:
`#define TIME_HEADER  'T'   // Header tag for serial time sync message`

and compilation goes well.


message:
Empty char variable

How do I empty all the values inside a variable `char array[256];`?

I tried a for loop assigning an empty value at each iteration, but it doesn't compile.

body:
    char array[256];

    ...

    int i;
    for( i=0; i<256;i++ ) {
        array[i] = 0x00;
    }


body:
There is a single-line command you can use:

    memset(array, 0, 256);


message:
Issue with time-dependant conditional I/O control flow (Arduino UNO)

We are working on a project to control the reaction of a system to a lever, whose position is monitored by two IR sensors at the ends of its travel, the Reward sensor and the Trigger sensor.

There are three modes of action:

Mode1: lever has to start at TriggerSensor, and a success is recorded if and when the lever is moved to RewardSensor

Mode2: lever starts at TriggerSensor and has to be held for 4 seconds. At the end of this interval a tone is played for 2 seconds, the reward interval. Within this 2 seconds, if the lever is moved to the RewardSensor, a success is recorded.

Mode3: same as Mode2, but the initial 4 second timeout is of random length.

We also want to use the following lines:

`digitalWrite(TriggerSensorOut, digitalRead(TriggerSensorIn));  //This is to record to our computer the states of the trigger sensor
  digitalWrite(RewardSensorOut, digitalRead(RewardSensorIn));  //This is to record to our computer the states of the reward sensor`

to constantly write the state of both sensors to our computer. However, this doesn't work as planned: there are delays between the execution of the mode functions (as described in full code below).Essentially, we are struggling to come up with a suitable way to time things correctly.

Please see full code below

    // -----LIBRARIES

    //#include <elapsedMillis.h>

    // ----CONSTANTS (won't change)

    const int TriggerSensorIn = 2;   //  Input from trigger sensor, LOW = broken
    const int RewardSensorIn = 3;    //  Input from reward sensor, LOW = broken
    const int ModeStateIn1 = 4;      //  Input 1 from switch to define paradigm mode
    const int ModeStateIn2 = 5;      //  Input 2 from switch to define paradigm mode
    const int RewardSignalOut = 12;   //  Output signal of reward, parallel taken off to counter module
    const int ServoResetOut = 6;     //  Servo reset output signal
    const int ToneOut = 10;          //  Audio stimulus
    const int TriggerSensorOut = 7;  //  Output from trigger sensor for DAC board recording
    const int RewardSensorOut = 8;   //  Output from reward sensor for DAC board recording

    //------- VARIABLES (will change)

    boolean backPressed = false;

    int timeoutWindow = 4000;    // 4 second preliminary interval
    int rewardWindow = 2000;    // 2 second reward interval

    unsigned long currentMillis = 0;

    //===============

    void setup() {

      // initialise the digital pins as inputs and outputs

      pinMode(TriggerSensorIn, INPUT);
      pinMode(RewardSensorIn, INPUT);
      pinMode(ModeStateIn1, INPUT);
      pinMode(ModeStateIn2, INPUT);

      pinMode(RewardSignalOut, OUTPUT);
      pinMode(ServoResetOut, OUTPUT);
      pinMode(ToneOut, OUTPUT);
      pinMode(TriggerSensorOut, OUTPUT);
      pinMode(RewardSensorOut, OUTPUT);

    }

    //===============

    void giveReward() {
      // This function is the protocol for recording a reward
      currentMillis=millis();
      digitalWrite(RewardSignalOut, HIGH);
      while (millis()>currentMillis+200) {
        digitalWrite(RewardSignalOut, LOW);
      }
    }

    //===============

    void servoReset() {
      // This function is the protocol for resetting servos after a failed action
      currentMillis=millis();
      digitalWrite(ServoResetOut, HIGH);
      while (millis()>currentMillis+200) {
        digitalWrite(ServoResetOut, LOW);
      }
    }

    //===============

    void mode1() {
      // This function is the protocol for controlling the system during mode 1, no time constraint on the action
      if (digitalRead(TriggerSensorIn == LOW)) {
        backPressed = true;

        if (backPressed == true && digitalRead(RewardSensorIn == LOW)) {
          giveReward();
          backPressed = false;
        }
      }
    }

    //===============

    void mode2() {
      if (digitalRead(TriggerSensorIn == LOW)) {
        currentMillis=millis();
        while (digitalRead(TriggerSensorIn == LOW)) {
          while (millis() > currentMillis + timeoutWindow) {
            tone(ToneOut, 3000, 2000);
            {
              goto rewardSeeking2;
            }
          }
        }

    rewardSeeking2:
        currentMillis=millis();  // reset timer
        if (millis() < (currentMillis + rewardWindow) && digitalRead(RewardSensorIn == LOW)) {
          giveReward();
        }
        else if (millis() > (currentMillis + rewardWindow)) {
          servoReset();
        }
      }
    }

    //===============

    void mode3() {
      timeoutWindow=random(1000,5000);
      if (digitalRead(TriggerSensorIn == LOW)) {
        currentMillis=millis();
        while (digitalRead(TriggerSensorIn == LOW)) {
          while (millis() > currentMillis + timeoutWindow) {
            tone(ToneOut, 3000, 2000);
            {
              goto rewardSeeking3;
            }
          }
        }

    rewardSeeking3:
        currentMillis=millis();  // reset timer
        if (millis() < (currentMillis + rewardWindow) && digitalRead(RewardSensorIn == LOW)) {
          giveReward();
        }
        else if (millis() > (currentMillis + rewardWindow)) {
          servoReset();
        }
      }
    }

    //===============

    void loop() {

      digitalWrite(TriggerSensorOut, digitalRead(TriggerSensorIn));  //This is to record to our computer the states of the trigger sensor
      digitalWrite(RewardSensorOut, digitalRead(RewardSensorIn));  //This is to record to our computer the states of the reward sensor

      if (digitalRead(ModeStateIn1) == LOW && digitalRead(ModeStateIn2) == LOW) {
        // Using the two mode selective switches to define mode1
        mode1();
      }

      else if (digitalRead(ModeStateIn1) == LOW && digitalRead(ModeStateIn2) == HIGH) {
        // Using the two mode selective switches to define mode2
        mode2();
      }

      else if (digitalRead(ModeStateIn1) == HIGH && digitalRead(ModeStateIn2) == LOW)  {
        // Using the two mode selective switches to define mode3
        mode3();
      }
    }

    //===============END

body:
This is a snippet of how I would refactor the code:

    void mode3() {
      int timeout = millis() + random(1000,5000);
      while (digitalRead(TriggerSensorIn == LOW) &&
             millis() < timeout) {
      };
      if (digitalRead(TriggerSensorIn == LOW) &&
             millis() > timeout) {
         tone(ToneOut, 3000);
         timeout = millis() + rewardWindow;
         while (millis() < timeout)
           if (digitalRead(RewardSensorIn == LOW)
             giveReward();
      }
      noTone();
    }

....

    void loop() {
      // This is to record to our computer the states of
      // the trigger sensor
      digitalWrite(TriggerSensorOut, digitalRead(TriggerSensorIn));

      // This is to record to our computer the states of
      // the reward sensor
      digitalWrite(RewardSensorOut, digitalRead(RewardSensorIn));

      int msin1 = digitalRead(ModeStateIn1);
      int msin2 = digitalRead(ModeStateIn2);

      if (msin1 == LOW)
          if (msin2 == LOW)
              mode1();
          else
              mode2();
      else if (msin2 == LOW)
        mode3();
    }

But I think you should first try to write it down in plain English and verify that at least that algo works.
Then you can think how to transpose it into code.


message:
Two motors in one set of pins/plugs

I have been putting together a small robot using an Arduino Motor Shield R3. The shield has two sockets for motors, however the wheel carriage I bought has four motors. I tried putting both right side motors in one socket set, and the left side motors in the other socket set.

When I turn on the Arduino, the left side motors turn together according to how I coded the board, however the right side behaves differently.

One of the motors does not start. If I push it a little it will start turning. Though not always. When I plugged in the misbehaving motor by itself, it runs correctly.

I am wondering about cause of the problem here. Is it likely the second motor on the right side is faulty? Or am I trying to use up too much power and disrupting the current?

body:
The drive capacity of the Motor Shield should match the motors – two of the motors. The shield was probably designed for a load of one motor, and you're giving two, so it is possible that neither of the motors on that side is getting enough current to get started. Here are somethings to check to get started:

 1. Find the drive capacity of the Motor Shield and compare it to the motors (if you don't have specs for the motors you could measure the current they draw if you have an DMM). It might be wise to measure the current anyway, just in case you have a defective motor or shield.
 2. If the capacity or the current draw is out of line, that's your problem. You can probably just add a power transistor to the circuit to drive the motors in this case.
 3. Try it with just one motor on each output and see if they run normally. If they do, that would suggest a loading problem or a defective motor or shield. You can sort out which is which by swapping sides – if one motor runs and the other doesn't, swap them. If the problem follows the motor, then blame the motor, otherwise blame the shield.


message:
Arduino Uno powers off when circuit plugged in to +5V and GND pins

I have a max7219 driving an 8 digit 7 segment LED array with forward current of 20mA and typical forward voltage of 1.85V. I'm trying to power this through my arduino UNO (which itself is drawing power from USB), and have the max7219 chip's +5V and ISet(+resistor) and ground pins connected to the respective pins on the arduino.  When I try to plug this in, the arduino will not power up, but removing the jumpers from +5V and GND allows the arduino to power up.

I have confirmed with my multimeter that there is no short between any of the power cables on my led circuit.

The voltage supplied by the arduino works normally if I connect it up to a simple resistor and led on a breadboard.

The voltage across the +5V & GND pins on the arduino drops from 5V to 0V if the jumpers are inserted whilst the arduino is powered up.

I thought perhaps the circuit was trying to draw too much power from the USB, so tried higher resistor values than my initial resistor (20K), to no effect.

What else could be causing this?

body:
>  and have the ... ISet(+resistor) and ground pins connected to the respective pins on the arduino.

*What* pin on the Arduino?

The ISet resistor should go to +5 V - don't connect it to an Arduino pin (unless you mean the +5 V Arduino pin). See diagram:

![MAX7219 wiring for 7-segment display][1]

I had a 7-segment display working fine on an Arduino via the USB, see photo:

![7-segment display with Arduino][2]

More details here: [Interfacing LED displays with the MAX7219 driver](http://www.gammon.com.au/forum/?id=11516)

  [1]: https://i.stack.imgur.com/iyDN7.png
  [2]: https://i.stack.imgur.com/OSkof.jpg


message:
Console monitor on different wifi network

I have a Yun doing data logging. It runs nicely and when I am on the same wifi network I can use the Console Monitor to watch what it is doing in more detail. However, my arduino is deployed far from me so it generally isn't possible to get on the same wifi network to monitor the console.

Is there a way to monitor the console from a different wifi network?

body:
The Yun is just an ordinary network device.  However, the tools you are provided with use a system called mDNS to find the Yun.  That only works across the same local subnet that you are on.

If the Yun is on a different subnet then you will have to (assuming the routing between subnets is working fine) do it manually by knowing the IP address of your Yun.  Use that IP address in place of "arduino.local" or whatever your Yun is called.


message:
Disabling i2c internal pull up resistors

How do you do this? I've been digging around and I can see that I should do this and supply my own external pull up resistors but I don't know exactly how to disable them. The pages I've been reading never explicity state how.

I'm trying to enable I2C between a leonardo and an uno, but I think the i2c bus is slowing down considerably because of the internal pullups. I want to switch to two 4.7k resistors but I can't figure out how to disable the internal ones. I know that the Wire library enables the internals by default, but how do I edit the library or disable the pullups in my sketch?

Maybe I just haven't been reading the right forums or articles, but if anyone could point me in the right direction that would be much appreciated.

EDIT: So the problem is probably with my setup or code, I'll put it down here. Everything I have before setup is importing libraries and variables like my mac, ip, placeholders for output, pwm, etc.

Master:

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      while(!Serial){
      }

      Wire.begin();

      Ethernet.begin(mac, ip);
      delay(1000);

      server.begin();
      if(server.available()){
        Serial.println("Client Available");
      }
    }

    void loop() {
      // put your main code here, to run repeatedly:

      ethernetwrite();

    }

    void ethernetwrite() {
      EthernetClient client = server.available();
      while(client) {
        if(client.find("P")) {
          output = client.parseInt();
          pwm = client.parseInt();

          Serial.println("Begin Transmitting");
          Wire.beginTransmission(14);
          Wire.write(output);
          Wire.write('\t');
          Wire.write(pwm);
          Wire.endTransmission();
          Serial.println("Done Transmitting");

          Serial.print(output);
          Serial.print('\t');
          Serial.println(pwm);

        }
      }
    }

Slave:

    void setup() {
      Wire.begin(14);
      Wire.onReceive(wirewrite);

    // *   - Base frequencies:
    // *      o The base frequency for pins 3, 9, 10, and 11 is 31250 Hz.
    // *      o The base frequency for pins 5 and 6 is 62500 Hz.
    // *   - Divisors:
    // *      o The divisors available on pins 5, 6, 9 and 10 are: 1, 8, 64,
    // *        256, and 1024.
    // *      o The divisors available p1on pins 3 and 11 are: 1, 8, 32, 64,
    // *        128, 256, and 1024.

        // Leg 1
        pinMode(leg[1], OUTPUT); setPwmFrequency(leg[1],8); analogWrite(leg[1], offset);

        // Leg 2
        pinMode(leg[2], OUTPUT); setPwmFrequency(leg[2],8); analogWrite(leg[2], offset);

        // Leg 3
        pinMode(leg[3], OUTPUT); setPwmFrequency(leg[3],8); analogWrite(leg[3], offset);

        // Leg 4
        pinMode(leg[4], OUTPUT); setPwmFrequency(leg[4],8); analogWrite(leg[4], offset);

        // Mirror
        pinMode(leg[0], OUTPUT); setPwmFrequency(leg[0],clkdivisor); analogWrite(leg[0], 255);
    }

    void loop() {

        int time = 10;
        time = time*128/clkdivisor;

        // box(time, 255, 1); // box(delay time, radius pwm, pwm step size);
        // autodisplay();
        updateL();

    }

    void updateL(){
      if (output == 0) pwm = 255 - pwm;
      switch (output) {
        case 1: pin =  3; break;
        case 2: pin =  9; break;
        case 3: pin =  10; break;
        case 4: pin =  11; break;
        case 0: pin = 5; break;
      }
      //if (output < 5) {
        analogWrite(pin, pwm);
      //}
    }

    void wirewrite(int numBytes) {
      String message;
      while(Wire.available()>0) {
        char c = Wire.read();
        message.concat(c);
      }
      output = Wire.parseInt();
      pwm = Wire.parseInt();
    }

When I send data to the master, on the serial monitor it freezes in the first wiring transmission or in the next few, and my slave doesn't seem to respond to the message being sent over i2c. My controls for my device and setup worked prior to my attempts with the Wire library, so there's no problem there.

EDIT: I also am sending a message that looks like this:
"P1 103"
every .4 seconds or so, but I usually can't get past the first transmission between the arduinos

body:
From the datasheet:

> Note that the internal pull-ups in the AVR pads can be enabled by setting the PORT bits corresponding to the SCL and SDA pins, as explained in the I/O Port section.

To disable the internal pull-ups:

    digitalWrite(A4, LOW);
    digitalWrite(A5, LOW);

or

    digitalWrite(2, LOW);
    digitalWrite(3, LOW);


body:
Let's go back to basics. A low-value pull-up resistor actually improves the shape of the I2C clock and data.

---

### One internal pull-up:

![I2C with one internal pull-up resistor][1]

---

### Both ends with the internal pull-up:

![I2C with two internal pull-up resistors][2]

---

### 10 k external pull-up:

![I2C with 10 k external pull-up][3]

---

### 4.7 k external pull-up:

![I2C with 4.7 k external pull-up][4]

---

### 2.2 k external pull-up:

![I2C with 2.2 k external pull-up][5]

---

As Majenko pointed out, leaving the internal pull-ups enabled would give you a pull-up between 4.7 k and 2.2 k. And as my screenshots show, that is perfectly acceptable.

In fact, it is probably better. See the nice square signals?

---

So your hypothesis that the pull-up is responsible for it running slowly is not supported.

You need to post your code, and other details, such as the length of the cable runs.

> I think the i2c bus is slowing down considerably ...

What do you mean "slowing down"? Compared to what? What are your figures? What is the transmission time? What do you expect it to be? Some facts please.

---

## Reference

[My page about I2C](http://www.gammon.com.au/i2c)

  [1]: https://i.stack.imgur.com/tPDqD.png
  [2]: https://i.stack.imgur.com/0Ldtd.png
  [3]: https://i.stack.imgur.com/jHiPf.png
  [4]: https://i.stack.imgur.com/WeSgG.png
  [5]: https://i.stack.imgur.com/QebED.png


message:
TinyGPS (Plus) Library

Is there a particular function in the library TinyGPS or TinyGPS Plus which outputs the raw NMEA sentences? I couldn't find anything about it on the website guide of the library.

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

There doesn't seem to be, but what you could do is print each character as it arrives. From their example code:

      while (nss.available())
      {
        if (gps.encode(nss.read()))    // <--- pass to TinyGPS
          return true;
      }

So, change that to be:

      while (nss.available())
      {
        char c = nss.read();  // <--- get the incoming character
        Serial.print (c);     // <--- print it
        if (gps.encode(c))    // <--- now pass it to TinyGPS
          return true;
      }


message:
AES Simplified for Arduino - Having hard time achieving desired result

Okay, here's the story. I'm not **very** familiar with how Arduino works but learning. I have a project that requires AES encryption on the Arduino Uno. As per a previous question we managed to figure out the problem but failed to resolve it fully so we started using another library. (This one: https://github.com/qistoph/ArduinoAES256)

`  uint8_t key[] = { //
    0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
    0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
    0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
    0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f
  };`

Now onto the problem itself. Using an online AES encryption tool such as: http://aesencryption.net/ Simply asks for a `Key of the encryption` in **plain text** and the output is `base64` as specified by the service here: `The result of the encryption will appear in base64 encoded to prevent character encoding problems.
`
Also, **plain text** can be used to process the encryption using `AES` algorithm.

I've been trying to achieve the exact same result using an `Arduino Uno` board with the exact same requirements. The end result is to have a `base64` string that can be decrypted on another remote location having the same `key`.

Now as for the `.ino` file it has this setup:

    #include "aes256.h" //Include library files
    #define DUMP(str, i, buf, sz) { Serial.println(str); \
        for(i=0; i<(sz); ++i) { if(buf[i]<0x10) Serial.print('0'); Serial.print(char(buf[i]), HEX); } \
        Serial.println(); } //Help function for printing the Output

    aes256_context ctxt;

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

      Serial.println("Initializing AES256... ");
      uint8_t key[] = { //
        0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
        0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
        0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
        0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f
      };
      DUMP("Key: ", i, key, sizeof(key));
      aes256_init(&ctxt, key);

      uint8_t data[] = { //"asdfasdfasdfasdf"
        0x61, 0x73, 0x64, 0x66, 0x61, 0x73, 0x64, 0x66,
        0x61, 0x73, 0x64, 0x66, 0x61, 0x73, 0x64, 0x66
      };
      DUMP("Unencrypted data: ", i, data, sizeof(data));

      aes256_encrypt_ecb(&ctxt, data);
      DUMP("Encrypted data: ", i, data, sizeof(data));

      aes256_decrypt_ecb(&ctxt, data);
      DUMP("Back decrypted data: ", i, data, sizeof(data));

      aes256_done(&ctxt);
    }

    void loop() {
    }

---

### 1) I can't seem to understand what is required to have a `plain text` key and `plain text` message to encrypt giving an end result of `base64` output.

For example if I were to do this using `JavaScript`: (And this is just an example).

---

### 2) I'd like to achieve something like this:

    var key = "32 characters plain text here";
    var plain = "Unlimited characters text here that can be used by the library to encrypt this plain message variable";
    var base64_output = aes.encrypt256(key, plain);

---

### 3) **I'd like to have the base64_output as base64 string so that it can be printed on a third-party printer hooked to the Arduino.** - Is this impossible to achieve? We've been trying for some time now from endless conversions to splitting up our `plain` text into chunks of 16 characters so that we can encrypt the message.

---

Any help is greatly appreciated. If someone doesn't mind us contacting them over the phone we would also greatly appreciate a phone call to have this issue explained and resolve so we can share our experience with the Arduino community.

Thanks in advance.

## edit:

We're getting this error
![enter image description here][1]

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

## edit2:
Thank you @Nick Gammon for the quick response.
After removing const from the function 4 places and the `key` variable declaration, everything seems to be working fine now.
We modified the code in order to print all bytes for each cipher block. We have this output:

    140 145 154 38 228 66 98 128 116 68 245 193 70 84 205 115
    Œ‘š&äBb€tDõÁFTÍsŒ‘š&äBb€tDõÁFTÍs
    186 174 17 21 162 83 96 210 128 134 46 206 172 215 0 103
    º®¢S`Ò€†.Î¬×
    112 4 216 150 27 202 6 176 77 159 123 231 127 128 32 132
    pØ–Ê°MŸ{ç€ „pØ–Ê°MŸ{ç€ „
    215 110 118 33 167 193 212 121 156 46 63 139 183 124 63 152
    ×nv!§ÁÔyœ.?‹·|?˜×nv!§ÁÔyœ.?‹·|?˜
    130 91 174 118 4 202 250 74 228 7 173 40 246 124 53 173
    ‚[®vÊúJä(ö|5‚[®vÊúJä(ö|5
    231 48 204 82 235 172 202 139 33 134 137 81 209 191 210 217
    ç0ÌRë¬Ê‹!†‰QÑ¿ÒÙç0ÌRë¬Ê‹!†‰QÑ¿ÒÙ
    184 161 98 135 12 230 86 213 183 113 103 234 187 213 224 133
    ¸¡b‡æVÕ·qgê»Õà…¸¡b‡æVÕ·qgê»Õà…
    Done

We're trying to convert each array of bytes into a `char` array of hex values then base_64 encode it.  But we're getting this output which is not what we want. Can you please explain how can we achieve this.
Please let us know if it is possible to open a chat with you so that we can understand this better.

body:
If you don't have to have the features of the String object, I'd highly recommend you use a uint8_t (or 'byte' or 'char') array from the get-go. It avoids the conversion altogether, as well as the code complexities of dealing with Strings.

`uint8_t plain = "Hello World";` works great for a literal string, or if you need more flexibility, `uint8_t plain[256+1] = "Hello World";` lets you use or re-use that space for whatever strings you need to hold at run-time (pick a size appropriate for your needs, obviously). Will that let you get past the conversion road-block to focus on encryption (about which, I'd be no help at all).


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

> We've been trying for some time now from endless conversions to splitting up our plain text into chunks of 16 characters so that we can encrypt the message.

To address this question/issue, below is some code that will take an arbitrary length string and break it into 16-character strings suitable for encoding with AES:

    const int KEY_SIZE = 32;
    const int BLOCK_SIZE = 16;
    const char message [] = "Unlimited characters text here that can be used by the library to encrypt this plain message variable";
    const byte key [KEY_SIZE] = "32 characters plain text here";

    void encrypt_it (const byte plaintext [BLOCK_SIZE], const byte cipherkey [KEY_SIZE]);  // prototype
    void encrypt_it (const byte plaintext [BLOCK_SIZE], const byte cipherkey [KEY_SIZE])
      {
      // encrypt here
      }

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

      const char * p = message;

      while (strlen (p) > 0)
        {
        byte plain [BLOCK_SIZE];
        memset (plain, 0, BLOCK_SIZE);  // ensure trailing zeros
        // copy block into plain array
        memcpy (plain, p, min (strlen (p), BLOCK_SIZE));
        // encrypt it
        encrypt_it (plain, key);
        // advance past this block
        p += min (strlen (p), BLOCK_SIZE);
        }
      Serial.println ("Done");
      }  // end of setup

    void loop ()
      {
      }  // end of loop

---

>  I'd like to have the base64_output as base64 string so that it can be printed on a third-party printer hooked to the Arduino. - Is this impossible to achieve?

Of course it is possible. Just look up (Google) a C or C++ function to base-64 encode a string. There must be thousands of them. This is not an Arduino question, this is a C programming question.

---

>  As per a previous question we managed to figure out the problem but failed to resolve it fully ...

Namely here: [Implementing DES or AES Encryption with DateTime Synchronization on Uno](https://arduino.stackexchange.com/questions/13426/implementing-des-or-aes-encryption-with-datetime-synchronization-on-uno).

This question actually looks remarkably similar to your previous one.


body:
> 2) I'd like to achieve something like this:
>
> ```
> var key = "32 characters plain text here";
> var plain = "Unlimited characters text here that can be used by the library to encrypt this plain message variable";
> var base64_output = aes.encrypt256(key, plain);
> ```

So do it.

    #define MAX_MESSAGE_SIZE 256
    uint8_t key[] = "32 characters plain text here";
    uint8_t plain[MAX_MESSAGE_SIZE+1] = "Unlimited characters text here that can be used by the library to encrypt this plain message variable";
    aes256_init(&ctxt, key);
    aes256_encrypt_ecb(&ctxt, plain);
    // plain is now encrypted.

That is limited to a maximum message (and encrypted output) size of 256 bytes due to the (purely arbitrary) size of the array I chose.


message:
Connect the Sparkfun CAN bus shield with an RFduino

I have a problem which I am working on for some days now. I do have knowledge in electronics, but not extensively. I also posted this question in the [RFduino Forum](http://forum.rfduino.com/index.php?topic=1146.0) but couldn't get any good answers.

What I am trying to do: I want to connect the Sparkfun CAN bus shield to the RFduino. I am using the code further below. It compiles without problem and **does work** with my Arduino Leonardo!

I used a logic analyser (ignore the filled shapes, some display error) to further narrow down the problem and found the following on the **RFduino**:
![Picture of the logic analyser on the RFduino](https://i.stack.imgur.com/yNB30.png)

On the **Leonardo**, it looks different:
![Picture of the logic analyser on the Leonardo](https://i.stack.imgur.com/JhnnI.png)

It seems like I don't get a response on the MISO line! I played around with different speeds, but nothing seemed to work.

I do have a suspicion however: The RFduino works with 3.3V, while the Leonardo works with 5V. So the logic signals on the RFduino can only achieve 3.3V P-P. I confirmed this with my old CRO, LOW is at GND and HIGH at 3.3V. The Leonardo has 5V P-P.
On page 70 of the datasheet for the MCP2515 (the chip used on the shield), it says that the supply voltage VDD ranges from 2.7V to 5.5V. So supply voltage should be ok. V_INPUT_HIGH ranges from 2.31 to 4.3V. V_INPUT_LOW ranges from -0.3V to 0.495V. I am in this range! Similarly so for the V_OUTPUT_LOW (up to 0.6V) and V_OUTPUT_HIGH (at least 2.8V). Could this nevertheless be a problem?

What would you try or change?

[MCP2515 Datasheet](http://ww1.microchip.com/downloads/en/DeviceDoc/21801d.pdf)

    #include <SPI.h>

    // demo: CAN-BUS Shield, send data
    #include <mcp_can.h>

    MCP_CAN CAN0(SS);                                      // Set CS to pin 10

    unsigned char stmp[8] = {0, 1, 0, 3, 0, 5, 0, 7};

    void setup()
    {
      Serial.begin(115200);
      while (!Serial) {
        ;                  // wait for serial port to connect. Needed for Leonardo only
      }
      // init can bus, baudrate: 500k
      if(CAN0.begin(CAN_500KBPS) == CAN_OK) Serial.print("can init ok!!\r\n");
      else Serial.print("Can init fail!!\r\n");
                   // send data per 100ms
    }

    void loop()
    {
    //    // send data:  id = 0x00, standrad flame, data len = 8, stmp: data buf
    //  CAN0.sendMsgBuf(0x00, 0, 8, stmp);
    }

body:
It is difficult to tell whether your chip select is working correctly or not with the logic analyzer view.  Have you tried hooking it up to an o-scope to capture what the CS is actually doing(in the analog world)?

What cabling have you chosen between the CAN and arduino?

If you get the o-scope out, you may want to check the MISO and MOSI for ringing, which may lead back to cabling.


body:
Ok, I found the solution. The fix first: I had to **physically connect the reset line from the RFduino to the MCP2515 reset pin.**
On page 55 in the datasheet of the MCP2515 it says that you can either reset it by pulling the reset line low or by sending a command over the SPI. The library I used is sending this reset command, but it isn't working for some reason. The logic analyser shows me this signal, it is the first recorded. Maybe it is a timing issue, that the reset has to be sent at the same time as the RFduino resets. Connecting the reset pin solves this issue, because then the RFduino and the MCP2515 are being reset at the same time.
If anybody knows more about this, feel free to tell me!


message:
MQTT client on Arduino + SIM900

I have used the [pubsubclient library][1] for Arduino for communicating with an MQTT broker in the past, however the library works only with Ethernet connecction. I need to use GSM in my application and am using the SIM900 at the moment. However, I cannot seem to find any library for MQTT communication using an Arduino as MQTT client and SIM900 as gateway. I found this to be surprising as there must surely be many instances where one would want to upload data from Arduino to a MQTT broker in a mobile scenario where cellular network is the only option (in place of Ethernet). So my questions are:

1. Is it possible to use the Arduino as MQTT client and SIM900 as gateway for communicating with an MQTT broker? Are there any libraries for the same?
2. What is the current standard way (gateway / communication protocol) of uploading some sensor data from Arduino to an internet server in a mobile scenario (i.e., where Ethernet is not an option)?

  [1]: https://github.com/knolleary/pubsubclient/tags

body:
 1. MQTT by definition is a TCP/IP protocol, so if you don't have a TCP/IP stack, then it is a no go.
 2. A common pattern/infrastructure in the IoT is to have your "things" connect to a hub of some kind (via BLE, XBee, or ... etc.) and then the hub will connect to the network and post the data. Another option would be to get a cellular device that provides a data connection (i.e. 2G/3G) and therefore a TCP/IP stack. It looks like the SIM900 only supports calls and texts, and as of this moment I am not aware of such a device that has libraries for Arduino.


body:
The SIM900 allows creation of TCP sockets through an AT style command language, so this addresses point #1 of the previous comments concern.

This is only half the story though, you'll still need to learn how to create the requests, and handle the responses of the MQTT protocol using the SIM900's protocol.

There may be usable examples to start from in the ESP8266 community, as their style of TCP API looks similar to the SIM900.


body:
Take a look at the FONA library from Adafruit.

https://github.com/adafruit/Adafruit_MQTT_Library/blob/master/examples/mqtt_fona/

The FONA Library uses SIM800 which is a newer version of SIM900. You will find MQTT and FONA within the same library. They also run an MQTT Broker service in adafruit.io


body:
MQTT Library for SIM800 GSM Modem is available at [ElementzTechBlog][1], [ElementzGithubRepository][2]

**Functionalities:**

**Auto connect**

       Automatically connect to TCP and to MQTT server.
**connect function**

       This function can be used to connect your client to MQTT broker.
       Use only if you do not use Auto connect functionality.
       Optionally  you can use username, password, WILL topic and WILL Message.
**OnConnect CallBack function**

       This call back function is called when MQTT connection is established.
       You can call subscription and publish functions inside it (according to your need).

**publish function**

       This function can be used to publish messages to different topics.
       You can select  QoS levels and RETAIN flag according to your need.
**subscribe function**

       This function can be used to subscribe messages from different topics.
**OnMessage CallBack function**

       This callback function is called when messages are received from  subscribed topics
       Topic, TopicLength, Message, MessageLength are the arguments of  OnMessage callback function.
       Inside this, you can write your custom code.
**unsubscribe function**

       This function can be used to unsubscribe from a previously subscribed topic.
**disconnect function**

       This function can be used to disconnect your client from MQTT broker.
**Keep Alive**

       You can specify your KeepAlive duration while initializing.
       Ping requests are sent and received automatically.

  [1]: https://elementztechblog.wordpress.com/2016/07/18/arduino-mqtt-library-for-sim800-gsm-modem/
  [2]: https://github.com/elementzonline/SIM800_MQTT
  [3]: http://elementzonline.com/

**Update**

Nowadays the easiest solution is to use SIM7600 4G/3G/2G modem. It supports MQTT using AT commands !. For more details the following link can be useful to get started.

https://www.elementzonline.com/blog/using-mqtt-at-commands-with-sim7600-and-arduino-for-gsm-iot-projects


body:
These tutorials should help on getting started with MQTT on SIM900 or SIM800.

MQTT Protocol tutorial - LIVE DEMO using Mosquitto and CloudMQTT
https://youtu.be/Oh3ZYAQBTko

This video explains about the main important control packets of MQTT protocol by explaining what each byte in a MQTT packet means and also shows how to send and receive data using TCP and Websockets UI of CloudMQTT.com Control panel. We also learn on  how to use the Mosquitto Open source broker on Windows machine to Publish and subscribe to MQTT message and topics on localhost and to cloud servers with and without Authentication.

MQTT Protocol tutorial using SIM900/SIM800 modules - LIVE DEMO
https://youtu.be/dcpMa2UwEeA

This video demonstrates how you can use the light weight MQTT protocol on the SIM900 or SIM800 GSM modules using TCP over the GPRS connection. Here you will learn, how you can use the SIM900/SIM800 TCP commands to send and receive messages as a publisher and a subscriber in almost realtime.


message:
Arduino Xbee AT command mode

I have 2 Xbee Series 2 modules.
One of it is connected to arduino via an adapter. And Ground 5V, as well as Rx>>Tx and Tx>>Rx.

The xbee is configured AT mode Coordinator.

I want to use the serial monitor in arduino to change the parameters of the xbee, such as DH or DL or PAN ID things like this.

Is there a way for the xbee to display its "OK" response after entering command mode on the serial monitor?

body:
Not if you have it connected to pins 0 and 1, no.  You should not use those pins for anything unless you absolutely have to, since they are what are used for communication with the PC.  You can't do both communication with the PC and with the XBee using the same pins.

You should ensure that the XBee is connected to one of the other serial ports on the Mega and then write a sketch that passes the data through from one port to the other as needed so you can view it on the serial monitor.


body:
Because you have an Arduino Mega, you can set it up to use it like a USB-to-UART adapter by using the following code ([source][1]):

    void setup() {
      // initialize both serial ports:
      Serial.begin(9600);
      Serial1.begin(9600);
    }

    void loop() {
      // read from port 1, send to port 0:
      if (Serial1.available()) {
        int inByte = Serial1.read();
        Serial.write(inByte);
      }

      // read from port 0, send to port 1:
      if (Serial.available()) {
        int inByte = Serial.read();
        Serial1.write(inByte);
      }
    }

Basically what this does is it takes the data it receives from the USB port via `Serial` and transmits it to `Serial1` and then also reads from the UART port via `Serial1` and transmits it back to the computer via `Serial`. With this code running you should be able to hook up the XBee to RX1 and TX1 and communicate to it using the Serial Monitor.

  [1]: https://www.arduino.cc/en/Tutorial/MultiSerialMega