text:
Controlling DC motor from Android device
Ref: https://robotics.stackexchange.com/q/8526/11146
I want to build a simple android controlled robot
I will connect android phone<usb>arduino<wire>motor controller<wire>dc motor
I wonder why I have to write two programs (android java & arduino c++)?
How can I directly control the DC motor from android java program without writing arduino code?

You could possibly utilize something like Firmata with minimal modifications, or potentially use a USB I/O chip instead of an Arduino, but these are likely to be inferrior to a custom solution - if you aren't willing to touch something as accessible as Arduino code, it's questionable if the project is practical for you.

It's not clear what you'd like to do, but for some applications one of the simpler ways to do this would be to add a wifi module to the Arduino and use a simple web interface to get the commands from the Android.

The short answer is "you can't." For the Arduino to do anything useful it needs to have instructions telling it what to do. In your example the Arduino's job is to do something that the Android can't – turn on and off the DC motor. You could even use a wifi or Bluetooth connection from the Android to the Arduino to make it possible to avoid the hassle of the USB cable.
Your project requires a number of small hunks of code on the Arduino to:

Listen for commands from the Android.
Validate the commands received.
Turn on or off the motor.

Roughly speaking your loop() function might look something like this:
void loop() {
  // look for a command
  // validate the command
  if (valid && turn_motor_on) {
    motor_on();
  } else {
    motor_off();
  }
}

Fortunately the Arduino code can be very simple and there is a lot of example code to help you get started.


text:
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:
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:

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

Here is the code:
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.
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:
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)

your third file is malformed, def setScaleValue(): isn't defined properly, you need an indent level change after a function definition.

When your code runs, can you be able to click on stop button?

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.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
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("%0D%0A", String('\n'));

  urlChars.replace("+",   " ");
  urlChars.replace("%20", " ");
  urlChars.replace("%21", "!");
  urlChars.replace("%22", String(char('\"')));
  urlChars.replace("%23", "#");
  urlChars.replace("%24", "$");
  urlChars.replace("%25", "%");
  urlChars.replace("%26", "&");
  urlChars.replace("%27", String(char(39)));
  urlChars.replace("%28", "(");
  urlChars.replace("%29", ")");
  urlChars.replace("%2A", "*");
  urlChars.replace("%2B", "+");
  urlChars.replace("%2C", ",");
  urlChars.replace("%2D", "-");
  urlChars.replace("%2E", ".");
  urlChars.replace("%2F", "/");
  urlChars.replace("%30", "0");
  urlChars.replace("%31", "1");
  urlChars.replace("%32", "2");
  urlChars.replace("%33", "3");
  urlChars.replace("%34", "4");
  urlChars.replace("%35", "5");
  urlChars.replace("%36", "6");
  urlChars.replace("%37", "7");
  urlChars.replace("%38", "8");
  urlChars.replace("%39", "9");
  urlChars.replace("%3A", ":");
  urlChars.replace("%3B", ";");
  urlChars.replace("%3C", "<");
  urlChars.replace("%3D", "=");
  urlChars.replace("%3E", ">");
  urlChars.replace("%3F", "?");
  urlChars.replace("%40", "@");
  urlChars.replace("%41", "A");
  urlChars.replace("%42", "B");
  urlChars.replace("%43", "C");
  urlChars.replace("%44", "D");
  urlChars.replace("%45", "E");
  urlChars.replace("%46", "F");
  urlChars.replace("%47", "G");
  urlChars.replace("%48", "H");
  urlChars.replace("%49", "I");
  urlChars.replace("%4A", "J");
  urlChars.replace("%4B", "K");
  urlChars.replace("%4C", "L");
  urlChars.replace("%4D", "M");
  urlChars.replace("%4E", "N");
  urlChars.replace("%4F", "O");
  urlChars.replace("%50", "P");
  urlChars.replace("%51", "Q");
  urlChars.replace("%52", "R");
  urlChars.replace("%53", "S");
  urlChars.replace("%54", "T");
  urlChars.replace("%55", "U");
  urlChars.replace("%56", "V");
  urlChars.replace("%57", "W");
  urlChars.replace("%58", "X");
  urlChars.replace("%59", "Y");
  urlChars.replace("%5A", "Z");
  urlChars.replace("%5B", "[");
  urlChars.replace("%5C", String(char(65)));
  urlChars.replace("%5D", "]");
  urlChars.replace("%5E", "^");
  urlChars.replace("%5F", "_");
  urlChars.replace("%60", "`");
  urlChars.replace("%61", "a");
  urlChars.replace("%62", "b");
  urlChars.replace("%63", "c");
  urlChars.replace("%64", "d");
  urlChars.replace("%65", "e");
  urlChars.replace("%66", "f");
  urlChars.replace("%67", "g");
  urlChars.replace("%68", "h");
  urlChars.replace("%69", "i");
  urlChars.replace("%6A", "j");
  urlChars.replace("%6B", "k");
  urlChars.replace("%6C", "l");
  urlChars.replace("%6D", "m");
  urlChars.replace("%6E", "n");
  urlChars.replace("%6F", "o");
  urlChars.replace("%70", "p");
  urlChars.replace("%71", "q");
  urlChars.replace("%72", "r");
  urlChars.replace("%73", "s");
  urlChars.replace("%74", "t");
  urlChars.replace("%75", "u");
  urlChars.replace("%76", "v");
  urlChars.replace("%77", "w");
  urlChars.replace("%78", "x");
  urlChars.replace("%79", "y");
  urlChars.replace("%7A", "z");
  urlChars.replace("%7B", String(char(123)));
  urlChars.replace("%7C", "|");
  urlChars.replace("%7D", String(char(125)));
  urlChars.replace("%7E", "~");
  urlChars.replace("%7F", "Â");
  urlChars.replace("%80", "`");
  urlChars.replace("%81", "Â");
  urlChars.replace("%82", "â");
  urlChars.replace("%83", "Æ");
  urlChars.replace("%84", "â");
  urlChars.replace("%85", "â¦");
  urlChars.replace("%86", "â");
  urlChars.replace("%87", "â¡");
  urlChars.replace("%88", "Ë");
  urlChars.replace("%89", "â°");
  urlChars.replace("%8A", "Å");
  urlChars.replace("%8B", "â¹");
  urlChars.replace("%8C", "Å");
  urlChars.replace("%8D", "Â");
  urlChars.replace("%8E", "Å½");
  urlChars.replace("%8F", "Â");
  urlChars.replace("%90", "Â");
  urlChars.replace("%91", "â");
  urlChars.replace("%92", "â");
  urlChars.replace("%93", "â");
  urlChars.replace("%94", "â");
  urlChars.replace("%95", "â¢");
  urlChars.replace("%96", "â");
  urlChars.replace("%97", "â");
  urlChars.replace("%98", "Ë");
  urlChars.replace("%99", "â¢");
  urlChars.replace("%9A", "Å¡");
  urlChars.replace("%9B", "âº");
  urlChars.replace("%9C", "Å");
  urlChars.replace("%9D", "Â");
  urlChars.replace("%9E", "Å¾");
  urlChars.replace("%9F", "Å¸");
  urlChars.replace("%A0", "Â");
  urlChars.replace("%A1", "Â¡");
  urlChars.replace("%A2", "Â¢");
  urlChars.replace("%A3", "Â£");
  urlChars.replace("%A4", "Â¤");
  urlChars.replace("%A5", "Â¥");
  urlChars.replace("%A6", "Â¦");
  urlChars.replace("%A7", "Â§");
  urlChars.replace("%A8", "Â¨");
  urlChars.replace("%A9", "Â©");
  urlChars.replace("%AA", "Âª");
  urlChars.replace("%AB", "Â«");
  urlChars.replace("%AC", "Â¬");
  urlChars.replace("%AE", "Â®");
  urlChars.replace("%AF", "Â¯");
  urlChars.replace("%B0", "Â°");
  urlChars.replace("%B1", "Â±");
  urlChars.replace("%B2", "Â²");
  urlChars.replace("%B3", "Â³");
  urlChars.replace("%B4", "Â´");
  urlChars.replace("%B5", "Âµ");
  urlChars.replace("%B6", "Â¶");
  urlChars.replace("%B7", "Â·");
  urlChars.replace("%B8", "Â¸");
  urlChars.replace("%B9", "Â¹");
  urlChars.replace("%BA", "Âº");
  urlChars.replace("%BB", "Â»");
  urlChars.replace("%BC", "Â¼");
  urlChars.replace("%BD", "Â½");
  urlChars.replace("%BE", "Â¾");
  urlChars.replace("%BF", "Â¿");
  urlChars.replace("%C0", "Ã");
  urlChars.replace("%C1", "Ã");
  urlChars.replace("%C2", "Ã");
  urlChars.replace("%C3", "Ã");
  urlChars.replace("%C4", "Ã");
  urlChars.replace("%C5", "Ã");
  urlChars.replace("%C6", "Ã");
  urlChars.replace("%C7", "Ã");
  urlChars.replace("%C8", "Ã");
  urlChars.replace("%C9", "Ã");
  urlChars.replace("%CA", "Ã");
  urlChars.replace("%CB", "Ã");
  urlChars.replace("%CC", "Ã");
  urlChars.replace("%CD", "Ã");
  urlChars.replace("%CE", "Ã");
  urlChars.replace("%CF", "Ã");
  urlChars.replace("%D0", "Ã");
  urlChars.replace("%D1", "Ã");
  urlChars.replace("%D2", "Ã");
  urlChars.replace("%D3", "Ã");
  urlChars.replace("%D4", "Ã");
  urlChars.replace("%D5", "Ã");
  urlChars.replace("%D6", "Ã");
  urlChars.replace("%D7", "Ã");
  urlChars.replace("%D8", "Ã");
  urlChars.replace("%D9", "Ã");
  urlChars.replace("%DA", "Ã");
  urlChars.replace("%DB", "Ã");
  urlChars.replace("%DC", "Ã");
  urlChars.replace("%DD", "Ã");
  urlChars.replace("%DE", "Ã");
  urlChars.replace("%DF", "Ã");
  urlChars.replace("%E0", "Ã");
  urlChars.replace("%E1", "Ã¡");
  urlChars.replace("%E2", "Ã¢");
  urlChars.replace("%E3", "Ã£");
  urlChars.replace("%E4", "Ã¤");
  urlChars.replace("%E5", "Ã¥");
  urlChars.replace("%E6", "Ã¦");
  urlChars.replace("%E7", "Ã§");
  urlChars.replace("%E8", "Ã¨");
  urlChars.replace("%E9", "Ã©");
  urlChars.replace("%EA", "Ãª");
  urlChars.replace("%EB", "Ã«");
  urlChars.replace("%EC", "Ã¬");
  urlChars.replace("%ED", "Ã");
  urlChars.replace("%EE", "Ã®");
  urlChars.replace("%EF", "Ã¯");
  urlChars.replace("%F0", "Ã°");
  urlChars.replace("%F1", "Ã±");
  urlChars.replace("%F2", "Ã²");
  urlChars.replace("%F3", "Ã³");
  urlChars.replace("%F4", "Ã´");
  urlChars.replace("%F5", "Ãµ");
  urlChars.replace("%F6", "Ã¶");
  urlChars.replace("%F7", "Ã·");
  urlChars.replace("%F8", "Ã¸");
  urlChars.replace("%F9", "Ã¹");
  urlChars.replace("%FA", "Ãº");
  urlChars.replace("%FB", "Ã»");
  urlChars.replace("%FC", "Ã¼");
  urlChars.replace("%FD", "Ã½");
  urlChars.replace("%FE", "Ã¾");
  urlChars.replace("%FF", "Ã¿");

  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.

very good for me .
but in the line urlChars.replace("%5C", String(char(65)));
I have String(char(123))); .... or ""

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%20there%3A%20majenko";

// 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

+35: Thank you very much! I'm not a C/C++ programmer, I only used Bash, Python and Gambas3 with a good level ;-). I'm beginning to contribute to this project: https://github.com/esp8266/Basic and I wanted to simplify the above code because it seemed ugly and badly implemented. However, would you recommend me to drop the use of String on all the project, or should I convert the input String to a char?

Strings are lazy and overly wasteful of resources. Not as critical on an esp8266 as it is on an Arduino, but still not good. I never ever use them.

I wrote a Tiny web server 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%21bar" (turn %21 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

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
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:

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

OR

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.

This sounds like a problem with the fuse bit configuration - specifically, that you are running with an internal oscillator and with a divider configuration that gives you a 1 MHz clock rate.

Second the fuse bits. Try selecting burn bootloader in the arduino menu, as that should set the correct fuses.

I checked it, and in boards.txt, my fuses are set to 0xDF (low) and 0xCA, which, according to this (http://www.engbedded.com/fusecalc) should set to external crystal. I even tried to change low to 0x4C, which should run it at 8MHz internally, but it had no effect...

Gerben: Avrdude returns: "efuse" memory type not defined for part "ATmega8"... I dont know what an efuse is...

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.


text:
Flexiforce to Uno to Keyboard. Working but not as inteded
I have a Flexiforce 25 pound pressure sensors connected to my Arduino Uno which connects to my laptop. My requirement is to be able to play video games using taps on pressure sensors. I am successfully sending signals to my Laptop and I am using Java on my Mac to send keystrokes (Key Down and Key Up) signals to move in the game. However I am facing issues with long key down and key up. How do I detect that and make sure that my program runs smooth?
Uno code:
void setup() {}

void loop() {
int sensorValue = analogRead(A0);
int sensorValue2 = analogRead(A1);
int sensorValue3 = analogRead(A2);
int sensorValue4 = analogRead(A3);
int sensorValue5 = analogRead(A4);
int sensorValue6 = digitalRead(2);

// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage = sensorValue * (5.0 / 1023.0);
float voltage2 = sensorValue2 * (5.0 / 1023.0);
float voltage3 = sensorValue3 * (5.0 / 1023.0);
float voltage4 = sensorValue4 * (5.0 / 1023.0);
float voltage5 = sensorValue5 * (5.0 / 1023.0);
float voltage6 = sensorValue6 * (5.0 / 1023.0);

if(voltage > 1){
   Serial.begin(9600); Serial.println("A0"); Serial.end();
}
if(voltage2 > 1){
   Serial.begin(9600); Serial.println("A1"); Serial.end();
}
if(voltage3 > 1){
   Serial.begin(9600); Serial.println("A2"); Serial.end();
}
if(voltage4 > 1){
   Serial.begin(9600); Serial.println("A3"); Serial.end();
}
if(voltage5 > 1){
   Serial.begin(9600); Serial.println("A4"); Serial.end();
}
if(voltage6 > 0){
   Serial.begin(9600); Serial.println("D2"); Serial.end();
}
// Wait 100 milliseconds
delay(100);
}

In java I'm using java.wt.Robot and gnu.io.SerialPort to press key and read from serial port. On a serialEvent I will override the listener function to perform my operation which is press Keys on my machine.
Java Code:
public void serialEvent(SerialPortEvent oEvent) {
    if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
        try {
            String inputLine = null;
            if (input.ready()) {
                inputLine = input.readLine();
                if (inputLine.contains("A0")) {

                    long start = System.currentTimeMillis();
                    while (System.currentTimeMillis() - start < duration) {
                        robot.keyPress(KeyEvent.VK_UP);
                    }
                    robot.keyRelease(KeyEvent.VK_UP);
                    System.out.println("UP");

                } else if (inputLine.contains("A1")) {

                    long start = System.currentTimeMillis();
                    while (System.currentTimeMillis() - start < duration) {
                        robot.keyPress(KeyEvent.VK_DOWN);
                    }
                    robot.keyRelease(KeyEvent.VK_DOWN);
                    System.out.println("DOWN");

                } else if (inputLine.contains("A2")) {

                    long start = System.currentTimeMillis();
                    while (System.currentTimeMillis() - start < duration) {
                        robot.keyPress(KeyEvent.VK_LEFT);
                    }
                    robot.keyRelease(KeyEvent.VK_LEFT);
                    System.out.println("LEFT");

                } else if (inputLine.contains("A3")) {

                    long start = System.currentTimeMillis();
                    while (System.currentTimeMillis() - start < duration) {
                        robot.keyPress(KeyEvent.VK_RIGHT);
                    }
                    robot.keyRelease(KeyEvent.VK_RIGHT);
                    System.out.println("RIGHT");

                } else if (inputLine.contains("A4")) {

                    long start = System.currentTimeMillis();
                    while (System.currentTimeMillis() - start < duration) {
                        robot.keyPress(KeyEvent.VK_S);
                    }
                    robot.keyRelease(KeyEvent.VK_S);
                    System.out.println("S");

                } else if (inputLine.contains("D2")) {
                    robot.keyPress(KeyEvent.VK_D);
                    robot.keyRelease(KeyEvent.VK_D);
                    System.out.println("D");

                }
            }

        } catch (Exception e) {
            System.err.println(e.toString());
        }
    }
}

This performs Up, Down, Left, Right, "S" and "D" operation for SuperMario 3 GBA game. This works but not as smooth as intended. Is there anything that I can use to directly bind to my keyboard to get a smoother key operations.


text:
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, 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 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).

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 ?

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().

Hello and thanks for your answer. The code I supplied was previously working, your LiquidCrystal_I2C lib should be different if you don't have at all the same ctor than mine. But I'll do a try with yours to see if if fixes my problem.

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

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...

Hello, thank you very much to confirm the behaviour I've seen. I had not time yet to look for other solutions like the suggestion of jwpat7.

I have had same problem, issued on v1.6.7 and v1.6.8. I solved it with the new 'marcoschwartz' library 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.

Welcome on Arduino Stack Exchange. "Thanks" and "Me too" answers aren't really considered usefull (http://meta.stackexchange.com/questions/256378/are-me-too-answers-considered-a-noisy-answer-detailed-in-the-faq). In your case, you do give some interesting information, but keep it in mind. You should only add an answer if it is different from another answer given and will actually answer the question.

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.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
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.

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).


text:
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?

How much current does it use currently? What's that black stuff underneath the IC? I don't think heat is an issue, as the ATMega has a temperature range of -40C to 85C.

The black thing is an ic holder, like the one on UNO boards. I powered it at 3.3v and it worked fine in air.

I asked for current, not voltage. I the future I'd solder wires directly to the IC, instead of using a IC holder.

For your next try, use a conformal coating (and test it) before molding it into the resin.  Replace any switches with corresponding jumpers

my bad I just measured it at 50µA ?

One could easily imagine resin seeping into the ic pin - socket interface and pushing the contacts out of contact.

I tried sealing it with nail polish then putting it in resin and it worked! And this time I have it set up so I can reprogram if needed!

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.


text:
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.
#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;
}

Welcome Michael. First, just a suggestion, in line 30 and 36 change the ~ to !. Now just clarify us one thing. Suppose you start arduino and press the the buttonPin once. You make both relays ON. Now with remote you make relay 1 OFF. So current state is relay1 OFF and relay2 ON. Now you press the buttonPin again. What do you want the new relay states to be? (not what is happening right now, what you intend to be)

Thank you! That changes has solved one issue of being able to turn on the relays from the remote while first being in the off state with the button.  To answer your question: I was hoping to turn both relays off or on using the button (like an all on all off switch/override) which works when both are on or off but if one is on and the other is off they toggle opposite to each other, so I guess it is doing what the code is telling it to do, just not the way I want it. I want the one that is left on to turn off with the button then when i press the button again both will turn on. Thank you!

That's because you're telling it "relay1State = !relay1State;". IE invert the relays' state when you press the button. If you want them both to go off and on together, you need an extra variable, to store whether the next time you press the button, you want on or off. So have the button flip that variable, then whatever value that variable is, send that to the relays. Also at the top, "int relay1State;" should be "int relay1State=0;" because in your setup, you send that state to relay1 without defining it first. By luck, it works anyway.

Also I should add, having the button do on AND off is a bit confusing! If one is on, other is off, then which state do you want them both to go to when you press it? I suppose if you only have one button you're a bit constrained by that. A better design would involve buying another button! Then you'd have one ON and one OFF. And the user would know which one to expect, where if currently you have one relay in each state, should the button switch them on or off? Maybe an LED or something could inform the user of that, but an extra button would be better I think.

So according to your comments this should be the code if no mistake was made
#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.

You sir are a big help! That's solved my problems! I'm not sure I totally understand how my program works just yet but it's slowly sinking in. But I can say I have learned much more and quicker by just getting stuck in and attempting small projects, rather than just reading book after book or watching tutorial after tutorial. Program to learn, not learn to program I think they say :)  Thanks again for your help. That was a real head scratch-er for me!  Think I might fire a photo-resister into the mix now..why not eh? This is fun! :D

Go on Michael. Keep testing things. To help you undertstand your original code, what you did was invert the current state of the relays when you pushed the buttonPin. The ! gives you the logical not of a variable. So if a var is 1, true, using ! will give the negation of that var. This is why you needed a master state to do what you wanted. Go on and keep practicing! Happy coding

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
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.

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
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):
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 with a well documented classes for adlx345 and ITG3200.
Edit:
This caused me no problem. That is the only 2 functions I changed:
// 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:
#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

Thank you I will try this in the morning. I can see I did not realize I was not reading the data when I requested it.

Sorry, it did not work...
I am now getting something in the range of 0-256, only positive values, and they vary widely. I've seen 92 as minimum and 230 as maximum.
I modified your code ||      I2c.read(dev_address, address, num)  // request 6 bytes from device
|| --> ||      I2c.read(address, (byte) num);  // request 6 bytes from device
|| and it compiled.

*This is while it is lying on the table. Left to run for about a minutes. The code in general prints to serial about 7Hz as tested a week ago.

have you changed all the other functions?

@JohnDoe I managed to get an adlx345 for testing communication and all went fine apparently. Look at updated code for the read with the forced casts. However, I really advise you that this can result in many mistakes. I couldn't find any documentation for the I2C library you are suggesting.

I am forever grateful for your help. I'm away from the office for the holiday week, and look forward to trying this when I get back.

solved at this time.


text:
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();
    }
  }
}

you may use mqtt protocol, it support push notifications instead of polling and it's way lighter

Yeah I thought about that, but I could not imagine that push is faster than polling. Is it?

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.

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!


text:
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());
  }
}

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.

but can i read the message then on my hardwired serial monitor with one arduino?

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.

have a look at this posts on Aerduino forum same problem https://forum.arduino.cc/index.php?topic=409654.0


text:
SRF-02 UART, transmitting from one address to another
So I just starting playing around with UART and SoftwareSerial while playing with these SRF-02 Sensors - http://www.robot-electronics.co.uk/htm/srf02techSer.htm
I need help getting one to read to the other, I have been using this, makes sense logically, but doesn't work. I was thinking I'm missing something important for the synchronization of both sensors to one another.
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 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 int reading;
  SendCmd(0x00,0x5C);//Transmit 8 cycle 40khz pulse from adress 0x00
  delay(70);//time for SRF02 to measure the range
  SendCmd(0x02,0x5E);//Get Range, returns two bytes (high byte first) from the most recent ranging to adress 0x02
   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");
  }
  delay(250); // wait a bit since people have to read the output :)
}


text:
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?

Ultrasonic chirp, or an (human) audible chirp? It sound to me like the teacher doesn't know what he/she is talking about.

Why won't usual ultrasoud modules work - are they physically limited to a narrow range of frequencies? (I know they are usually run at a particular frequency, but if driven at other frequencies there might still be a measurable response - is it just a case of doing some tests?)

The most common ultrasonic modules for Arduino use have self-contained pulse generation and detection (actually done by abusing a serial line driver charge pump chip!)  To build a chirp system you would need transducer(s) with a suitable bandwith, and either a chirp generator/detector or interface/conversion circuitry to put a DSP algorithm in those roles.

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.


text:
"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:
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 :)

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.

Its using the ICSP headers to power the board :) But this makes sense. The board (and the arduino, and the extra hardware) would need an interrupt controller to check whoose turn it is to listen / write to the ports, if I understand correctly. Thanks for the answer!

Interrupts are far from the only means of deconflicting.


text:
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?

It sound a lot like the OverTheAir update system used by Moteino. They use an external SPI flash chip to store any updates. The main program check for updates and downloads them (and then reset the board). The bootloader only has to read the flash chip to see if there is an update. This will make the bootloader a lot smaller. Imagine having to load the GPRS library in both your main program and the bootloader. It also makes things less likely to go wrong.

Thanks, thats interesting. I might be able to use some information from that system. I have some information to get me started :) Thanks a ton guys!

@RobQuist Did you managed to update the arduino using GPRS?

@MuzahirHussain No, sorry! It was a fun project to work on but never came around on doing it. I did manage to write a ATMEGA328P chip to flash other ATMEGA328P chips, so it probably is doable just like described up here :)

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:

The GPRS is connected to Arduino A.
Your main software runs on Ardiuno B.
Both Arduinos are connected by serial
Normal operation Arduino A passes all serial verbatim through to Arduno B
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.
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.

Cool! Thats the answer I was looking for. But instead of using an extra Arduino, wouldn't it be possible to download the hex file to some persistant storage, and tell the bootloader to restart, and write that hex file to the ATMega, and restart the arduino? I've seen some external bootloader thingsies like these; https://learn.sparkfun.com/tutorials/installing-an-arduino-bootloader/uploading-code---hard-way - would it be possible to use that? It would require less space and save me an arduino :)

You could do it with one Arduino, but you will need to write a custom bootloader which knows what you are doing - you could download to SD card then reboot into a bootloader that understands what an SD card is and can find your file on it, but again it's not a trivial bit of programming.  By the way, the "bootloader" is just a special sketch that runs on the Arduino before your sketch runs. It's not an external thing. It's just software that has to be installed on the main chip before it becomes an Arduino.

Cool, thanks. That'll help me get started :)


text:
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.

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.

This is not a very useful answer - first it is based on speculation rather than facts, and second your proposal "just getting an actual tag" ignores the question's goal that "the data should be supplied by the Arduino".


text:
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.

Yes. It's called #include.

cases that can't be separated out into functions. This sounds very wrong. If you can't break you code into smaller chuck, creating separate files isn't going to much, and will probably make your code even harder to understand.

In those -few- cases where there are really complex sets of parameters, the usual solution is to pass them through a struct.

Or you can use global variables... Or just use the include (remember to call your file "xxx.h" instead of "xxx.ino", otherwise the compiler will try to compile it twice, thus giving errors)

Thanks for responding! Could you guys please look at the edit I made at the bottom of the question, and tell me what you think?

I'm surprised that #include can be used like that, because the official Arduino page on Include says this: #include is used to include outside libraries in your sketch. But if it works for things other than libraries, maybe it would be a good solution for me! I'll try it out after I get some further input.

@Jerry Check my answer... you can use it as long as you use it properly ;)

You should also use PROGMEM, otherwise those variables also end up in RAM. See Putting constant data into program memory (PROGMEM) for details.

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;

This will work only if you include the h files just once. As soon as you include them in two cpp/ino files you will get linker errors. The usual way is to split definition and declaration in two files and use extern to notify the linker to search for them somewhere else. Check my answer for what i think is the correct way to deal with shared variables

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


text:
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:

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.

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?

"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

I tried but still not working. Should I use JP3 pins on Lilypad board directly? But, how can I program directly ATmega 328 ? What I need?

“device "\.\COM4” looks like an odd name.  I don't have an MSWindows system, but perhaps you know if it's an ok name.

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?
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.


text:
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?

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);
}

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.

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.


text:
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)

Is the data always going to be triplets of RCP/CMD/VAL?

No, I'd like to be able to add like: VAL1, VAL2, or RESP=1 or something like that. Is this possible?

I've read this twice, but I can't find any question.

My apologies Gerben, I should've been clearer. But it has already been solved. Thanks for commenting anyway. :)

Why not use a library like RF24Mesh that does all this for you.

You're right, that is a more sensible way to go. Thanks for the heads up! Got the example working today and I'll be rewriting the current functionality to work with RF24Mesh. Again, thanks! :)

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.

Thank you very much! So it boils down to the fact that Arduino's have a small amount of memory and thus aren't suitable for dynamic memory allocation like a higher level language would be? I think I'll be able to think of a reasonable max amount of commands. The reason I wanted to have it dynamic was that newer version of my "master" might want to send more commands, but I could implement a type of version check on the client so the master knows if he is capable of those commands. Again, thanks :)

The lowest (RAM) memory footprint would to act on the information as it is received, and so basically avoid storing commands at all, except for a small (provided by Arduino anyway) circular buffer between the serial port and main-loop parsing.


text:
Multiple servos noise
I'm building  an application that uses 20 servo motors, and i control then with an Arduino Mega. The servos are having some instability, to the point where they make small random swings. Im powering then from a 7.4V LiPo battery and I drop the voltage to around 6V with 2 series diodes. I've made some research and found 4 things that may help stabilize the servos.

Put a 1000uF eletrolitic capacitor between the battery VCC and GND pins.
Put a 470uF eletrolitic capacitor between each servo VCC and GND pins.
Put a 100nF ceramic capacitor between each servo SIGNAL and GND pins.
Put a 10k pull-up resistor on each servo SIGNAL pin.

My question is, how to make the right decision here. It is better for the project if I take all this designs into account, or I shouldn't be making some combination of this, or one in particular?

My first question is do you have enough power available? As the servos work they may be drawing enough current to pull down your power supply. The capacitors will help, but have you actually checked so see if they are sufficient?

The battery is strong enought to keep 7.4V out while the servos are on.

OK, so probably not that…

Do u use a software serial? That can make you're servos jitter because it uses the same interupts as the servo lib.

I don't think that 7.4V are good for servos. And if very little current is drawn, the diodes have a much lower voltage drop. Measure the voltage after the diodes with an oscilloscope. And then I suggest you to fix your power supply part: use a LDO if the battery voltage is high enough even under stress or a buck-boost module to stabilize it even under heavy load. I prefer the second one, but it depends on you. Probably it can be better to split the 20 motors group in smaller groups to use less costly converters

I've tested the voltage after diode voltage drop and its normaly around 6V, that may not be the problem. The servos consume a mean current of 15 to 20 amps, so the low current drawn problem problaby don't interfere. Im thinking the problem is more due to signal.

I've used it a bit. I'll check that as soon as I can. Do you have any idea how to solve this, because I really need to use both.

This is a bad design!  Your "7.2v"  battery when freshly charged will be 8.4v, which means around 7.2v to the servos, in excess of normal ratings.  Further, the voltage drop through a diode is not truly constant, but current dependent, and your current varies widely depending on how many servos are moving to a new position or stalled.  Use proven battery eliminator circuits or possible switch regulator modules.  Also consider using only a few servos per supply module.

You can use the old software serial library from mikal heart. that one does not die interupts. You can do a google search on it.
here is a forum topic about it:
http://forum.arduino.cc/index.php?topic=82596.0


text:
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.

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.


text:
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:
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:
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?

Not sure what your problem is, but I'd try a "delay" in loop after the call to demoBasic. I'd start with 100 ms. Maybe your code execute "too fast" then the js function gets blocked.

@fabrosell i tried doing that also but still there was problem.Can you suggest any othing thing which might solve issue.

If you have any working code which continuously able to push data to Parse.com,can you share that ?

I'm sorry, I do not have any. Either way, it's a very strange behavior if function gets called just 8 times and no more...

At what point in the code does the program flow "get blocked"?

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());
}