message:
Update Dynamically Tkinter Widget Scale from Arduino Ports using python and firmata

I'm having trouble trying to get Arduino digital ports values and set these values into a Python Tkinter Widget Scale.

I'm using Python and Arduino with Firmata.  I'm able to access my arduino board with python code.  For example in a label widget I'm getting and setting Arduino analog port value in real-time to a label as in following code without any problems:

<!-- language: lang-py -->

    import Tkinter
    import pyfirmata

    def onStartButtonPress():
        while True:
            if flag.get():
                analogReadLabel.config(text=str(a0.read()))
                analogReadLabel.update_idletasks()
                top.update()
            else:
                break
        board.exit()
        top.destroy()

    def onExitButtonPress():
        flag.set(False)

    port = 'COM7'
    board = pyfirmata.Arduino(port)

    it = pyfirmata.util.Iterator(board)
    it.start()

    a0 = board.get_pin('a:0:i')

    top = Tkinter.Tk()
    top.title("Reading Analog pins")

    descriptionLabel = Tkinter.Label(top, text="Potentiometer input:- ")
    descriptionLabel.grid(column=1, row=1)

    analogReadLabel = Tkinter.Label(top, text="Press Start..")
    analogReadLabel.grid(column=2, row=1)

    flag = Tkinter.BooleanVar(top)
    flag.set(True)

    startButton = Tkinter.Button(top, text="Start", command=onStartButtonPress)
    startButton.grid(column=1, row=2)

    exitButton = Tkinter.Button(top, text="Exit", command=onExitButtonPress)
    exitButton.grid(column=2, row=2)

    top.mainloop()

Up to this point it's okay and the GUI shows me something like:

![Python Gui interface reading real-time value from analog 0][1]

But what I'm trying to do and not getting is:

![What I'm trying to update Scale with digital pins][2]

Here is the code:

<!-- language: lang-py -->

    import Tkinter
    import pyfirmata
    import serial;

    def onStartButtonPress():
        while True:
            if flag.get():
                analogReadLabel.config(text=str(d8.read()))
                analogReadLabel1.config(text=str(d9.read()))
                analogReadLabel2.config(text=str(d10.read()))
                analogReadLabel.update_idletasks()

            pos1 = d8.read()
            if pos1 == True:
                pos1 = int(pos1)
                pos1 = 0
                brightnessScale.set(pos1)

            pos2 = d9.read()
            if pos2 == True:
                pos2 = int(pos2)
                pos2 = 100
                brightnessScale.set(pos2)

           ''' and so on '''

            brightnessScale.update_idletasks()
            top.update()
        else:
            break
    board.exit()
    top.destroy()

    def onExitButtonPress():
        flag.set(False)

    port = 'COM7'
    board = pyfirmata.Arduino(port)

    it = pyfirmata.util.Iterator(board)
    it.start()

    a0 = board.get_pin('a:0:i')

    d4 = board.get_pin('d:4:i')
    d5 = board.get_pin('d:5:i')
    d6 = board.get_pin('d:6:i')
    d7 = board.get_pin('d:7:i')
    d8 = board.get_pin('d:8:i')
    d9 = board.get_pin('d:9:i')
    d10 = board.get_pin('d:10:i')

    top = Tkinter.Tk()
    top.geometry("800x600")
    top.title("Reading Analog pins")

    descriptionLabel = Tkinter.Label(top, text="Potentiometer input:- ")
    descriptionLabel.grid(column=1, row=1)

    analogReadLabel = Tkinter.Label(top, text="Level 1")
    analogReadLabel.grid(column=2, row=1)

    analogReadLabel1 = Tkinter.Label(top, text="Level 2")
    analogReadLabel1.grid(column=3, row=1)

    analogReadLabel2 = Tkinter.Label(top, text="Level 3")
    analogReadLabel2.grid(column=4, row=1)

    brightnessScale = Tkinter.Scale(top, from_ = 500,
                                to = 0,
                                length = 500,
                                width = "30",
                                tickinterval = 50,

                                bg = "lightskyblue",
                                highlightcolor = "darkblue",
                                highlightbackground = "royalblue",
                                troughcolor = "darkblue",

                                state = Tkinter.DISABLED,
                                sliderlength = 50,
                                relief = "sunken",
                                label = "Volume do Reservatorio em %",
                                orient = Tkinter.VERTICAL)
    brightnessScale.grid(column=1, row=5)
    Tkinter.Label(top,text="Volume da Caixa em (%)").grid(column=1, row=6)

    flag = Tkinter.BooleanVar(top)
    flag.set(True)

    startButton = Tkinter.Button(top, text="Start", command=onStartButtonPress)
    startButton.grid(column=1, row=2)

    exitButton = Tkinter.Button(top, text="Exit", command=onExitButtonPress)
    exitButton.grid(column=2, row=2)

    top.mainloop()

To summarize: I have reed switches in each digital port declared in the code.  These reed switches are normally open state, when I put a magnetic field near them it turn to close and I get a change in that value like from False to True.  What I'm trying to do is update the Tkinter Scale Widget in real time as the labels but I'm not getting it.

Is there any trick in python code that can solve my problem ? Because I did a lot of research on the internet and I could not get done, as you can see in image 2 when the state of the second digital pin changes, a label changes to True, and in the scale code this corresponds to the value 100, but it's still on the 0 mark.

I'm not comfortable also with the usage of command, and variable parameters of scale widget.

In short, I want to update in real time python Tkinter scale widget according to values from digital ports from arduino using firmata.

I'm using Python 2.7

PS: for completeness:

This is my arduino code (Sketch) without firmata, which is working as expected.

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

    int level;
    int position;

    void setup() {

    pinMode(8, INPUT);
    pinMode(9, INPUT);
    pinMode(10, INPUT);
    pinMode(11, INPUT);
    pinMode(12, INPUT);

    Serial.begin(9600); // ativa a porta serial

    void loop() {
    digitalWrite(8, LOW);
    digitalWrite(9, LOW);
    digitalWrite(10, LOW);
    digitalWrite(11, LOW);
    digitalWrite(12, LOW);

    position = digitalRead(8);
    if ( position == HIGH) {level=0;}

    position = digitalRead(9);
    if ( position == HIGH) {Level=100;}

    position = digitalRead(10);
    if ( position == HIGH) {level=200;}

    position = digitalRead(11);
    if ( position == HIGH) {level=300;}

    position = digitalRead(12);
    if ( position == HIGH) {level=400;}

    Serial.println(level);
    delay(500);

    }

What I could do also here
is get these values via serial in python and use them to update the scale in this way but I don't know if in this method it's gonna work also!

And what I thought in Python:
But I still have much to learn in algorithms and Data Structures.
Just the Pseudo Code:

<!-- language: lang-py -->

    def setScaleValue():
 while True:
        if flag.get():
          pos1 = d4.read()
            if pos1 == True: #or 1
            #Here is the problem i don't know for sure what comes in my digital port
            #If is a True bool or a 1 as HIGH value from arduino
            #And probably i don't know if it's possible to change the values of a scale in this way !!!
            #or if i'm mistaken the Cast stuff in Python
                pos1 = int(pos1)
                pos1 = 0
                brightnessScale.set(pos1)

            pos2 = d8.read()
            if pos2 == True:
                pos2 = int(pos2)
                pos2 = 100
                brightnessScale.set(pos2)

            brightnessScale.update_idletasks()
            top.update()
        else:
            break
    board.exit()
    top.destroy()

 return

    d4 = board.get_pin('d:4:i')
    d5 = board.get_pin('d:5:i')
    d6 = board.get_pin('d:6:i')
    d7 = board.get_pin('d:7:i')
    d8 = board.get_pin('d:8:i')

    brightnessScale = Tkinter.Scale(top, from_ = 500,
                                to = 0,
                                length = 500,
                                width = "30",
                                tickinterval = 50,

                                bg = "lightskyblue",
                                highlightcolor = "darkblue",
                                highlightbackground = "royalblue",
                                troughcolor = "darkblue",

                                state = Tkinter.DISABLED,
                                sliderlength = 50,
                                relief = "sunken",
                                label = "Volume do Reservatorio em %",
                                orient = Tkinter.VERTICAL)
    brightnessScale.grid(column=1, row=5)
    Tkinter.Label(top,text="Volume da Caixa em (%)").grid(column=1, row=6)

  [1]: https://i.stack.imgur.com/wNfXQ.png
  [2]: https://i.stack.imgur.com/udb6v.png

body:
in your code:

    pos2 = d8.read()
    print("pos2 is {} type {}".format(pos2, type(pos2)))  # This way, you'll know the var type you're getting on the console
        if posX == True:
            posX = int(posX)          # You then cast to an integer
            posX = 100                # You discard pos2 value by setting it to 100
            brightnessScale.set(posX) # You set the scale always to value 100

By adding the print line, you can ensure the variable value and type.
Then, you may have to adapt your if statement accordingly.
Beware what you're doing then with those 2 lines reaffecting posX, this is probably not what you want to do before updating the scale.


sender: user

message:
Simple URL decoding

How can I do a readable, small, smart and good URL decoder in Arduino?

Now I'm using this code:

    String GetRidOfurlCharacters(String urlChars)
    {

      urlChars.replace("
", String('\n'));

      urlChars.replace("+",   " ");
      urlChars.replace(" ", " ");
      urlChars.replace("!", "!");
      urlChars.replace(""", String(char('\"')));
      urlChars.replace("#", "#");
      urlChars.replace("$", "$");
      urlChars.replace("%", "%");
      urlChars.replace("&", "&");
      urlChars.replace("'", String(char(39)));
      urlChars.replace("(", "(");
      urlChars.replace(")", ")");
      urlChars.replace("*", "*");
      urlChars.replace("+", "+");
      urlChars.replace(",", ",");
      urlChars.replace("-", "-");
      urlChars.replace(".", ".");
      urlChars.replace("/", "/");
      urlChars.replace("0", "0");
      urlChars.replace("1", "1");
      urlChars.replace("2", "2");
      urlChars.replace("3", "3");
      urlChars.replace("4", "4");
      urlChars.replace("5", "5");
      urlChars.replace("6", "6");
      urlChars.replace("7", "7");
      urlChars.replace("8", "8");
      urlChars.replace("9", "9");
      urlChars.replace(":", ":");
      urlChars.replace(";", ";");
      urlChars.replace("<", "<");
      urlChars.replace("=", "=");
      urlChars.replace(">", ">");
      urlChars.replace("?", "?");
      urlChars.replace("@", "@");
      urlChars.replace("A", "A");
      urlChars.replace("B", "B");
      urlChars.replace("C", "C");
      urlChars.replace("D", "D");
      urlChars.replace("E", "E");
      urlChars.replace("F", "F");
      urlChars.replace("G", "G");
      urlChars.replace("H", "H");
      urlChars.replace("I", "I");
      urlChars.replace("J", "J");
      urlChars.replace("K", "K");
      urlChars.replace("L", "L");
      urlChars.replace("M", "M");
      urlChars.replace("N", "N");
      urlChars.replace("O", "O");
      urlChars.replace("P", "P");
      urlChars.replace("Q", "Q");
      urlChars.replace("R", "R");
      urlChars.replace("S", "S");
      urlChars.replace("T", "T");
      urlChars.replace("U", "U");
      urlChars.replace("V", "V");
      urlChars.replace("W", "W");
      urlChars.replace("X", "X");
      urlChars.replace("Y", "Y");
      urlChars.replace("Z", "Z");
      urlChars.replace("[", "[");
      urlChars.replace("\", String(char(65)));
      urlChars.replace("]", "]");
      urlChars.replace("^", "^");
      urlChars.replace("_", "_");
      urlChars.replace("`", "`");
      urlChars.replace("a", "a");
      urlChars.replace("b", "b");
      urlChars.replace("c", "c");
      urlChars.replace("d", "d");
      urlChars.replace("e", "e");
      urlChars.replace("f", "f");
      urlChars.replace("g", "g");
      urlChars.replace("h", "h");
      urlChars.replace("i", "i");
      urlChars.replace("j", "j");
      urlChars.replace("k", "k");
      urlChars.replace("l", "l");
      urlChars.replace("m", "m");
      urlChars.replace("n", "n");
      urlChars.replace("o", "o");
      urlChars.replace("p", "p");
      urlChars.replace("q", "q");
      urlChars.replace("r", "r");
      urlChars.replace("s", "s");
      urlChars.replace("t", "t");
      urlChars.replace("u", "u");
      urlChars.replace("v", "v");
      urlChars.replace("w", "w");
      urlChars.replace("x", "x");
      urlChars.replace("y", "y");
      urlChars.replace("z", "z");
      urlChars.replace("{", String(char(123)));
      urlChars.replace("|", "|");
      urlChars.replace("}", String(char(125)));
      urlChars.replace("~", "~");
      urlChars.replace("", "Â");
      urlChars.replace("�", "`");
      urlChars.replace("�", "Â");
      urlChars.replace("�", "â");
      urlChars.replace("�", "Æ");
      urlChars.replace("�", "â");
      urlChars.replace("�", "â¦");
      urlChars.replace("�", "â");
      urlChars.replace("�", "â¡");
      urlChars.replace("�", "Ë");
      urlChars.replace("�", "â°");
      urlChars.replace("�", "Å");
      urlChars.replace("�", "â¹");
      urlChars.replace("�", "Å");
      urlChars.replace("�", "Â");
      urlChars.replace("�", "Å½");
      urlChars.replace("�", "Â");
      urlChars.replace("�", "Â");
      urlChars.replace("�", "â");
      urlChars.replace("�", "â");
      urlChars.replace("�", "â");
      urlChars.replace("�", "â");
      urlChars.replace("�", "â¢");
      urlChars.replace("�", "â");
      urlChars.replace("�", "â");
      urlChars.replace("�", "Ë");
      urlChars.replace("�", "â¢");
      urlChars.replace("�", "Å¡");
      urlChars.replace("�", "âº");
      urlChars.replace("�", "Å");
      urlChars.replace("�", "Â");
      urlChars.replace("�", "Å¾");
      urlChars.replace("�", "Å¸");
      urlChars.replace("�", "Â");
      urlChars.replace("�", "Â¡");
      urlChars.replace("�", "Â¢");
      urlChars.replace("�", "Â£");
      urlChars.replace("�", "Â¤");
      urlChars.replace("�", "Â¥");
      urlChars.replace("�", "Â¦");
      urlChars.replace("�", "Â§");
      urlChars.replace("�", "Â¨");
      urlChars.replace("�", "Â©");
      urlChars.replace("�", "Âª");
      urlChars.replace("�", "Â«");
      urlChars.replace("�", "Â¬");
      urlChars.replace("�", "Â®");
      urlChars.replace("�", "Â¯");
      urlChars.replace("�", "Â°");
      urlChars.replace("�", "Â±");
      urlChars.replace("�", "Â²");
      urlChars.replace("�", "Â³");
      urlChars.replace("�", "Â´");
      urlChars.replace("�", "Âµ");
      urlChars.replace("�", "Â¶");
      urlChars.replace("�", "Â·");
      urlChars.replace("�", "Â¸");
      urlChars.replace("�", "Â¹");
      urlChars.replace("�", "Âº");
      urlChars.replace("�", "Â»");
      urlChars.replace("�", "Â¼");
      urlChars.replace("�", "Â½");
      urlChars.replace("�", "Â¾");
      urlChars.replace("�", "Â¿");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã¡");
      urlChars.replace("�", "Ã¢");
      urlChars.replace("�", "Ã£");
      urlChars.replace("�", "Ã¤");
      urlChars.replace("�", "Ã¥");
      urlChars.replace("�", "Ã¦");
      urlChars.replace("�", "Ã§");
      urlChars.replace("�", "Ã¨");
      urlChars.replace("�", "Ã©");
      urlChars.replace("�", "Ãª");
      urlChars.replace("�", "Ã«");
      urlChars.replace("�", "Ã¬");
      urlChars.replace("�", "Ã");
      urlChars.replace("�", "Ã®");
      urlChars.replace("�", "Ã¯");
      urlChars.replace("�", "Ã°");
      urlChars.replace("�", "Ã±");
      urlChars.replace("�", "Ã²");
      urlChars.replace("�", "Ã³");
      urlChars.replace("�", "Ã´");
      urlChars.replace("�", "Ãµ");
      urlChars.replace("�", "Ã¶");
      urlChars.replace("�", "Ã·");
      urlChars.replace("�", "Ã¸");
      urlChars.replace("�", "Ã¹");
      urlChars.replace("�", "Ãº");
      urlChars.replace("�", "Ã»");
      urlChars.replace("�", "Ã¼");
      urlChars.replace("�", "Ã½");
      urlChars.replace("�", "Ã¾");
      urlChars.replace("�", "Ã¿");

      return urlChars;
    }

However I want to make a loop and only replace a url escaping if it exists, not trying to replace all the (possible) occurrences.

sender: assistant

body:
The fact that you're using a String (urgh, shudder shudder... you should read this: http://hacking.majenko.co.uk/the-evils-of-arduino-strings) actually makes it a little harder to work with.  Instead you should have your String data in a character array ("C string"). Then a parser is much easier to write using a pair of character pointers.

Basically the theory is you scan from the start of the string to the end of the string using both pointers copying characters as you go, and as soon as you hit a `%` you read ahead 2 characters using the first pointer (the second pointer stays where it is) and you convert the two read characters as hex into the ASCII equivalent and use the second pointer to replace the `%`.

Then both pointers keep moving forward, but they stay out of step. As each `%` crops up the pointers get further and further out of step until you reach the end of the string and all the `%xx` have been replaced with a single character.

For instance, this code I have just knocked up does the job:

    char data[50] = "http://foo/bar?x=hello there: majenko";

    // Create two pointers that point to the start of the data
    char *leader = data;
    char *follower = leader;

    // While we're not at the end of the string (current character not NULL)
    while (*leader) {
        // Check to see if the current character is a %
        if (*leader == '%') {

            // Grab the next two characters and move leader forwards
            leader++;
            char high = *leader;
            leader++;
            char low = *leader;

            // Convert ASCII 0-9A-F to a value 0-15
            if (high > 0x39) high -= 7;
            high &= 0x0f;

            // Same again for the low byte:
            if (low > 0x39) low -= 7;
            low &= 0x0f;

            // Combine the two into a single byte and store in follower:
            *follower = (high << 4) | low;
        } else {
            // All other characters copy verbatim
            *follower = *leader;
        }

        // Move both pointers to the next character:
        leader++;
        follower++;
    }
    // Terminate the new string with a NULL character to trim it off
    *follower = 0;

The `data` array now contains:

    http://foo/bar?x=hello there: majenko


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

I wrote a [Tiny web server](http://www.gammon.com.au/forum/?id=12942) for the Arduino which has a similar thing in it. You might find it useful for your project. Inside there is a function that decodes the URL codes on-the-fly (ie. in a state machine). The code is a bit different to Majenko's because he assumes that you have the string in memory. In my case I am decoding a byte at a time (so you don't have to hold a long string in memory before you decode it).

The snippet that does the decoding is this:

      // percent-encoding: possible states
      enum EncodePhaseType {
        ENCODE_NONE,
        ENCODE_GOT_PERCENT,
        ENCODE_GOT_FIRST_CHAR,
      };
      // percent-encoding: current state
      EncodePhaseType encodePhase;
      byte encodeByte;  // encoded byte being assembled (first nybble)

...

    // ---------------------------------------------------------------------------
    // add a character to the value buffer - percent-encoded (if wanted)
    // ---------------------------------------------------------------------------
     void HTTPserver::addToValueBuffer (byte inByte, const bool percentEncoded)
      {
      if (valueBufferPos >= MAX_VALUE_LENGTH)
        {
        flags |= FLAG_VALUE_BUFFER_OVERFLOW;
        return;
        }  // end of overflow

      // look for stuff like "foo+bar" (turn the "+" into a space)
      // and also "foo!bar" (turn ! into one character)
      if (percentEncoded)
        {
        switch (encodePhase)
          {

          // if in "normal" mode, turn a "+" into a space, and look for "%"
          case ENCODE_NONE:
            if (inByte == '+')
              inByte = ' ';
            else if (inByte == '%')
              {
              encodePhase = ENCODE_GOT_PERCENT;
              return;  // no addition to buffer yet
              }
            break;

          // we had the "%" last time, this should be the first hex digit
          case ENCODE_GOT_PERCENT:
            if (isxdigit (inByte))
              {
              byte c = toupper (inByte) - '0';
              if (c > 9)
                c -= 7;  // Fix A-F
              encodeByte = c << 4;
              encodePhase = ENCODE_GOT_FIRST_CHAR;
              return;  // no addition to buffer yet
              }
            // not a hex digit, give up
            encodePhase = ENCODE_NONE;
            flags |= FLAG_ENCODING_ERROR;
            break;

          // this should be the second hex digit
          case ENCODE_GOT_FIRST_CHAR:
            if (isxdigit (inByte))
              {
              byte c = toupper (inByte) - '0';
              if (c > 9)
                c -= 7;  // Fix A-F
              inByte = encodeByte | c;
              }
            else
              flags |= FLAG_ENCODING_ERROR;

            // done with encoding it, or not a hex digit
            encodePhase = ENCODE_NONE;

          } // end of switch on encodePhase
        } // end of percent-encoded

      // add to value buffer, encoding has been dealt with
      valueBuffer [valueBufferPos++] = inByte;
      valueBuffer [valueBufferPos] = 0;  // trailing null-terminator
      } // end of HTTPserver::addToValueBuffer


message:
ATmega 8 wrong timing with Arduino NG bootloader

I have build simple Arduino ISP programmer, which works fine on ATmega 328 chips (when I select Arduino UNO board) and a ton of others (tiny45, tiny2313). But, when I want to program an ATmega8 chip, it writes it succesfuly, but then the chip runs at 1/16 of the desired speed! (for example a delay(1000) in code takes 16 seconds real-life). I have a 16 MHz crystal oscillator with capacitors connected to the chip, so I thought that the problem is not there but... when I remove the crystal, the chip still runs the same, it still takes 16 seconds.
So I assume two possibilities:

 1. the crystal is somehow broken, so the chip runs from some internal
    thing? But I tried multiple crystals, all the same,

OR

 2. I am doing something wrong, but I really don't know what...

Does somebody have an idea what may be wrong or how to test it? Or feel free for more details...Thanks

EDIT: In IDE, I am selecting "Arduino NG or older" and then I select ATmega8  as processor. I am uploading the sketches directly, without bootloader.

body: Ok, I finally solved it, so I will write it here so somebody may learn from it in the future :) The problem was really in the fuses, thanks Chris Stratton. Most of my chips were bought already modified for working with Arduino. But this ATmega 8 had the factory fuses, which were setting it for working with internal 1MHz oscillator. You can read and your write your fuse settings with avrdude, so I set them to arduino default (lfuse 0xDF, hfuse 0xCA, from boards.txt). Now it works perfectly even without uploading bootloader.


message:
LCD 16*02 I2C shield only shows first character printed

I have an I2C LCD screen provided with a Sunfounder kit and certainly built by DFRobot or such a constructor (there is nothing written on the LCD), and an Arduino Uno R3 copy.

My issue is when I use `lcd.print()` to write a string on the LCD, only the **first character** of the string is printed. I can only print on other positions by using setCursor but only one character at a time.

I tried to change libraries ([https://github.com/fdebrabander/Arduino-LiquidCrystal-I2C-library][1], the one supplied with the LCD...), It always behaves the same!

For example, here's a very simplistic program which exhibits this behavior:

    #include <LiquidCrystal_I2C.h>

    LiquidCrystal_I2C lcd(0x27, 16, 2);
    // set the LCD address to 0x27 for a 16 chars and 2 line display
    void setup() {
      lcd.init();
      lcd.backlight();
    }

    void loop() {
      lcd.print("write");
      delay(1000);
      lcd.setCursor(10, 0);
      lcd.print("p10");
      lcd.setCursor(0, 1);
      lcd.print("0, 1 write");
      if((millis() / 1000) % 5 == 0) {
        lcd.clear();
        delay(1000);
      }
    }

I end up with something like:

    w      p
    0w

On the screen (before the `clear()` occurs of course).

Instead of something like:

    write  p10
    0, 1 writewrite

The lcd itself was ok some time ago. The only thing I could think is I recently updated to Arduino 1.6.6. Can it be a bug in the compiler?

[The hello world from DFRobot][2] also doesn't work properly (first char only, again) (please note to make it display something with my LCD I have to change the address from 0x20 to 27).

  [1]: https://github.com/fdebrabander/Arduino-LiquidCrystal-I2C-library "github"
  [2]: http://www.dfrobot.com/index.php?route=product/product&path=156_53&product_id=135 "The hello world from dfrobot"

body:
Your code contains, in part,

    #include <LiquidCrystal_I2C.h>
    ....
    LiquidCrystal_I2C lcd(0x27, 16, 2); // set the LCD address to 0x27 for a 16 chars and 2 line display
    void setup() {
      lcd.init();
      lcd.backlight();
    }

For all of the constructors in `LiquidCrystal_I2C.h` on my system, the second and third parameters are `EN` and `RW`, ie, the enable and read/write backpack-pin numbers.  They don't specify the size of the display.

I suggest trying constructor usage like

    LiquidCrystal_I2C lcd(0x27,2,1,0,4,5,6,7); // 0x27 is the I2C bus address for an unmodified backpack

and in place of `lcd.init();` say

    lcd.begin (16,2); // for 16 x 2 LCD module

Note, `lcd.begin()` will call `init()`.


body:
I'm incredibly new to Arduino (I literally got one a few hours ago and I'm still finding my feet with it!) so take that into account when considering anything I say however I'd be inclined to agree that this may be an issue with the 1.6.6 IDE.

I was getting pretty much the same symptoms on a Freematics MEGA2560/3.2" SSD1289 LCD using the MultiLCD library using 1.6.6. Based on your comment above I uninstalled and installed 1.6.5 instead, recompiled and uploaded and it's now displaying properly...


body:
That's definitely a bug appeared in 1.6.6.
For reference, see
https://blog.arduino.cc/2015/11/03/arduino-ide-1-6-6-released-and-available-for-download/#comment-278766
https://forum.arduino.cc/index.php?topic=359652.0
http://forum.arduino.cc/index.php?topic=357312.msg2476987#msg2476987

Last link seems to provide a solution, by a **updated version of LCD I2C lib** : https://github.com/marcoschwartz/LiquidCrystal_I2C (not yet tried).

The 1.6.6 is a bit messy according some people, but the I2C lib too ;). So the question is : where should it be fixed ?


body:
I tried the solution described by AFract and it solved the problem. (sorry, I couldn't reply to his comment because I don't have enough reputation.)

I got the new LiquidCrystal_I2C library here: https://github.com/marcoschwartz/LiquidCrystal_I2C

Info on the code commit is here: https://github.com/marcoschwartz/LiquidCrystal_I2C/pull/5


body:
I have had same problem, issued on v1.6.7 and v1.6.8. I solved it with the [new 'marcoschwartz' library][1] specified in other answers.

Previously, I had used the same DFRobot library, which worked fine on IDE 1.6.0, until I upgraded on v1.6.7.

  [1]: https://github.com/marcoschwartz/LiquidCrystal_I2C


body: I had the same problem. My LCD only showed one character. I downloaded and tryed docens of LCD libraries and ended up with a bunch of libraries installed in my IDE. After days trying to solve the problem I decided to clear my IDE deleting the libraries directory (mind that the IDE could take them from documents/arduino/library folder). After that I tested one by one the LCD libraries. I case it did not work I deleted it. The one posted above  https://github.com/marcoschwartz/LiquidCrystal_I2C worked!!.I don't really know where was the problem exactly, maybe a conflict among the libraries intalled.


message:
When it says the Uno has logic level at 5 V is that also true of a bareduino/breadboard Arduino?

I want to hook up ESP8266, which has a 3.3v logic level to my bare-bones Arduino (basically a minimal interface for the ATmega382P IC).

I can power my circuit at 3.3 V without a 5 V regulator so will the voltage of the logic level also be 3.3 V?

I don't think there is a tiny boost converter in the IC... but I'm uncertain.

body:
The logic level is the same as the voltage you supply the chip.

You can think of the IO pins as tiny switches that either connect the output pin to the supply voltage or to ground (when in output mode) or compare the incoming voltage to an input pin to a percentage of the supply voltage (typically <0.3×Vcc for low and >0.6Vcc for high)

So yes, if you run the chip at 3.3V the logic level will be 3.3V logic (or more specifically < 1.1v for low and > 2.2v for high).


message:
What killed it? Arduino in resin

I made a simple circuit controlled by the ATMEGA IC then tried to encase it in resin. It died. What is the thing that caused it to die? I've had other circuits working fine in resin. I want to try again, what steps can I take to prevent this?

I've looked for obvious shorts but can find none.

Resin heats up when it cures, could that be the issue?

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

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

body:
Potting of circuits can lead to various issues. It can't be told exactly what caused your device to fail until you uncover it like an archeologist.

Common problems are:

 - Resin entering a spring loaded contact and canceling out contact forces
 - Resin exsuding corrosive substances ruining contacts
 - Resin expanding during curing and opening spring contacts or even breaking up solder contacts
 - Same effect after cool down of resin

Later and often unexpected problems are:

 - thin gaps around potted objects (i.e. no surface contact) literally sucking in water.
 - potting material producing water itself during curing.

Many of these problems can be circumvented by applying conformal coating, as suggested by comments and apparently proven right by your experiments.
If it is not necessary refrain from using sockets and solder connections directly to the components. You won't be able to salvage them, anyway.


message:
Controlling relays with IR and button

What I have:

 - 1 x 8 channel relay
 - 1 x IR receiver
 - 1x Arduino Uno
 - 1x momentary switch
 - 1x breadboard
 - 1x 10K resister

I think the wiring is all ok as for the most part things are working as they should..ish.

Just a few bugs I need to fix.

The goal was to toggle just 2 relays (at the moment) on/off with the hardwired switch and individually toggle the a relay using an IR remote control.

Like I said this sort of works....

If I press the momentary button it does indeed toggle both relays...yeah!
then as long as the 2 relays are toggled to the on position by the momentary switch I can toggle each relay using buttons on a remote.

However if I turn the relays off with the momentary button I can't turn them on with the remote. Also if I turn off one of the relays with the remote and then press momentary switch it alternates the toggle between the 2 relays rather than just turning the other one off.

I have been using various example sketches to achieve all this and just trying to stitch them together as best I can but something is telling me that the approach is all wrong and that I should maybe be looking into Boolean's perhaps?

Hope you can shed some light on this for me.

<!-- language: c -->

    #include <IRremote.h>
    #define irPin 8
    IRrecv irrecv(irPin);
    decode_results results;
    const int buttonPin = 2;
    const int relay1 = 13;
    const int relay2 = 12;
    int relay1State;
    int relay2State;
    int buttonState;
    int lastButtonState;
    long lastDebounceTime = 0;
    long debounceDelay = 50;

    void setup() {
      Serial.begin(9600);
      irrecv.enableIRIn();
      pinMode(buttonPin, INPUT);
      pinMode(relay1, OUTPUT);
      pinMode(relay2, OUTPUT);
      digitalWrite(relay1, relay1State);
      digitalWrite(relay2, relay2State);
    }

    void loop() {
      if (irrecv.decode(&results)) {
        switch (results.value) {
          case 0xFF30CF:
            Serial.println("Button 1 Pressed");
            relay1State = ~relay1State;
            digitalWrite(relay1, relay1State);
            delay(250);
            break;
          case 0xFF18E7:
            Serial.println("button 2 pressed");
            relay2State = ~relay2State;
            digitalWrite(relay2, relay2State);
            delay(250);
            break;
        }
        irrecv.resume();
      }

      int reading = digitalRead(buttonPin);
      if (reading != lastButtonState) {
        lastDebounceTime = millis();
      }
      if ((millis() - lastDebounceTime) > debounceDelay) {

        if (reading != buttonState) {
          buttonState = reading;

          if (buttonState == HIGH) {
            relay1State = !relay1State;
            relay2State = !relay2State;
          }
        }
      }

      digitalWrite(relay1, relay1State);
      digitalWrite(relay2, relay2State);
      lastButtonState = reading;
    }

body:
So according to your comments this should be the code if no mistake was made

<!-- language: c -->

    #include <IRremote.h>
    #define irPin 8
    IRrecv irrecv(irPin);
    decode_results results;
    const int buttonPin = 2;
    const int relay1 = 13;
    const int relay2 = 12;
    int relay1State = 0;
    int relay2State = 0;
    int masterState = 0;
    int buttonState;
    int lastButtonState;
    long lastDebounceTime = 0;
    long debounceDelay = 50;

    void setup() {
      Serial.begin(9600);
      irrecv.enableIRIn();
      pinMode(buttonPin, INPUT);
      pinMode(relay1, OUTPUT);
      pinMode(relay2, OUTPUT);
      digitalWrite(relay1, relay1State);
      digitalWrite(relay2, relay2State);
    }

    void loop() {
      if (irrecv.decode(&results)) {
        switch (results.value) {
          case 0xFF30CF:
            Serial.println("Button 1 Pressed");
            relay1State = !relay1State;
            digitalWrite(relay1, relay1State);
            delay(250);
            break;
          case 0xFF18E7:
            Serial.println("button 2 pressed");
            relay2State = !relay2State;
            digitalWrite(relay2, relay2State);
            delay(250);
            break;
        }
        irrecv.resume();
      }

      int reading = digitalRead(buttonPin);
      if (reading != lastButtonState) {
        lastDebounceTime = millis();
      }
      if ((millis() - lastDebounceTime) > debounceDelay) {

        if (reading != buttonState) {
          buttonState = reading;

          if (buttonState == HIGH) {
            masterState = !masterState;
            relay1State = masterState;
            relay2State = masterState;
          }
        }
      }

      digitalWrite(relay1, relay1State);
      digitalWrite(relay2, relay2State);
      lastButtonState = reading;
    }

what I've done is create a masterState that only changes whenever you press the buttonPin and by pressing it will also change both relays to the value of new masterState independently of their actual state.

Another advice: is a bad practice to not initialize variables before use, because when you declare it is not granted that they are automatically equal to zero.


message:
Modifying Arduino IMU library to rely on DSSCircuit's I2C Master Library

For an Arduino project I am working on, I am trying to modify the SparkFun 6 Degrees of Freedom IMU Digital Combo Board - ITG3200/ADXL345 to support DSSCircuit's I2C Master Library (https://github.com/DSSCircuits/I2C-Master-Library). This is to combat the known issue of the Arduino Wire library to often get hung up while trying to run the EndTransmission function.

I'm new to this and do not understand how the terms 'slave address' and 'register address' and 'bytes you want to send' are different, if they are. I also do not understand how buffering works in the base IMU library. Any information on those would be appreciated, but is not the focus of my question.

I use the example code of the IMU unit...

    #include <FreeSixIMU.h>
    #include <FIMU_ADXL345.h>
    #include <FIMU_ITG3200.h>
    #include <Wire.h>
    #include <I2C.h>

    int raw[6]; // x y z yaw pitch roll

    // Set the FreeSixIMU object
    FreeSixIMU sixDOF = FreeSixIMU();

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

      delay(100);
      sixDOF.init(); //begin the IMU
      delay(100);
    }

    void loop() {
      sixDOF.getRawValues(raw);
      Serial.print(raw[0]);
      Serial.print(" x | ");
      Serial.print(raw[1]);
      Serial.print(" y | ");
      Serial.print(raw[2]);
      Serial.println(" z");
      delay(100);
    }

And I changed the selected IMU library functions as follows:

    // Writes val to address register on device
    void ADXL345::writeTo(byte address, byte val) {
      I2c.write(address, val);
      // send register address
    }

    // Reads num bytes starting from address register on device in to _buff array
    void ADXL345::readFrom(byte address, int num, byte _buff[]) {
      I2c.read(address, (byte) num);
      // sends address to read from
    }

    void ITG3200::writemem(uint8_t _addr, uint8_t _val) {
      I2c.write(_addr, _val);   // start transmission to device
    }

    void ITG3200::readmem(uint8_t _addr, uint8_t _nbytes, uint8_t __buff[]) {
      I2c.read(_addr, _addr, _nbytes);   // start transmission to device
    }

And added the `#include <I2C.h>` statements to the headers files where applicable.

When running the example code, the serial output will not change values based on how I move the accelerometer, which makes me think I used the wrong slave address to read data from, or some other issue.

Can someone help me modify the IMU library to include DSSCircuit's Master I2C Library?

Thank you Stack Exchange Community!
John

**EDIT:**

Please see PersonAGem's edit below. Using the wire library is known to have arbitrary hangups, and in this example PersonAGem lists the edits I should make to the other libraries I am using as well as gives me the code I should use in my `.ino`.

I ask a new question about this topic [here][1].

  [1]: https://arduino.stackexchange.com/questions/18256/using-arduino-shield-seems-to-break-serial-print-and-uploading-new-code

body:
You are missing the rest of the code in reading operations. You are just requesting the data, no actually reading it from the device:

the original code of adlx345::read

<!-- language: c -->

    void ADXL345::readFrom(byte address, int num, byte _buff[]) {
      Wire.beginTransmission(_dev_address); // start transmission to device
      Wire.write(address);             // sends address to read from
      Wire.endTransmission();         // end transmission

      Wire.beginTransmission(_dev_address); // start transmission to device
      Wire.requestFrom(_dev_address, num);    // request 6 bytes from device

      int i = 0;
      while(Wire.available())         // device may send less than requested (abnormal)
      {
        _buff[i] = Wire.read();    // receive a byte
        i++;
      }
      if(i != num){
        status = ADXL345_ERROR;
        error_code = ADXL345_READ_ERROR;
      }
      Wire.endTransmission();         // end transmission
    }

would change to (if no mistakes made):

<!-- language: c -->

    void ADXL345::readFrom(byte address, int num, byte _buff[]) {
      I2c.read(_dev_address, address, num) // request 6 bytes from device
      if(I2c.available() != num){  // device may send less than requested (abnormal)
        status = ADXL345_ERROR;
        error_code = ADXL345_READ_ERROR;
      }

      int i = 0;
      while(I2c.available())
      {
        _buff[i] = I2c.receive();    // receive a byte
        i++;
      }
    }

you may need to force cast parameters between functions.

If for some reason you don't want the actual code and want to use another library, I'll suggest [I2Cdev site](http://www.i2cdevlib.com/devices) with a well documented classes for adlx345 and ITG3200.

**Edit:**

This caused me no problem. That is the only 2 functions I changed:

<!-- language: c -->

    // Writes val to address register on device
    void ADXL345::writeTo(byte address, byte val) {
      I2c.write((uint8_t) _dev_address, (uint8_t) address, (uint8_t) val);
    }

    // Reads num bytes starting from address register on device in to _buff array
    void ADXL345::readFrom(byte address, int num, byte _buff[]) {
      I2c.read((uint8_t) _dev_address, (uint8_t) address, (uint8_t) num);  // request 6 bytes from device
      if(I2c.available() != num){  // device may send less than requested (abnormal)
        status = ADXL345_ERROR;
        error_code = ADXL345_READ_ERROR;
      }

      int i = 0;
      while(I2c.available())
      {
        _buff[i] = I2c.receive();    // receive a byte
        i++;
      }
    }

**Arduino code used:**

<!-- language: c -->

    #include <I2C.h>
    #include "FIMU_ADXL345.h"

    ADXL345 acc = ADXL345();
    int x=0,  y=0, z=0;
    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      I2c.begin();
      delay(100);
      acc.init(ADXL345_ADDR_ALT_LOW);
      delay(100);
      Serial.print("Is ACC OK?: ");
      Serial.println(acc.status);
      Serial.print("Any Error code?: ");
      Serial.println(acc.error_code);
      Serial.println("********Print all register current values********");
      acc.printAllRegister();
      Serial.println("********END register print******");
      Serial.println(acc.getRate());
    }

    void loop() {
      // put your main code here, to run repeatedly:
      acc.readAccel(&x,&y,&z);
      Serial.print(x);
      Serial.print('\t');
      Serial.print(y);
      Serial.print('\t');
      Serial.println(z);
      delay(500);
    }

**Output given:**

    Is ACC OK?: 1
    Any Error code?: 0
    ********Print all register current values********
    0x00: B11100101
    0x1D: B00000000
    0x1E: B00000000
    0x1F: B00000000
    0x20: B00000000
    0x21: B00000000
    0x22: B00000000
    0x23: B00000000
    0x24: B00000000
    0x25: B00000000
    0x26: B00000000
    0x27: B00000000
    0x28: B00000000
    0x29: B00000000
    0x2A: B00000000
    0x2B: B00000000
    0x2C: B00001010
    0x2D: B00001000
    0x2E: B00000000
    0x2F: B00000000
    0x30: B10000011
    0x31: B00000000
    0x32: B11110101
    0x33: B11111111
    0x34: B00000011
    0x35: B00000000
    0x36: B11100101
    0x37: B00000000
    0x38: B00000000
    0x39: B00000000
    ********END register print******
    100.00
    -12 4 230
    -10 2 231
    -11 3 231
    -12 3 228
    -10 3 230
    -11 2 231
    -12 2 229
    -11 3 229
    -10 3 231
    -11 3 229
    -10 2 230
    -12 4 230
    -12 3 229
    -10 2 229
    -13 4 230
    -11 3 230
    -10 3 230
    -11 2 230
    -11 4 229
    -11 3 230
    -11 3 230
    -11 3 229
    -12 3 229
    -10 2 229
    -11 3 230
    -11 3 231
    -11 3 230
    -15 14 227
    34 104 210
    138 95 191
    243 18 88
    323 -15 74
    280 -8 -2
    263 -2 37
    212 10 163
    16 39 233
    28 114 195
    29 161 170
    33 124 211
    5 49 244
    7 22 224
    -10 3 229
    -11 2 230
    -12 2 230
    -11 3 231
    -12 4 228


message:
Arduino read from Server periodically

I have an arduino attached with a RGB-Shield. I want to query my server for the RGB values periodically. I basically got it working using the Ethernet Shield but it takes too long to get the value (~500ms}. I really want to read the values from my server really really fast in an endless loop.

Can you give me any hints on how I can improve my code?

    #include <SPI.h>
    #include <Ethernet.h>
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    IPAddress server(192,168,1,151);
    IPAddress ip(192, 168, 1, 177);
    EthernetClient client;

    void setup() {
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for Leonardo only
      }

      // start the Ethernet connection:
      if (Ethernet.begin(mac) == 0) {
        Ethernet.begin(mac, ip);
      }

      delay(1000);

      if (client.connect(server, 80)) {
        client.println("GET /rgb.php HTTP/1.1");
        client.println("Host: 192.168.1.151");
        client.println("Connection: close");
        client.println();
      }
      else {
        Serial.println("connection failed");
      }
    }

    void loop()
    {
      if (client.available()) {
        char c = client.read();

        ... read from Server

      }

      if (!client.connected()) {
        client.stop();
        if (client.connect(server, 80)) {
          client.println("GET /rgb.php HTTP/1.1");
          client.println("Host: 192.168.1.151");
          client.println("Connection: close");
          client.println();
        }
      }
    }

body: You could try with a direct TCP connection (in this way you skip the HTTP layer) but you need to prepare also a small TCP server (in any language comfortable to you) that accepts the client connection, sends the data, waits the ACK and close the connection.


body:
I would start with this section:

    if (client.connect(server, 80)) {
      client.println("GET /rgb.php HTTP/1.1");
      client.println("Host: 192.168.1.151");
      client.println("Connection: close");
      client.println();
    }

How many messages does the Arduino Ethernet library send for this block? Actually due to the implementation of the Arduino Print and EthernetClient class it sends 7 messages (no joke!). It does not collect this into a single message/frame.

The first optimization is to print a single string and send that as one frame.

      #define CR "\r\n"

      client.print("GET /rgb.php HTTP/1.1" CR
                   "Host: 192.168.1.151" CR
                   "Connection: close" CR
                   CR);

Cheers!


message:
Need Basic Help with Software Serial

I am testing the basic Software Serial example on the arduino website, but I cant get the myserial to print

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(10, 11); // RX, TX

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

     Serial.println("Goodnight moon!");

      // set the data rate for the SoftwareSerial port
      mySerial.begin(4800);
      mySerial.println("Hello, world?");
    }

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

body: In the example, digital pins 10 and 11 (mySerial) on your Arduino board are used as virtual RX and TX serial lines. The virtual RX pin (pin10)is set up to listen for anything coming in on the hardware RX serial line, and to then echo that data out the virtual TX line (pin11). Conversely, anything received on the virtual RX (pin10) is sent out over the hardware TX.


body:
You would need to connect something to the pins 10 and 11 like a FT232RL breakout or another serial device. If you have another Arduino, connect the RX of that Arduino to pin 11 on the Arduino connected to the USB and give the other a simple program like:

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

    void loop(){
      Serial.println("Testing mySerial on Other Arduino");
      delay(500);
    }

Once the above code is loaded to second Arduino, put that example code on first Arduino and connect the two together like mentioned above; tx to rx and rx to tx and load the code on first Arduino and see results.


message:
Are there ultrasonic transducers which are able to produce a "chirp" sound wave?

I'm working in a ultrasonic radar project and the supervising teacher wants us to produce a chirp sound wave (a frequency-varying sinusoid).

I'm familiarised with the usual ultrasonic module, but as far as I know, it cannot do the task.

I searched on-line for transducers that I could use, but couldn't find anything useful.
Are there any commercially available component that could do this task? If not, what could I possibly do?

body:
Piezoelectric speakers, the kind commonly found in ultrasonic transducers generally operate in a narrow frequency range when operating at ultrasonic range (a resonate frequency of the metallic diaphragm). This is very true once you get above about ~60 kHz. However if the ultrasonic "chirp" you are looking for can be in the range of say 20-60 kHz you could be in luck, i.e., http://www.conrad-electronic.co.uk/ce/en/product/710991/KEPO-piezo-element-25-60-kHz-515-mm

You could use the Tone function (which goes up to 65535 Hz) to produce the frequency sweep you desire. However if you want to go up to frequencies in the 100+ kHz range you will be delving into research territory and hence extremely expensive equipment.

Having said that, technologies change very quickly and I my knowledge may already be out of date. Hope this helps.


message:
"Sharing" used GPIO pins

I have a question regarding the ARDuino uno and some shields. I currently have a shield on my Uno, which takes the pins 0 to 7. However, on top of that board there is an extension of those 8 pins. If they were always in use, I suppose that the extra ports wouldn't be on top of the board, right?

Here's how it looks: [![arduino shield][1]][1]

So it seems like you're able to "share" them. Is it possible to do so in real-time or is that there so you can use the ports when you disable the shield?

If its possible in real-time, how would I go about doing that? I've searched a little but couldn't find anything. I suppose i'd need some kind of clock to make the switch between the shield and the other components on pins 0-7, but not sure how to do that.

I'm kind of an electrics newbie, so hence the question might be a little silly :)

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

body:
No, you can't "share" pins between shields, except in specific circumstances (open-drain interrupts, I2C or SPI buses, etc).  General GPIO pins connect to just one device at a time.

I can't tell from that picture, but it is highly unlikely that all 8 of the IO pins are actually in use by the shield, and the ones that aren't actually connected to anything within the shield are available for another shield placed on top to use.  You'll have to look at the schematic or manual for the shield to know exactly which pins are used for what and which are available for other shields to use.

However, one thing to note with that shield - it doesn't appear to pass through the power header, so how a shield on top would get powered at all is a mystery to me.


message:
Updating the ARDuino code over GPRS

I've been searching a little for self-updating the ARDuino, and most i've come about is updating it using a wifi / lan shield.

Now I have a GPRS shield that can connect it to the internet. Say that I want to remotely update the shield - how would I go about doing that?

I'm guessing I need some kind of bootloader - but is that extra hardware?

Actually the question boils down to:

- How can I flash the ARDuino Uno with new software, that I'll receive over a GPRS connection using a GPRS shield?

body:
You would either have to replace the bootloader on your chip (software) with one that knows about your GPRS shield (I don't know if there is one, so you would most likely have to write your own and that is not a trivial task), or use a second microcontroller to act as a programming interface between the GPRS shield and the main Arduino.  That could be another Arduino.

The second option is probably the simplest to create:

1. The GPRS is connected to Arduino A.
2. Your main software runs on Ardiuno B.
3. Both Arduinos are connected by serial
4. Normal operation Arduino A passes all serial verbatim through to Arduno B
5. Arduino A receives programming instructions and downloads the new code - maybe storing it on an SD card temporarily (not enough RAM in an Arduino) then resets Arduino B into the bootloader.
6. Arduino A then sends the serial instructions in the same way that avrdude does to program the downloaded HEX file.

Arduino A is then a proxy between the GPRS and Arduino B.  Arduino A does all the control of the GPRS and sends data between Arduino A and the internet and vice versa - it's up to you to decide how best to achieve that, depending on what information you have going backwards and forwards.

Both solutions require a certain level of programming knowledge and skill and aren't trivial, but are perfectly possible if you set your mind to it.


message:
Emulate RFID Tag

I just got my RFID-RC522 Reader and was wondering one thing. Can i Use an RFID Reader to emulate an RFID Tag, so that if i have another reader it will detect the other one as a card and transfer data. It should be detected as a Tag like a midfare Classic but the data sould be supplied by the Arduino. Is this possible? At all? Or does it require another type of reader? If you know a solution please share it.

body:
I'm almost positive you cant use a RFID Reader to talk to another RFID Reader with the basic libraries and resources we have. You are best just getting an actual tag may it be Mifare classic or another type of RFID Tag.

I'm sure this is possible but the amount of development you will need to dedicate towards this would out weigh just getting a cheap RFID tag.

What you can do is look around see what type of things you have laying around maybe something has an RFID tag in it, or maybe you have a phone with NFC. You can use your phones NFC to send data to a RFID reader, but you will need to find the resources to do this. Sorry I'm not much help but maybe someone has done this before and has a simple solution.


message:
Any way to include the text of a file inside a sketch, to make it shorter and neater?

I'm wondering if there is any way to include the text of a file into a sketch by using a single placeholder command, similar to the "#Include" command when using Server Side Includes on .shtml files.

I'm sorry if I'm not wording this correctly. It was hard for me to phrase it and also hard for me to search about it, since the nouns seem so generic.

I understand that some parts of code can be separated out into their own functions, and that those functions could be saved in a different .ino file. But I'm wondering about for the cases that can't be separated out into functions (like for declarations at the beginning of a sketch, or an area in loop() that would require too many variables to be passed to the function).

----------

EDIT: I think I should've been more specific:
In one example, I have lots of html code being served from the loop() function. The Arduino webserver is serving a complex page that shows about 100 buttons on the webpage. I would like to separate the page-serving code to a separate .ino file and have it opened as a separate tab in the Arduino IDE. That way it's easy for me to open that tab whenever I want to modify the webpage, but also the code for serving the page won't take up so much space in my main file. The code isn't completely html (it has lots of functions and conditionals), so that's why I can't just save it as an external .html file and have it served from that file.

As another example: At the top of my sketch I have lots of defines for wireless signals that need to be sent. They look like this:

    const unsigned long a1o = 4216115, a1c = 4216124, a2o = 4216259, a2c = 4216268, a3o = 4216579, a3c = 4216588, a4o = 4218115, a4c = 4218124, a5o = 4224259, a5c = 4224268; //remote control 1

There are 10 lines of code that look like that, and I never have to modify them because they're all constants. When I'm searching for bugs in my code, I never have to refer to those lines, and they're usually just in my way.

body:
As suggested in comments, you can use `#include` statements to include texts of files into a sketch.  For example, suppose files c1.h,  c2.h,  c3.h,  c4.h, and  c5.h are in directory `~/sketchbook/tincludes`, along with the file `tincludes.ino`, which is as follows:

    #include <Streaming.h>
    void setup() {
      const long int
    #include "c1.h"
    #include "c2.h"
    #include "c3.h"
    #include "c4.h"
    #include "c5.h"
     etc=5   ;
      Serial.begin(115200);
      Serial << z1o <<  z1c <<  z2o <<  z2c <<  z3o <<  z3c <<  z4o <<  z4c <<  z5o <<  z5c;
    }

Further, suppose c1.h ... c5.h each contain one line of code, as follows:

    ==> c1.h <==
      z1o=25829, z1c=9774,

    ==> c2.h <==
      z2o=7850, z2c=25585,

    ==> c3.h <==
      z3o=7103, z3c=17981,

    ==> c4.h <==
      z4o=30827, z4c=24511,

    ==> c5.h <==
      z5o=4167, z5c=10036,

Then the sketch will compile ok, and the sketch-lines with `const long int` through `etc=5   ;` will compile the same as if they were replaced by

    const long int z1o=25829, z1c=9774, z2o=7850, z2c=25585, z3o=7103,
         z3c=17981, z4o=30827, z4c=24511, z5o=4167, z5c=10036, etc=5;


body:
Usually you should not define a variable inside a header file. If, for example, you write

    // file myvars.h
    int var_a = 10;

    // file main.ino
    #include "myvars.h"

    // file another.cpp
    #include "myvars.h"

the linker will fail, because there are two definitions of the same variable `var_a`.

The correct way to do it is to declare a variable as extern inside the header file, then define them into a cpp (or ino) file just once. I mean

    // file myvars.h
    extern int var_a;

    // file myvars.cpp
    int var_a = 10;

    // file main.ino
    #include "myvars.h"

    // file another.cpp
    #include "myvars.h"

This way you will be able to access `var_a` from both main.ino and another.cpp. If you don't want to add another cpp file for the definitions, you just have to provide the definition inside ONE of the ino or cpp files you already have.

So, in your case, just make two more files:

file remote_control_1.h:

    extern const unsigned long a1o, a1c, a2o, a2c, a3o, a3c, a4o, a4c, a5o, a5c;

file remote_control_1.cpp:

    #include "remote_control_1.h"
    const unsigned long a1o = 4216115;
    const unsigned long a1c = 4216124;
    const unsigned long a2o = 4216259;
    const unsigned long a2c = 4216268;
    const unsigned long a3o = 4216579;
    const unsigned long a3c = 4216588;
    const unsigned long a4o = 4218115;
    const unsigned long a4c = 4218124;
    const unsigned long a5o = 4224259;
    const unsigned long a5c = 4224268;

and in your files just write `#include "remote_control_1.h"` to access those variables


message:
How to use FTDI to program Lilypad Arduino?

I am trying to upload a basic Blink code from my computer to Arduino Lilypad contains Atmega 328. While my Blink codes are uploading, **FTDI 1402-C CN480661 FT232RL** module is not responding to the Arduino IDE at the end of the process. So I couldn't upload any codes with this uploading method, I mean using FTDI modules directly.

This is how I do the connections:

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

This is my Blink code:

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

    void loop() {
      digitalWrite(13, HIGH);     delay(1000);
      digitalWrite(13, LOW);      delay(1000);
    }

I chose **AVRISP mkII** as a programmer. **ATmega328** as a processor. **Arduino Lilypad** as a board on *Arduino IDE* **v1.6.6**

At this point, I got this error:

> avrdude: ser_open(): can't open device "\\.\COM4": Access is denied

Windows's device manager says: USB Serial Port is attached to COM4, also Arduino IDE saw that.

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

  [1]: https://i.stack.imgur.com/axOsO.png
  [2]: https://i.stack.imgur.com/gRNE8.jpg

I downloaded FTDI driver for Windows, but still, I can't upload any code into my Lilypad Arduino.

How can I use FTDI to program my Lilypad Arduino?

body:
"Access is denied" this looks like you should at least restart your computer after you installed the FTDI driver if you have not already.

Run Arduino IDE as Administrator and also make sure you are logged into an Administrator account in your windows login.

If all this fails this means another application is using that com port you will need to figure out what could be using that com port another instance of Arduino IDE opened? Etc

If all else fails restart your computer with the usb unplugged, login, open arduino IDE and plug in your usb and select the com port.

Edit: You can also try changing the USB port you are currently using for another one, this will also change your com port to a new number


body:
The error message

> "avrdude: ser_open(): can't open device "\\\\.\COM4": Access is denied"

tells me that the error occurs when the Arduino IDE tries to open a connection to the FTDI adapter "serial port", long before the Arduino IDE actually sends anything through the FTDI adapter to the Arduino.

Have you read the [Arduino Troubleshooting guide][1]?
The Arduino Troubleshooting guide recommends

> Access to the Serial Port
>
> * On Windows, if the software is slow to start or crashes on launch, or
> the Tools menu is slow to open, you may need to disable Bluetooth
> serial ports or other networked COM ports in the Device Manager. The
> Arduino software scans all the serial (COM) ports on your computer
> when it starts and when you open the Tools menu, and these networked
> ports can sometimes cause large delays or crashes.
> * Check that you're
> not running any programs that scan all serial ports, like USB Cellular
> Wifi Dongle software (e.g. from Sprint or Verizon), PDA sync
> applications, Bluetooth-USB drivers (e.g. BlueSoleil), virtual daemon
> tools, etc.
> * Make sure you don't have firewall software that blocks
> access to the serial port (e.g. ZoneAlarm).
> * You may need to quit
> Processing, PD, vvvv, etc. if you're using them to read data over the
> USB or serial connection to the Arduino board.

If I were you my next steps would be:

* Unplug the USB cable from my computer, and check the "Tools >> Serial Port" option. Usually when the USB cable is unplugged, that option is greyed out (empty list), but sometimes there is a few things listed. Remember that list.
* Plug the USB cable from the FTDI back in (preferably in a *different* socket of the computer this time), and check the "Tools >> Serial Port" option. Do you remember the list from the previous step? There should be a new item on the list, representing the FTDI adapter -- pick that one.
* I would unplug the FTDI from the Arduino Lilypad, and then tell the Arduino IDE to upload the sketch. Obviously with the Arduino airgapped from your computer it won't be able to upload the sketch, but does it give a useful error message?

* Reboot the computer with nothing plugged into its USB ports. Plug the FTDI adapter directly into the Arduino Lilypad ("BLK" to "B", "GRN" to "G"). Start the Arduino IDE in Administrator mode. Make sure the board type is set correctly. Try to plug in the USB cable, set the Serial Port, and upload a sketch before any other program has a chance to grab that COM port.

  [1]: http://www.arduino.cc/en/Guide/Troubleshooting


message:
Share data between the two processors of the Arduino Yun

The linux processor runs a Python script from which I would like to send an array of integers to the Yun microprocessor. How can I do that?

And then, how can I retrieve and then use this array in my Arduino Sketch?

body:
Serial1 on the Arduino side is connected to a serial console on the Linux side.

So, you could use calls on the Arduino to run your Python script on the Linux side and then listen to the output of the script to come back though the serial port and part it.

Here is an example of a project where I used a Yun like this. The Arduino side interfaces to some temperature sensors, and then types commands into the Linux side over the serial connection to run CURL and report data to internet URLs.

http://wp.josh.com/2014/06/05/tempurature-logging-to-a-google-spreadsheet-with-an-arduino-yun/#more-1797

I am going to warn you that this is very ugly. Then Yun itself is quite ugly too. There were so many problems that I ended up giving up on this platform completely.


body:
Given that my Python script printed the following

    [10, 20, 30, 40]

This is the sketch I used to retrieve the array

    #include <Bridge.h>
    #include <Process.h>

    void setup()
    {
       Bridge.begin();
       Serial.begin(19200);
    }

    void loop()
    {
       Process proc;
       int i=0;
       size_t dim = 1;
       int* array = (int*)malloc(dim);

       Serial.print("Running process...");
       Serial.println("done!");
       proc.runShellCommand("python /script.py");

       while (proc.available()){
         if((char)proc.read() != ']'){
            array[i] = proc.parseInt();
            dim++;
            array = (int*)realloc(array,dim);
            Serial.println(array[i]);
            i++;
          }
          else
            break;
       }

       Serial.println();
       delay(1000);
    }


body:
The Yun makes communication between the microprocessor and the Linux side easy.  On the Arduino side, use the Bridge library in your "processing script" to read (or write) Bridge values set by the python program running on the Linux side.  From the linux side, the bridge looks like a web address and you set values by addressing a URL with a get or put url http request. You can also manipulate these values from another computer on the network as well if you like.

 I have some Arduino Yun dataloggers that use the Linux side to communicate via wifi with an ftp server that serves several Yun dataloggers. The arduino script reads the sensors, creates the records, etc. You can also have the microprocessor side write files that are used by the linux side of the Yun.

I find the Yun's combination of Linux and the regular arduino in one package makes the overall system easier to program and to interface with the rest of the web.


message:
Run code via NRF24L01+ command "dynamically"?

I'm trying to make a home automation setup but I'm having a bit of trouble.

I want to be able to send commands of varying sizes to my arduino, separated by "|" and after receiving it completely it runs code corresponding to the command.

Example:

input "RCP=10001|CMD=D|VAL=120"
would result in an array like:

    String cmd[][] = {{"RCP", "10001"}, {"CMD", "D"}, {"VAL", "120"}}

with the amount of 'variables' being... well, variable.

The code would continue checking if the RCP (recipient) ID corresponds with the ID of the current client and then run code based on the following variables.
But I don't think that's important info for the code which separated the string.

This string would be sent through an NRF24L01+ (That code already works)

body:
What you are asking is very tricky at best. Your average Arduino doesn't have enough memory to start storing arrays of Strings.

Instead you will need to "distil" the information as it comes in and store the distilled information.

If the possible keys are all known beforehand then you can assign a number to each possible key - say RCP is 1, CMD is 2, VAL is 3, etc.  If the values are all numeric or can be represented by a number, then convert those to the corresponding number and store those.

Also the Arduino is not good at working with dynamic memory allocations - again because of lack of memory.  If you can decide on a reasonable maximum number of messages to store then you can pre-allocate the memory for them.

For instance it may be good to define a structure which is the content of a message:

    struct message {
        uint8_t key;
        uint16_t val;
    };

Then make an array of that structure - one slice per possible command, say 10 of them:

    struct message messageQueue[10];

That would take a total of 30 bytes in memory - each entry being 3 bytes (1 for the key, two for the value).  Now you can set the keys and values to the correct data as it arrives.

Depending on how you want to deal with the messages as they come in - add them to the end of an existing queue, or always starting the queue from empty every time a new message arrives - you might want to implement a *circular buffer*.  This is basically how the Serial port on the Arduino works - in involves having two *pointers* to locations in the array - one where you are writing to, and one where you are reading from. As you write to the array the writing pointer moves along - if it reaches the end it starts from the beginning again.  As you read from the array the reading pointer moves along too.  If the two pointers are together then the array is empty. If the writing pointer would end up where the reading pointer is, the array is full.  Take a look in the Arduino source code (HardwareSerial.cpp) to see how it's implemented.

As for parsing the string as it comes in - if you have it as a single String already then it's a case of looking through it for the | characters and splitting out each portion in turn, then doing the same with each portion looking for the =. Then you can interpret what is in the key/value pairs and decide what to store in the array.


message:
RFduino communication capabilities

Is there any way to connect RFduino's via radio frequency? Or any capability to transmit information between RFduino's for distances up to 200 feet?

I would like to purchase a dev kit (for RF duino) but i'm not sure what parts I will need to transmit info longish (200 feet) distances.

body:
https://blog.adafruit.com/2010/06/11/aprs-radio-shield-for-arduino/
Be warned you need a license to transmit on amateur frequencies at least in the US, you will also need to hook up a transmitter for this shield.

GSMShield would also be great and is something I'm thinking about using for my project, the way the Arduino IDE is setup and the libraries already in place I'm sure it would be easy to turn text messages into commands or readable and usable data between the sender and receiver.

Here are two ways one using a long range radio frequency or the GSM network. We would need to know more exact data of your project on how to implement these two solutions to accomplish what you would like to do.

The first option is most likely going to be the lesser option if you don't have a license to transmit long range frequencies and do not have experience.

The second option is easy and all you would have to do is make sure both sender and receiver are within a GSM network.

Good luck and I'm excited to see what other solutions others may post since I'm in the same boat.


message:
Cloud function getting stopped Parse.com in loop when calling from Arduino-yun

I have created a cloud function using the Parse.com Javascript SDK and I am calling those functions from Arduino. Following is code for the `hello` function:

<!-- language: lang-js -->

    Parse.Cloud.define("hello", function(request, response) {
        response.success("This is hello function");
    }); //hello function Block

I am calling this function from the Arduino side using the following code:

<!-- language: lang-cpp -->

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

      while (!Serial);

      Parse.begin("***zE0uUjQkMa7nj5D5BALvzegzfyVNSG22BD***", "***Ssggp5JgMFmSHfloewW5oixlM5ibt9LBSE***");
      //commented my keys with * here only

      // In this example, we associate this device with a pre-generated installation
      Parse.getInstallationId();
      Parse.startPushService();
    }

    void loop() {
      Serial.println("Start loop");
      demoBasic("meeting", 0);
    }

    void demoBasic(String functionname, int light) {
      char fnname[11];
      functionname.toCharArray(fnname, 11);

      Serial.print("In ");
      Serial.print(functionname);
      Serial.println(" Function");

      ParseCloudFunction cloudFunction;
      cloudFunction.setFunctionName(fnname);
      cloudFunction.add("light_sensor", light);
      cloudFunction.add("value", "Arduino Hello");//parameters

      ParseResponse response = cloudFunction.send();
      Serial.println(response.getJSONBody());
    }

Problem is that I am getting response 8 times only. After that whole program flow gets blocked. What is the problem?

body:
Give this a shot, I really hate String, maybe that 8-times thing has to do with memory issues caused by it.

    void loop() {

      char functionToCall[8] = "meeting";
      Serial.println("Start loop");
      demoBasicCharArray(functionToCall, 0);
    }

    void demoBasicCharArray(char *functionname, int light) {

      Serial.print("In ");
      for (byte i=0;i<sizeof(functionname);i++){
        Serial.print(functionname[i]);
      }
      Serial.println(" Function");

      ParseCloudFunction cloudFunction;
      cloudFunction.setFunctionName(functionname);
      cloudFunction.add("light_sensor", light);
      cloudFunction.add("value", "Arduino Hello");//parameters

      ParseResponse response = cloudFunction.send();
      Serial.println(response.getJSONBody());
    }


message:
HDMI EDID emulator

I am working on a project where i emulate the EDID of a screen to force a source into sending data on a certain resolution.

I read the original EDID code of a screen and change the timings into the resolution I want to force the source in, i send this changed EDID code to the source with an Arduino uno when the source gives a read on address 0x50 (where the EDID located, see handshake). We have an HDMI in/out with the data lines connected thru and the DDC lines (source) connected to the Arduino that we can send the changed EDID to the source (i²c protocol).

I can change the resolution successfully on some sources, and on some it doesn’t change. The attached screen doesn’t find a source. I use the same code for both scenarios.

    #include <DTWI.h>
    #include <Wire.h>         //BUFFER_LENGTH = 256

    uint8_t edid[256] = {
     0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x4C, 0x2D, 0xF4, 0x0C, 0x45, 0x52, 0x46, 0x31, 0x15, 0x19, 0x01, 0x03, 0x80, 0x3C, 0x22, 0x78, 0x2A, 0x52, 0x95, 0xA5, 0x56, 0x54, 0x9D, 0x25, 0x0E, 0x50, 0x54, 0xBF, 0xEF, 0x80, 0x71, 0x4F, 0x81, 0xC0, 0x81, 0x00, 0x81, 0x80, 0x95, 0x00, 0xA9, 0xC0, 0xB3, 0x00, 0x01, 0x01, 0x02, 0x3A, 0x80, 0x18, 0x71, 0x38, 0x2D, 0x40, 0x58, 0x2C, 0x45, 0x00, 0x56, 0x50, 0x21, 0x00, 0x00, 0x1E, 0x01, 0x1D, 0x00, 0x72, 0x51, 0xD0, 0x1E, 0x20, 0x6E, 0x28, 0x55, 0x00, 0x56, 0x50, 0x21, 0x00, 0x00, 0x1E, 0x00, 0x00, 0x00, 0xFD, 0x00, 0x32, 0x4B, 0x1E, 0x51, 0x11, 0x00, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x00, 0x00, 0x00, 0xFC, 0x00, 0x53, 0x32, 0x37, 0x45, 0x33, 0x37, 0x30, 0x0A, 0x20, 0x20, 0x20, 0x20, 0x20, 0x01, 0x62, 0x02, 0x03, 0x1B, 0xF1, 0x46, 0x90, 0x04, 0x1F, 0x13, 0x03, 0x12, 0x67, 0x03, 0x0C, 0x00, 0x10, 0x00, 0x80, 0x22, 0x23, 0x09, 0x07, 0x07, 0x83, 0x01, 0x00, 0x00, 0x01, 0x1D, 0x00, 0xBC, 0x52, 0xD0, 0x1E, 0x20, 0xB8, 0x28, 0x55, 0x40, 0x56, 0x50, 0x21, 0x00, 0x00, 0x1E, 0x8C, 0x0A, 0xD0, 0x90, 0x20, 0x40, 0x31, 0x20, 0x0C, 0x40, 0x55, 0x00, 0x56, 0x50, 0x21, 0x00, 0x00, 0x18, 0x8C, 0x0A, 0xD0, 0x8A, 0x20, 0xE0, 0x2D, 0x10, 0x10, 0x3E, 0x96, 0x00, 0x56, 0x50, 0x21, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3D
    };

    void receiveEvent(int receivedByte)
    {
        if (receivedByte == 1)          //If there is 1 byte received
        {
          int receivedValue = Wire.read() << 1;
          receivedValue |= Wire.read();
          Serial.print("Read byte: ");
          Serial.print(receivedValue);
          Serial.println();
        }
        else
        {
            Serial.println("Not the amount of bytes that was expected: ");
            Serial.print(receivedByte);
        }

        while(Wire.available())
        {
            Wire.read();
        }
        return;
    }

    void requestEvent()
    {
          Serial.println();

         for (int i = 0; i < 256; i++){
                Wire.write(edid[i]);               //Write EDID
                Serial.print(edid[i], HEX);      //Print EDID
                Serial.print(",");
         }

        Serial.println();
        Serial.println("Finished");      //Write is complete

    }

    void setup()
    {
      Serial.begin(9600);
      Serial.println("**** HDMI ****");
      pinMode(2, OUTPUT);          //Hot plug detection
      Wire.begin(0x50);
      digitalWrite(2, LOW);
      delay(20);
      digitalWrite(2, HIGH);         //Source knows that a screen is attached and want to read the edid of the screen

      Wire.onReceive(receiveEvent);
      Wire.onRequest(requestEvent);
    }

    void loop()
    {

    }

The following attached pictures are the EDID handshakes without the Arduino involved.

Handshake 1: This is an HDMI 1.4 device [![HDMI 1.4 device][1]][1]

Handshake 2: This is another HDMI 1.4 device[![Another HDMI 1.4 device][2]][2]

You can see that the handshakes are the same.
My code only works on handshake 1.

Does anyone have an idea why it doesn't work on the other devices ?

Does it has to do with the Start/Restart ?

Regards !

  [1]: https://i.stack.imgur.com/8YSMW.png
  [2]: https://i.stack.imgur.com/HXRxR.png

body:
I'm not an expert in HDMI/DDC, but I have some theories to remove potential problems:

1. "Wire.onRequest/Wire.onReceive" could be before "digitalWrite(2, HIGH)", to really represent "OK, you can send me data now" (Arduino isn't the fastest HW, and Arduino libs add extra overhead - lots of condition races can occur);
2. You could use "Write.write(did, 256)", instead of writing one byte to I2C then another via serial (again, racing conditions, specially since serial writing is slow);
3. If I'm not misunderstanding, the byte received from HDMI means the byte you should start transmitting EDID (ex: for "0", do a "Wire.write(edid, 128)", for "0x80", do a "Wire.write(edid + 0x80)"). This is a common approach for reading from PROM chips. HDMI have a 5V pin to allow PROM reading from turned-off devices, and byte 127 from EDID means "I may have more 128 bytes for you".
4. Are you doing simple tests, with unmodified data? Ex: read EDID from device X, test that same EDID, then test with modified data?


message:
Event driven programming

I have ran across a couple of different event libraries that are available on the AVR and Andruino but I am not sure which one is the best option. What I would like to do is design my program in a event driven style but not sure how to go about this.

I have a project that I need to keep lightweight but also in this program I have several actions that can be happening at any given time i.e. Digital Inputs being triggered and I need to run code whenever these events happen.

I found [the QP Framework][1] that looked promising but I wanted to get some feedback from some others that might of used this type of library before and might be able to provide some examples and maybe some experiences.

Another site I found [here][2] and lists all sorts of different libs

  [1]: http://playground.arduino.cc/Code/QP
  [2]: http://blog.ardublock.com/2013/10/29/evaluating-of-event-driven-libraries-on-arduino/

body:
You may want to take a look at LMX by David Anderson [A Light-Weight Multi-Tasking Executive][1].

He has a very good set of videos on the code that he did for [Dallas Personal Robotics Group (DPRG)][2].

The specific videos for LMX are:

 - [David Anderson on Robotics Software - part 1][3]
 - [David Anderson on Robotics Software - part 2][4]

  [1]: http://www.geology.smu.edu/dpa-www/robo/LMX
  [2]: https://www.youtube.com/channel/UCsGzeeBTraAts7lMQdfhqtA
  [3]: https://www.youtube.com/watch?v=nRaosdrDrdA
  [4]: https://www.youtube.com/watch?v=Jnrg4WAtxGQ


message:
TCP connection CPU usage, multiple signals?

I'm connecting a client (java program) to an arduino (server). What I want to know is, how high the CPU usage is, and what to do if there are no clients that are trying to connect to arduino? Should I make a delay?

My code looks like this:

    EthernetClient client = server.available();

    if(client){
        Serial.println("Connected");
        server.write("Hello\n");

        //check if client is still connected
        while (client.connected()){
            Serial.println("Still there");
            delay(2000);
           //check if client received any data
           if(client.available()){
               //read message from client
         }
      }
    } else {
         Serial.println("Nope");
         server.write("Hello\n");
         ???????????? delay(2000); ??????????????
    }

Thank you for your help.

body:
You don't need to do anything. If the else clause has a delay (e.g. of 2 seconds), then it will take up to that long before the arduino accepts the connection.

The "server.write" in the "else" clause doesn't make any sense - who are you sendin it to? server.write will normally write to all available connections.

If there's nothing else you want to do, you might as well retry straight away.

Note that, if you are doing a serial.println statement, and you have no delay, then, while waiting for a connection, it will print the "Nope" message, as fast as it can.


body:
As the Arduino typically has no demand-based clock scaling, or alternate threads of comparable priority you can schedule, there's really little point in using a delay (which is implemented as a busy-wait) rather than a tight loop - really, the primary appropriate reason would be to reduce the frequency of status output.

However, if you want to design a power-efficient system, you could consider sleeping the CPU between checking if there is anything worthwhile to do, or until an interrupt indicates that there is.  This is not something which delay() will take care of for you, so it is a fair amount of extra work and testing to get right, but it can be very worthwhile if running from batteries.

If your application is not particularly intensive you can also configure the clock divider fuse and slow the chip down generally.


message:
sending multiple signals at the same time, with short delay

Is it possible to do something like this: send a HIGH signal to an output pin, after a 0.33s delay arduino sends HIGH signal to another pin, and after another 0.33s delay, arduino sends signal to third pin. There has to be 90 seconds long high signal for each pin, but with 0.33s delay between each other.

Sooo something like this; start of the high signal on left, stop on right side:

    pin1: 0 ...... 90.00
    pin2: 0.33 ... 90.33
    pin3: 0.66 ... 90.66

Is there a way to solve this?

body: Yes. Read the BlinkWithoutDelay example and triplicate it.


message:
I want to move the mouse pointer with an Arduino and ultrasonic sensor

but when I compiled it says

> Mouse.h not found

 and I don't know what I can do.

Here is my code;

     #include <Mouse.h>

    int echoPinCursor=2;
    int trigPinCursor=3;

    int echoPinBtn=4;
    int trigPinBtn=5;
    int echoPinScroll=6;
    int trigPinScroll=7;
    int x;
    int y;
    long duracionCursor, distanciaCursor;
    void setup() {
     Serial.begin(9600);
     pinMode(trigPinCursor, OUTPUT);
     pinMode(echoPinCursor, INPUT);
     pinMode(trigPinBtn, OUTPUT);
     pinMode(echoPinBtn, INPUT);
     pinMode(trigPinScroll, OUTPUT);
     pinMode(echoPinScroll, INPUT);

    }

    void loop() {

        //mover el cursor
      int direccionx=moverx();
      int direcciony=movery();

      Mouse.move(direccionx, direcciony,0);
      delay(2);

    }

    int moverx(){
          distanciaCursor=obtener_distanciaCursor();
      if (distanciaCursor >= 1  || distanciaCursor <= 11){
           x--;
         }
       if (distanciaCursor >= 12 || distanciaCursor <= 24){
           x++;
          }
         return x;
    }

    int movery(){
          distanciaCursor=obtener_distanciaCursor();
         if (distanciaCursor >= 25 || distanciaCursor <= 37){
           y--;
           }
       if (distanciaCursor >= 38 || distanciaCursor <= 50){
           y++;
          }
      return y;
    }

    long obtener_distanciaCursor(void)
    {
      digitalWrite(trigPinCursor, LOW);
     delayMicroseconds(2);

     digitalWrite(trigPinCursor, HIGH);
     delayMicroseconds(10);

     digitalWrite(trigPinCursor, LOW);
     duracionCursor = pulseIn(echoPinCursor, HIGH);

     distanciaCursor = duracionCursor/58.2;
    return(distanciaCursor);

    }

body:
That's because the Uno can't be a mouse.  For that you need the Leonardo or something else with a similar "U" style microcontroller.

If you are adventurous, and you have a genuine Arduino, you can reprogram the USB controller chip with new firmware so it thinks it's a mouse, but programming the main MCU is then a real chore.


message:
UART Software Serial - Syncing two different sensors with start and stop bytes

I'm using 2 SRF02 sensors on the same Arduino board to attempt to have the transmitter only pulse the 40 KHz wave, while the receiver will be only taking a fake range, i.e. picking up a reading based on another transmission.

I've been using SoftwareSerial and need to know how to synchronize the time for the receiver to know when the transmitter sent the data. What I found is that I'm going to have to do this using start and stop bytes to set them in the same cycle.

How can I do this?

This is my current code:

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

    void SendCmd(unsigned char address,unsigned char cmd) {
      mySerial.write(address);
      //set the address of SRF02(factory default is 0)
      delayMicroseconds(100);
      //serial data is fixed at 9600,N,8,2,so we need some time to create the second stop bit
      mySerial.write(cmd);
      //send the command to SRF02
      delayMicroseconds(100);
      //serial data is fixed at 9600,N,8,2,so we need some time to create the second stop bit
    }
    void setup(void) {
      Serial.begin(9600);
      mySerial.begin(9600);
      Serial.println("SRF02 TEST!");
    }

    void loop(void) {
      unsigned int reading;
      SendCmd(0x00,0x5C);
      //Transmit 8 cycle 40khz pulse from address 0x00 - transmitter
      delay(70);
      //time for SRF02 to measure the range
      SendCmd(0x02,0x57);
      //Get Fake Range at Address 0x02 - receiver
      delay(10);
      //wait for some time,let the Arduino receive 2 bytes data from the TX pin of SRF02
      if(mySerial.available()>=2) {
        //if two bytes were received
        reading = mySerial.read()<<8;
        //receive high byte (overwrites previous reading) and shift high byte to be high 8 bits
        reading |= mySerial.read();
        // receive low byte as lower 8 bits
        Serial.print(reading);
        // print the reading
        Serial.println("cm");
        //Serial.println("Time Sent: ");
        //Serial.print(T_sent);
      }
      delay(250);
      // wait a bit since people have to read the output :)
    }

body:
Your code bit

    SendCmd(0x00,0x5C);//Transmit 8 cycle 40khz pulse from address 0x00 - transmitter
    delay(70);//time for SRF02 to measure the range
    SendCmd(0x02,0x57); //Get Fake Range at Address 0x02 - receiver

will send a sound burst, delay 70 ms, then start listening for the burst, which by then will have traveled around 24 meters and probably be no longer audible.

You should instead start the fake range listener immediately after sending the burst.  The general idea for one approach is as follows:

* Record time (eg, `t1=micros();`)
* Send burst (eg, `SendCmd(0,0x5C);`)
* Record time (eg, `t2=micros();`)
* Listen for burst (eg, `SendCmd(2,0x58); // Get microseconds`)
* Wait 70 ms, then read microseconds result `t3`
* Compute corrected total microseconds, `tm=t3+t2-t1`
* Convert microseconds to cm

Note use of command 0x58 instead of 0x57 to get microseconds instead of cm.  If you used 0x57, instead of adding `t2-t1` to `t3`, you would add `t2-t1` microseconds-converted-to-cm to a cm reading.

The reason for the computation `tm=t3+t2-t1` is that the second command is issued about `t2-t1` microseconds later than the first command, as explained in the next paragraph.

There is an unknown delay `d1` between when `t1` is recorded and when the first SRF02 acts; and there is an unknown delay `d2` between when `t2` is recorded and when the second SRF02 begins listening.  The correct amount to add to `t3` is `t2+d2-(t1+d1)`, which is `t2-t1` if `d1` equals `d2`, a more-or-less plausible assumption.  If your experiments reveal a constant error, add a small constant offset to compensate.

I doubt you should have the `delayMicroseconds(100);` statements in `SendCmd()`, and would recommend getting the code to work ok, then see if it still works ok when you take them out.  The `delay(10);` is unnecessary if you rewrite your 2-character-wait correctly (ie as a `while` rather than an `if`), and the `delay(70);` is unnecessary if you start conversion with command `0x5A`,  “Fake Ranging Mode - Result in centimeters, automatically Tx range back to controller as soon as ranging is complete” and then properly wait for two characters to arrive, instead of a blind wait followed by a test if they've arrrived.


body:
     unsigned int reading;
      unsigned long t1=micros();
      SendCmd(0, 0x5C);//send pulse with transmitter
      unsigned long t2=micros();
      SendCmd(2, 0x58);//return value in microseconds

      delay(70);//time for SRF02 to measure the range
      //SendCmd(0x02,0x5E);
      unsigned long t3 = SendCmd(2,0x5E);
      unsigned long tm = t3+t2-t1;

Hey thanks for the input. When I created t3, I get an error saying void value not ignored as ought to be.


body:
This is my updated code based on your suggestions, jwpat, although I did not understand your comment with `delay(70);` not being needed if I start conversion with `(2,0x5A)`.

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

    void SendCmd(unsigned char address,unsigned char cmd)
    {
      mySerial.write(address);//set the address of SRF02(factory default is 0)
      //delayMicroseconds(100);//serial data is fixed at 9600,N,8,2,so we need some time to creat the sencond stop bit
      mySerial.write(cmd);//send the command to SRF02
      //delayMicroseconds(100);//serial data is fixed at 9600,N,8,2,so we need some time to creat the sencond stop bit
    }
    void setup(void)
    {
      Serial.begin(9600);
      mySerial.begin(9600);
      Serial.println("SRF02 TEST!");
    }
    void loop(void)
    {
      unsigned long t3;
      unsigned long t1=micros();//time tx command issued
      SendCmd(0, 0x5C);//send pulse with transmitter
      unsigned long t2=micros();//time rx command issued
      SendCmd(2, 0x58);//listen for pulse
      //SendCmd(2, 0x5A);
      delay(70);//time for SRF02 to measure the range
      //SendCmd(0x02,0x5E);
      SendCmd(2,0x5E);//Get range

     while(mySerial.available()>=2)//if two bytes were received
      {
        t3 = mySerial.read()<<8;//receive high byte (overwrites previous reading) and shift high byte to be high 8 bits
        t3 |= mySerial.read();// receive low byte as lower 8 bits
        unsigned long Tm = t3 + t2 - t1;//total amt of microseconds between pulse and reading
        unsigned long Dist = (Tm/29); //converting microseconds to cm
        Serial.print(Dist); // print the reading
        Serial.println("cm");
        //Serial.print(tm);
        //Serial.println("ms");

      }
      delay(250); // wait a bit since people have to read the output :)
    }

After running this code my results keep being the following values regardless of me shifting the distance between the sensors:
72cm [![enter image description here][1]][1]

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


message:
Problem in Uploading a Bootloader to Atmega8A

I am getting an error while Uploading the Bootloader to Atmega8A
I am selecting..

      Board -> Arduino NG and Older
      Processor -> Atmega8A
      Programmer -> USBasp

and sketch code is ArduinoISP, After selecting port then I do "Burn Bootloader"

But getting an error of...

       "efuse" memory type not defined for part "ATmega8"
        Error while burning bootloader.

Please tell me what to do. Any help will be appreciated.

Thank you

body:
Google is your friend!!!
Apparently this is a known regression [bug](https://github.com/arduino/Arduino/issues/2075) not yet corrected. The possible solution is also suggested there by user [rigelinorion](https://github.com/rigelinorion) and here is the quote:

    Hello, I solved it this way...

    Open for edit the file C:\Program Files\Arduino\hardware\arduino\avr\platforms.txt
    this is standard section uploader/programmers tools

    #==============================================================================
    tools.avrdude.cmd.path={runtime.ide.path}/hardware/tools/avr/bin/avrdude
    tools.avrdude.config.path={runtime.ide.path}/hardware/tools/avr/etc/avrdude.conf
    tools.avrdude.cmd.path.linux={runtime.ide.path}/hardware/tools/avrdude
    tools.avrdude.config.path.linux={runtime.ide.path}/hardware/tools/avrdude.conf

    tools.avrdude.upload.params.verbose=-v -v -v -v
    tools.avrdude.upload.params.quiet=-q -q
    tools.avrdude.upload.pattern="{cmd.path}" "-C{config.path}" {upload.verbose} -p{build.mcu} -c{upload.protocol} -P{serial.port} -b{upload.speed} -D "-Uflash:w:{build.path}/{build.project_name}.hex:i"

    tools.avrdude.program.params.verbose=-v -v -v -v
    tools.avrdude.program.params.quiet=-q -q
    tools.avrdude.program.pattern="{cmd.path}" "-C{config.path}" {program.verbose} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{build.path}/{build.project_name}.hex:i"

    tools.avrdude.erase.params.verbose=-v -v -v -v
    tools.avrdude.erase.params.quiet=-q -q
    tools.avrdude.erase.pattern="{cmd.path}" "-C{config.path}" {erase.verbose} -p{build.mcu} -c{protocol} {program.extra_params} -e -Uefuse:w:{bootloader.extended_fuses}:m -Ulock:w:{bootloader.unlock_bits}:m -Uhfuse:w:{bootloader.high_fuses}:m -Ulfuse:w:{bootloader.low_fuses}:m

    tools.avrdude.bootloader.params.verbose=-v -v -v -v
    tools.avrdude.bootloader.params.quiet=-q -q
    tools.avrdude.bootloader.pattern="{cmd.path}" "-C{config.path}" {bootloader.verbose} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{runtime.ide.path}/hardware/arduino/avr/bootloaders/{bootloader.file}:i" -Ulock:w:{bootloader.lock_bits}:m
    #==============================================================================

    create a new tool called, for example, avrdude1
    simply copy section tools.avrdude and name it tools.avrdude1
    the trick is that we remove switch "-Uefuse:w:{bootloader.extended_fuses}:m" from "tools.avrdude1.erase.pattern="

    #=============================================================================
    tools.avrdude1.cmd.path={runtime.ide.path}/hardware/tools/avr/bin/avrdude
    tools.avrdude1.config.path={runtime.ide.path}/hardware/tools/avr/etc/avrdude.conf
    tools.avrdude1.cmd.path.linux={runtime.ide.path}/hardware/tools/avrdude
    tools.avrdude1.config.path.linux={runtime.ide.path}/hardware/tools/avrdude.conf

    tools.avrdude1.upload.params.verbose=-v -v -v -v
    tools.avrdude1.upload.params.quiet=-q -q
    tools.avrdude1.upload.pattern="{cmd.path}" "-C{config.path}" {upload.verbose} -p{build.mcu} -c{upload.protocol} -P{serial.port} -b{upload.speed} -D "-Uflash:w:{build.path}/{build.project_name}.hex:i"

    tools.avrdude1.program.params.verbose=-v -v -v -v
    tools.avrdude1.program.params.quiet=-q -q
    tools.avrdude1.program.pattern="{cmd.path}" "-C{config.path}" {program.verbose} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{build.path}/{build.project_name}.hex:i"

    tools.avrdude1.erase.params.verbose=-v -v -v -v
    tools.avrdude1.erase.params.quiet=-q -q

    #this line was edited
    tools.avrdude1.erase.pattern="{cmd.path}" "-C{config.path}" {erase.verbose} -p{build.mcu} -c{protocol} {program.extra_params} -e -Ulock:w:{bootloader.unlock_bits}:m -Uhfuse:w:{bootloader.high_fuses}:m -Ulfuse:w:{bootloader.low_fuses}:m

    tools.avrdude1.bootloader.params.verbose=-v -v -v -v
    tools.avrdude1.bootloader.params.quiet=-q -q
    tools.avrdude1.bootloader.pattern="{cmd.path}" "-C{config.path}" {bootloader.verbose} -p{build.mcu} -c{protocol} {program.extra_params} "-Uflash:w:{runtime.ide.path}/hardware/arduino/avr/bootloaders/{bootloader.file}:i" -Ulock:w:{bootloader.lock_bits}:m
    #==============================================================================

    Here is an example of the use of the tool avrdude1 in boards.txt file

    atmega8.name=ATmega8 OPTIBOOT
    atmega8.upload.protocol=arduino
    atmega8.upload.maximum_size=7168
    atmega8.upload.speed=115200
    atmega8.upload.tool=avrdude1
    atmega8.bootloader.low_fuses=0xbf
    atmega8.bootloader.high_fuses=0xCC
    atmega8.bootloader.path=atmega8
    atmega8.bootloader.file=optiboot/optiboot_atmega8.hex
    atmega8.bootloader.unlock_bits=0x3F
    atmega8.bootloader.lock_bits=0x0F
    atmega8.bootloader.tool=avrdude1
    atmega8.build.mcu=atmega8
    atmega8.build.f_cpu=16000000L
    atmega8.build.core=arduino
    atmega8.build.variant=standard