text:
Error in code saying "expected primary expression before "<" token" and other errors
I am Creating a laptop controlled robot using an arduino nano using the instructbles. I have tried running the code but it is throwing back lots off error and the main one is "expected primary expression before "<" token"
as well as various other error. if anyone could take a look and try help me out i would be grateful thank you!
#include <NewPing.h>

#include <LiquidCrystal.h>

LiquidCrystal lcd(11, 8, 7, 4, 3, 2);
float temp =1;
int temppin = A0;
int r_motor_n = 9; //PWM control Right Motor +
int r_motor_p = 10; //PWM control Right Motor -
int l_motor_p = 6; //PWM control Left Motor -
int l_motor_n = 5; //PWM control Left Motor +
int f_light = A3;
int b_light = A4;
int horn = 12;
int n_light = 13;
int speedy = 255;
int incomingByte = 0; // for incoming serial data
#define TRIGGER A2 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO A1 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX 400 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
NewPing sonar(TRIGGER, ECHO, MAX); // NewPing setup of pins and maximum distance.
void setup()
{
pinMode(r_motor_n, OUTPUT); //Set control pins to be outputs
pinMode(r_motor_p, OUTPUT);
pinMode(l_motor_p, OUTPUT);
pinMode(l_motor_n, OUTPUT);
pinMode(f_light, OUTPUT);
pinMode(b_light, OUTPUT);
pinMode(n_light, OUTPUT);
pinMode(horn, OUTPUT);
digitalWrite(r_motor_n, LOW); //set both motors off for start-up
digitalWrite(r_motor_p, LOW);
digitalWrite(l_motor_p, LOW);
digitalWrite(l_motor_n, LOW);
Serial.begin(9600);
Serial.println("Start");
lcd.begin(16,2);
lcd.clear();
lcd.print("     Hello      ");
lcd.setCursor(0,1);
lcd.print("   I'm Robot   ");
delay(3000);
}
void loop()
{</liquidcrystal.h></newping.h>

if (Serial.available() > 0)
{
incomingByte = Serial.read();
}

switch(incomingByte)
{

case 'S': // control to stop the robot
digitalWrite(r_motor_n, LOW);
digitalWrite(r_motor_p, LOW);
digitalWrite(l_motor_p, LOW);
digitalWrite(l_motor_n, LOW);
Serial.println("Stop");
lcd.clear();
lcd.print("Stop");
incomingByte='*';
break;

case 'R': //control for right
analogWrite(r_motor_n, speedy);
digitalWrite(r_motor_p, LOW);
analogWrite(l_motor_p, speedy);
digitalWrite(l_motor_n, LOW);
Serial.println("right");
lcd.clear();
lcd.print("Right");
incomingByte='*';
break;

case 'L': //control for left
digitalWrite(r_motor_n, LOW);
analogWrite(r_motor_p, speedy);
digitalWrite(l_motor_p, LOW);
analogWrite(l_motor_n, speedy);
Serial.println("left");
lcd.clear();
lcd.print("Left");
incomingByte='*';
break;

case 'F': //control for forward
analogWrite(r_motor_n, speedy);
digitalWrite(r_motor_p, LOW);
digitalWrite(l_motor_p, LOW);
analogWrite(l_motor_n, speedy);
Serial.println("forward");
lcd.clear();
lcd.print("Forward");
incomingByte='*';
break;

case 'B': //control for backward
digitalWrite(r_motor_n, LOW);
analogWrite(r_motor_p, speedy);
analogWrite(l_motor_p, speedy);
digitalWrite(l_motor_n, LOW);
Serial.println("backwards");
lcd.clear();
lcd.print("Backward");
incomingByte='*';
break;

case 'f': //control for stop
digitalWrite(r_motor_n, LOW);
digitalWrite(r_motor_p, LOW);
digitalWrite(l_motor_p, LOW);
digitalWrite(l_motor_n, LOW);
Serial.println("Stop");
lcd.clear();
lcd.print("Stop");
incomingByte='*';
break;

case 'd': // control for right
analogWrite(r_motor_n, speedy);
digitalWrite(r_motor_p, LOW);
analogWrite(l_motor_p, speedy);
digitalWrite(l_motor_n, LOW);
Serial.println("right");
lcd.clear();
lcd.print("Right");
incomingByte='*';
break;

case 'a': // control for left
digitalWrite(r_motor_n, LOW);
analogWrite(r_motor_p, speedy);
digitalWrite(l_motor_p, LOW);
analogWrite(l_motor_n, speedy);
Serial.println("left");
lcd.clear();
lcd.print("Left");
incomingByte='*';
break;

case 'w': // control for forward
analogWrite(r_motor_n, speedy);
digitalWrite(r_motor_p, LOW);
digitalWrite(l_motor_p, LOW);
analogWrite(l_motor_n, speedy);
Serial.println("forward");
lcd.clear();
lcd.print("Forward");
incomingByte='*';
break;

case 's': // control for backward
digitalWrite(r_motor_n, LOW);
analogWrite(r_motor_p, speedy);
analogWrite(l_motor_p, speedy);
digitalWrite(l_motor_n, LOW);
Serial.println("backwards");
lcd.clear();
lcd.print("Backward");
incomingByte='*';
break;

case 'J': // front lights on
digitalWrite(f_light, HIGH);
Serial.println("front lights on");
incomingByte='*';
break;

case 'j':
digitalWrite(f_light, LOW); // off
Serial.println("front lights off");
incomingByte='*';
break;

case 'K':
digitalWrite(b_light, HIGH); // back lights on
Serial.println("back lights on");
incomingByte='*';
break;

case 'k':
digitalWrite(b_light, LOW); // off
Serial.println("back lights off");
incomingByte='*';
break;

case 'G':
digitalWrite(n_light, HIGH); // neon lights on
Serial.println("neon lights on");
incomingByte='*';
break;

case 'g':
digitalWrite(n_light, LOW); off
Serial.println("neon lights off");
incomingByte='*';
break;

case 'H':
digitalWrite(horn, HIGH); // horn on
Serial.println("horn on");
incomingByte='*';
break;

case 'h':
digitalWrite(horn, LOW); off
Serial.println("horn off");
incomingByte='*';
break;

case 'O': // PWM speed values
speedy = 0 ;
Serial.println("speed= 0");
lcd.clear();
lcd.print("Speed=0");
incomingByte='*';
break;

case '1':
speedy = 155;
Serial.println("speed= 10");
lcd.clear();
lcd.print("Speed=10");
incomingByte='*';
break;

case '2':
speedy = 165;
Serial.println("speed= 20");
lcd.clear();
lcd.print("Speed=20");
incomingByte='*';
break;

case '3':
speedy = 175;
Serial.println("speed= 30");
lcd.clear();
lcd.print("Speed =30");
incomingByte='*';
break;

case '4':
speedy = 185;
Serial.println("speed= 40");
lcd.clear();
lcd.print("Speed=40");
incomingByte='*';
break;

case '5':
speedy = 195;
Serial.println("speed= 50");
lcd.clear();
lcd.print("Speed=50");
incomingByte='*';
break;

case '6':
speedy = 205;
Serial.println("speed= 60");
lcd.clear();
lcd.print("Speed=60");
incomingByte='*';
break;

case '7':
speedy = 215;
Serial.println("speed= 70");
lcd.clear();
lcd.print("Speed=70");
incomingByte='*';
break;

case '8':
speedy = 225;
Serial.println("speed= 80");
lcd.clear();
lcd.print("Speed=80");
incomingByte='*';
break;

case '9':
speedy = 235;
Serial.println("speed= 90");
lcd.clear();
lcd.print("Speed=90");
incomingByte='*';
break;

case 'q':
speedy = 255;
Serial.println("speed= 100");
lcd.clear();
lcd.print("Speed=100");
incomingByte='*';
break;

case 'p':
delay(50);  // display temp. and distance
unsigned int uS = sonar.ping();
Serial.print("Distance: ");
Serial.print(uS / US_ROUNDTRIP_CM);
Serial.println("cm");
lcd.clear();
lcd.print("Distance: ");
lcd.print(uS / US_ROUNDTRIP_CM);
lcd.print("cm");
lcd.setCursor(0,1);
temp = analogRead(temppin);
temp = temp * 0.48828125;
Serial.print("Temperature = ");
Serial.print(temp);
Serial.print("*C");
Serial.println();
lcd.print("Temp. = ");
lcd.print(temp);
lcd.print("*C");
delay(1000);
incomingByte='*';
break;

delay(5000);
}
}

Did you bother reading the code you copied from this site? It seems not. Just a quick browse will reveal some HTML in the middle of it (
...) This is wrong on the instructable site, so you have to clean up the code by yourself.

your code is ridden with html tags, like

 or </liquidcrystal.h></newping.h>
Try removing them all, but it would be better if you could copy it from a plain ASCII source.
And when reporting a compiler bug, it's always good to paste it exactly as it is shown (it would have listed also line and possibly column where the error was detected)

It's like that on the Instructables site. Sigh. Laptop Controlled Robot v2.0


text:
Changing ESP8266 WiFi network via Access Point
I have an ESP8266 project that requires setting the SSID and password for a network via an Access Point.  Everything works fine, the only issue is if you send incorrect credentials to the access point, the server returns an empty response before the timeout period elapses, and the error message is never sent to the client.
If the connection is successful then the success message is appropriately sent to the client.  It's almost like the WiFi.begin() function detects the connection fails on its own, and something there is preventing me from sending my own response.
%  curl -X POST "http://192.168.1.1/authenticate?ssid=FakeNetworkpassword=87654321"
curl: (52) Empty reply from server

Did some research and saw some mentions to keep the loop running, so I attempted to do so below, but to no avail.  Would appreciate any ideas, thanks.
#include "ESP8266WiFi.h"
#include "ESP8266HTTPClient.h"
#include "ESP8266WebServer.h"

HTTPClient http;
WiFiClient client;

ESP8266WebServer server(80);
IPAddress ipAP(192, 168, 1, 1);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);

unsigned long previousMillisConnection = 0;
unsigned long startingMillisConnection = 0;
const unsigned long CONNECTION_PERIOD = 1000;
const unsigned long CONNECTION_TIMEOUT = 10000;

int DELAY = 40;

char ssid[64] = { 0 };
char password[64] = { 0 };

char ssidNew[64];
char passNew[64];

const int STATE_DEFAULT = 0;
const int STATE_CREDS = 1;
int state = STATE_DEFAULT;

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

  WiFi.softAPConfig(ipAP, gateway, subnet);
  WiFi.softAP("ESP8266", "12345678");
  delay(100);

  server.on("/authenticate", HTTP_POST, onSetCredentials);
  server.begin();

  performWifiConnect(ssid, password);
  WiFi.waitForConnectResult(CONNECTION_TIMEOUT);

  Serial.println("Initialization complete");
}

void loop() {
  if (state == STATE_DEFAULT) {
    server.handleClient();
    if (WiFi.status() == WL_CONNECTED) {
      Serial.println("Connected!");
    }
  }

  else if (state == STATE_CREDS) {
    whileConnecting();
  }

  delay(DELAY);
}

void performWifiConnect(char ssid[], char password[]) {
  Serial.println("Attempting to connect to " + String(ssid) + "...");
  WiFi.setAutoReconnect(false);
  WiFi.persistent(false);
  WiFi.begin(ssid, password);
}

void onWifiConnected() {
  Serial.println("WiFi connected " + WiFi.localIP().toString());
  WiFi.setAutoReconnect(true);
  WiFi.persistent(true);
}

void onSetCredentials() {
  Serial.println("onSetCredentials");

  server.arg("ssid").toCharArray(ssidNew, 64);
  server.arg("password").toCharArray(passNew, 64);

  if (String(ssidNew) == String(ssid) && WiFi.status() == WL_CONNECTED) {
    Serial.println("Already connected to " + String(ssidNew));
    server.send(200, "application/json", "{ \"success\": true, \"changed\": false }");
  } else {
    Serial.println("Switching from " + String(ssid) + " to " + String(ssidNew));
    state = STATE_CREDS;
    performWifiConnect(ssidNew, passNew);
    startingMillisConnection = millis();
  }
}

void whileConnecting() {
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillisConnection >= CONNECTION_PERIOD) {
    previousMillisConnection = currentMillis;

    Serial.println("checking connection...");

    // Success
    if (WiFi.status() == WL_CONNECTED) {
      Serial.println("Connected to " + String(ssidNew) + " successfully!");

      strcpy(ssid, ssidNew);
      strcpy(password, passNew);

      server.send(200, "application/json", "{ \"success\": true, \"changed\": true }");

      state = STATE_DEFAULT;
    }

    // Failure
    if (currentMillis - startingMillisConnection >= CONNECTION_TIMEOUT) {
      Serial.println("connection failed, attempting to reconnect to old network!");
      Serial.println("ssidOld: " + String(ssid));
      Serial.println("passOld: " + String(password));

      String errorMessage = "Timed out while attempting to connect to " + String(ssidNew);
      Serial.println(errorMessage);
      server.send(500, "application/json", "{\"errorMessage\":\"" + errorMessage + "\"}");

      performWifiConnect(ssid, password);

      WiFi.waitForConnectResult(CONNECTION_TIMEOUT);

      state = STATE_DEFAULT;

      if (WiFi.status() != WL_CONNECTED) {
        Serial.println("Could not return to old network!");
      }
    }
  }
}

I recommend you to use the WiFiManager library. It has the WiFi provisioning solved.

To join an AP esp8266 must change the WiFi radio channel to the channel of the AP. Since the esp8266 has only one radio, the SoftAP must change the channel too. This causes the SoftAP clients to disconnect.
The solution is respond to the configuration request before connecting to AP, then let the configuration page do a new request for the result.
To illustrate here is a simple example:
#ifdef ESP32
#include <WiFi.h>
#else
#include <ESP8266WiFi.h>
#endif

void setup() {

  Serial.begin(115200);
  delay(500);

#ifdef ESP32
//  WiFi.begin(); // use SSID and password stored by SDK. commented out to test the Configuration AP
#else
//  WiFi.disconnect(); // forget the persistent connection to test the Configuration AP
#endif

  // waiting for connection to remembered  Wifi network
  Serial.println("Waiting for connection to WiFi");
  WiFi.waitForConnectResult();

  if (WiFi.status() != WL_CONNECTED) {
    Serial.println();
    Serial.println("Could not connect to WiFi. Starting configuration AP...");
    configAP();
  } else {
    Serial.println("WiFi connected");
  }
}

void loop() {
}

void configAP() {

  WiFiServer configWebServer(80);

  WiFi.mode(WIFI_AP_STA); // starts the default AP (factory default or setup as persistent)

  Serial.print("Connect your computer to the WiFi network ");
#ifdef ESP32
  Serial.print("to SSID of you ESP32"); // no getter for SoftAP SSID
#else
  Serial.print(WiFi.softAPSSID());
#endif
  Serial.println();
  IPAddress ip = WiFi.softAPIP();
  Serial.print("and enter http://");
  Serial.print(ip);
  Serial.println(" in a Web browser");

  configWebServer.begin();

  while (true) {

    WiFiClient client = configWebServer.available();
    if (client) {
      char line[64];
      int l = client.readBytesUntil('\n', line, sizeof(line));
      line[l] = 0;
      client.find((char*) "\r\n\r\n");
      if (strncmp_P(line, PSTR("POST"), strlen("POST")) == 0) {
        l = client.readBytes(line, sizeof(line));
        line[l] = 0;

        // parse the parameters sent by the html form
        const char* delims = "=&";
        strtok(line, delims);
        const char* ssid = strtok(NULL, delims);
        strtok(NULL, delims);
        const char* pass = strtok(NULL, delims);

        // send a response before attemting to connect to the WiFi network
        // because it will reset the SoftAP and disconnect the client station
        client.println(F("HTTP/1.1 200 OK"));
        client.println(F("Connection: close"));
        client.println(F("Refresh: 10")); // send a request after 10 seconds
        client.println();
        client.println(F("
Configuration AP

connecting..."));
        client.stop();

        Serial.println();
        Serial.print("Attempting to connect to WPA SSID: ");
        Serial.println(ssid);
        WiFi.persistent(true);
        WiFi.setAutoConnect(true);
        WiFi.begin(ssid, pass);
        WiFi.waitForConnectResult();

        // configuration continues with the next request

      } else {

        client.println(F("HTTP/1.1 200 OK"));
        client.println(F("Connection: close"));
        client.println();
        client.println(F("
Configuration AP

"));

        int status = WiFi.status();
        if (status == WL_CONNECTED) {
          client.println(F("Connection successful. Ending AP."));
        } else {
          client.println(F("<form action='/' method='POST'>WiFi connection failed. Enter valid parameters, please.

"));
          client.println(F("SSID:
<input type='text' name='i'>
"));
          client.println(F("Password:
<input type='password' name='p'>

"));
          client.println(F("<input type='submit' value='Submit'></form>"));
        }
        client.println(F(""));
        client.stop();

        if (status == WL_CONNECTED) {
          delay(1000); // to let the SDK finish the communication
          Serial.println("Connection successful. Ending AP.");
          configWebServer.stop();
          WiFi.mode(WIFI_STA);
          return;
        }
      }
    }
  }
}

Using second request is such a nice, simple answer.  Works flawlessly!

source: Stack Exchange

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

sort: votes


text:
How to writte simple string compare?
I new to Arduino and I'm attempting to writte a simple string compare code like this:
void loop()
{
  distance(cm);
  delay(200);
}

void distance(char[3] unit)
{
  if (unit[] == "cm")
    Serial.println("cm");
}

Could somebody please advise me how to writte it correctly?
Thanks in advance!

Use strcmp().

Thank you for your answer.
I've written this statement: if (strcmp(unit, "cm") = 0) ,but I think I have a problem with void distance(char[3] unit) and "reading" the string.
IDE output: sketch_jul08a:15: error: 'unit' was not declared in this scope
expected ',' or '...' before 'unit'

It's char unit[3], or, better char * unit. And you call like distance("cm"), with the quotes.

I've written this statement: if (strcmp(unit, "cm") = 0) -- that should be == 0 to do a comparison.

if (strcmp (unit,"cm") == 0) {

    // matches cm

}

For syntax like this the intellisense in products such as Atmel Studio or Visual Studio can really help. Whilst you still need to understand what you might be looking for the intellisense makes all the available Arduino functions visible from the code. If you install the Arduino plugin then there will be an Arduino reference explorer in both ide's which explains everything.

Shameless plug!

@PhillyNJ Hi, not true. It is entirely correct, what users often doesn't realize will help most.  + I didn't post any links!

Shameless or not, Atmel Studio 7 Beta runs all the Arduino libraries with no plugin.

Sure you can use the import tool to convert some Arduino projects to cpp projects. they are then no longer Arduino compatible, no ability to easily take core upgrades from Arduino, no usb upload, only a debugger if you hack your board, only debug with optimization disabled, difficult to add new libraries and the list goes on. Great for some pro users but not for others. Have you tried it? maybe not?

Yes - Both Visual Macro and Beta 7.

Great then you will see that for pro users Atmel is fine but not for others. It's too rigid, different and complicated for most Arduino users but the publicity will surly bring new users :)

You seem to think shameless is bad.

Oops sorry. I am usually jumped on by linux people. Becoming paranoid in my old age.

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


text:
Using Arduino To Control Boot Sequence of PC
I want to know if it is possible to use an arduino to tell a pc which os to boot to. I know It is possible to turn on the pc by wiring it to the motherboard pins with the power switch, and I know the arduino I have (http://www.amazon.com/SainSmart-ATmega328P-Development-Compatible-Arduino/dp/B00E5WJSHK/ref=sr_1_1?ie=UTF8&qid=1436368217&sr=8-1&keywords=sainsmart+uno+r3) can act as a mouse or keyboard. Can that be done before the pc has booted however?

"can act as a mouse or keyboard" Do you know how to make it do so, or have you heard that others can do it?

There's a hackaday article on using the board's AT16u2 to emulate an HID device.

Injecting key events should be do-able, the question may be more if what needs to be injected and when is context- dependent.  Why not use a customizeable boot manager like grub, and modify it to talk to you over a serial port?

Arduino Micro, or Arduino Leonardo would be a lot easier to emulate a keyboard. Since you want the arduino to power up the PC you'd connect it to the 5v-standy (usb will power down in some PCs, so you can't usb to power it. I don't see how this would not be possible. You could use the old power button to control the arduino. Something like, one press=>Boot Windows, two presses =>Boot Linux etc.

Ignacio- I have never used an arduino for more than a motor and sensor controller, but the documentation says that It can emulate a HID device.

I see the issue with attempting to solve my issue with a keyboard now. There is no way to tell the arduino that the computer is waiting for an os selection. Grub control via serial port sounds like the only way to go.

So it might depend on how you implement it. With an Arduino Uno, your options for creating an HID device are limited to either reprogramming the 16u2 (which will require an ISP) or using a software USB implementation (like V-USB). If you go with the first method I'm pretty sure that will work as it will be a native USB connection. As for the second method, I'm not sure how well V-USB responds to having the USB host turning on while it is running. The best thing to do is just try it and see how well it works.
The bigger challenge you will run into is being able to select your PC operating system. Because this will be a one way connection, there is no way of knowing what state the computer is in and whether or not it is time to press a key yet or not. This means you will have to be timing things fairly accurately, which can be tricky unless you are careful. The internal oscillator is not very accurate (but probably still accurate enough) and interrupts used for communicating with USB can block the main loop. That is not to mention any variations the computer might have in its boot process.
A good alternative method would be to set up a bootloader on your PC that can be controlled via a serial port. GRUB2 is a popular one that does support a serial console. All you would need to do is add a level adjuster to adapt the Arduino UART to RS232, then set up the code to wait for the GRUB prompt and then send the command necessary to select which OS you wish to use.

Thanks for the information. This is very helpful and a great place to start. Grub sounds like the way to go. I have used grub in the past, but no more than using the arrow keys to select the os. The arduino's would send the power signal to the computers to boot, and then feed the bootloader the information telling it what to boot to? The serial console is via usb? How could I do this on two separate machines at the same time? Is it the same type of thing as using the serial console to monitor the arduino through the arduino++ software?

The arduino would listen to the serial port and wait for grub to be ready, usually it does this by printing a prompt (e.g. traditionally this has been "grub>" not super sure about newer versions though). If these computers have actual serial ports (i.e. 9 pin DSUB RS232) I would try and use that and connect to it via the UART port on the Arduino, using an adapter like I mentioned. Using the USB serial port might be possible, but it just depends on whether GRUB supports them.

As far as multiple computers go, you would pretty much have to go the UART route and get an Arduino that has more than one UART. For example the Due and the Mega 2560 have 4. Other Arduino-like boards like the Teensy 3.1 also offer extra UARTs.

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


text:
Servo motors won't work with motor controller
I have a motor controller controlling two motors, which works perfectly fine when I comment out the two servos in the below code. These two servos are not connected to the motor controller but simply being operated using other Arduino Uno pins, as seen in the code.
When the servo attach() functions are included in the code the motor controller only works with one of the motors and the other completely stops working.
I don't understand why the servos are interfering with the motor controller. What's going on here?
#include <Servo.h>
Servo myServo1;
Servo myServo2;

int m1_ALI = 10;
int m1_BLI = 9;
int m2_ALI = 3;
int m2_BLI = 11;

int m1_AHI = 12;
int m1_BHI = 4;
int m2_AHI = 6;
int m2_BHI = 5;

void setup() {

  //myServo1.attach(7);
  //myServo2.attach(8);

  pinMode(m1_AHI, OUTPUT);
  pinMode(m1_ALI, OUTPUT);
  pinMode(m1_BLI, OUTPUT);
  pinMode(m1_BHI, OUTPUT);
  pinMode(m2_AHI, OUTPUT);
  pinMode(m2_ALI, OUTPUT);
  pinMode(m2_BLI, OUTPUT);
  pinMode(m2_BHI, OUTPUT);
}

void loop() {

moveForward(30);

}//end loop

void moveForward(int x){

    digitalWrite(m1_AHI, LOW);
    digitalWrite(m1_BLI, LOW);
    digitalWrite(m1_BHI, HIGH);

    digitalWrite(m2_AHI, LOW);
    digitalWrite(m2_BLI, LOW);
    digitalWrite(m2_BHI, HIGH);

    analogWrite(m2_ALI, x);
    analogWrite(m1_ALI, x);
}//end moveForward

See Servo.cpp:

Note that analogWrite of PWM on pins associated with the timer are disabled when the first servo is attached.
   Timers are seized as needed in groups of 12 servos - 24 servos use two timers, 48 servos will use four.

Also Servo Library reference

On boards other than the Mega, use of the library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins.

You are using pins 9 and 10 for your motors.

analogWrite uses PWM, the servo library uses PWM, you have a conflict of resources here.

The servo's are not connected to PWM pins though.

wow thanks that worked. My goodness I have been trying to solve this for a week.

Strange with how many arduino robot car projects there are out there, how none I came across talked about this.  I just happened to decide to 'upgrade' to controlling the speed, and ran into this (5 years after the original question)

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


text:
Using for loop to set pinMode
I notice problems with my output pins when I use this method of setting their pinMode:
int allOutputPins[] = {3, 4, 9, 10, 5, A3, 11, 12, 7, 8, A1, A2};

for(int a = 0; a < sizeof(allOutputPins); a++){
   pinMode(allOutputPins[a], OUTPUT);
  }//end for

Am I doing something wrong?

Re  “Am I doing something wrong?”, yes :)
The sizeof(allOutputPins) expression returns the size of allOutputPins[] in terms of bytes, so is 24 because the array contains 12 two-byte integers.  The loop's last 12 pinMode() calls will be garbage.
Among other ways of fixing the problem, you could change the expression to sizeof(allOutputPins)/sizeof(int) [which has the same value, 12, as (sizeof allOutputPins)/sizeof(int); eg see the syntax entries for the sizeof operator at cppreference.com] or you could change the base type of the array to byte or uint8_t.

I would recommend using sizeof allOutputPins / sizeof allOutputPins[0] instead. This idiom is more robust because it works independently of the type of the array. I would use it even if I change allOutputPins base type to uint8_t.

What you needed and were expecting was the count of the items in the array. I need this so regularly, I keep a countof macro, #define countof(a) (sizeof(a)/sizeof(a[0])) in my local.h file (personal file of common idioms).

Thanks @JRobert that's a good idea. Is that all I need to define to use it?

You also need to use the countof define like this: for(int a = 0; a < countof(allOutputPins); a++){

You would need to #include <local.h> in your sketch (the Arduino IDE won't know to do it for you); thereafter you can use it anywhere in your sketch, such as how @NickGammon just described.


text:
Check the value of character variable
I'm writing some code for Arduino and I'm not sure if I'm checking the value of this character variable correctly. Can you please tell me if this is correct:
const char* front = "front";
const char* back = "back";

eyeballs(front);
eyeballs(back);

void eyeballs(const char* frontOrBack){

if (frontOrBack == "front") {
    digitalWrite(frontEyes, LOW);}//end if
  else if (frontOrBack == "back") {
    digitalWrite(backEyes, LOW);}//end else*/
}

Since you are using C strings (array of characters) instead of the C++ String class, you cannot use the == operator.
Instead, you can use the C style strcmp function, which is also part of the C++ library:
    #include <string.h>
       .
       .
       .

    if (!strcmp(frontOrBack,"front")) {
        digitalWrite(frontEyes, LOW);}//end if
    else if (!strcmp(frontOrBack,"back")) {
        digitalWrite(backEyes, LOW);}//end else*/
    }

Thank you. Is that the only issue with my code? For some reason the ARduino IDE isn't catching the error.

@Armandas thx, updated.

@MichaelRader Syntactically, there is nothing wrong with your code, so the compiler doesn't display an error.  What you are doing is testing whether the address of the character array frontOrBack passed into the function eyeballs  is the same as the address of the constant character arrays "front" or "back", which will always be false.

Can you tell me why you have the ! before strcmp?

@MichaelRader If you click on the link that I gave for the strcmp function, you will see (under Return Value) that it can return one of three values: >0 (e.g. 1) if the the first character of string1 is greater than the first character of string2; <0 (e.g. -1) if the the first character of string1 is less than the first character of string2; and 0 if the two strings are equal (which is what you are testing for).  Putting a ! in front of a variable or function in C or C++ is the same as testing for 0.  So I could have written this as "if (strcmp(frontOrBack,"front")==0)"


text:
Why is the constrain function used after the map function?
I am reading some sample code and they use this method of mapping data from IR sensors:
  sensor1 = analogRead(0);
  adj_1 = map(sensor1, s1_min, s1_max, 0, 255);
  adj_1 = constrain(adj_1, 0, 255);

What is the point of using constrain here if adj_1 is already getting a value 0-255 from the map function?

Are s1_min and s1_max the guaranteed or the expected limits of the raw reading? map() does not constrain its output.

@EdgarBonet what do you mean it doesn't constrain its output? Won't it return a value 0-255?

Not necessarily, it’s just a linear mapping.

Sorry, what does that mean?

A linear function.

An affine map :-) (http://en.wikipedia.org/wiki/Affine_transformation). If you draw a straight line through the points (fromLow, toLow) and (fromHigh, toHigh) then the input ('x') value is mapped to the corresponding 'y' value on the line.

From the official Arduino site:

[The map function] does not constrain values to within the range, because out-of-range values are sometimes intended and useful. The constrain() function may be used either before or after this function, if limits to the ranges are desired.

EDIT: Example.
You can try this by yourself with this code:
int val = 20;
val = map(val, 0, 10, 0, 100);

Although you set the upper bound of the value's range to 10, you passed an higher value than that and the function will linearly map it accordingly, resulting in an output of 200.

One caveat would be when mapping an input that ranges from 0 to 1023, since the Arduino is incapable of reading outside of this range there would be no need to constrain. You can check this by running through each iteration from 0 to 1023 and outputting the corresponding mapped value:
for (int i = 0; i < 1024; i++){
    Serial.print(i);
    Serial.print(",");
    Serial.println(map(i, 0, 1023, 0, 255));

}

Certainly, if your sensor reading offers a range smaller than 0 to 1023, then the constrain() function is definitely required, as per LoganBlade's example. Otherwise, it is not needed, but may still fall into the realm of best practice.
The only hiccup to this logic would be if you are mapping to decimal values (which doesn't make much sense since the function will return a long type anyway), in which case the Arduino's internal typecasting will round-down your lowest value mapping. Example:
map(0, 0, 1023, 8.9, 61.9));
>> 0 becomes 8

map(1023, 0, 1023, 8.9, 61.9));
>> 1023 becomes 61

Again, for the sake of best practice and the potential time wasted trying to find a mapping bug, using constrain() is better than skipping it.

Some sensors output high numbers when they are out of their normal range of operation or if something else is off. The STM VLS30X can suddenly output 8190 after having measured 487 (mm) for example. Therefore, constrain should be a must. See also a solution to the mapping error too many users make https://www.jetmore.org/john/blog/2011/09/arduinos-map-function-and-numeric-distribution/


text:
What is the best transmitter/receiver to use with an Arduino RC?
I want to customize an RC car that I have because the controller is gone. I'm going to use an Arduino with a custom motor controller but I have no idea what to use for the transmitter/receiver. I've seen some IR sensors being used but I want something that uses a frequency channel. Has anyone had experience doing this? What is the easiest way to go about accomplishing a remote controlled Arduino car?

That depends largely what is controlling it
Some options include:

wifi, if you have an expansion board, from a PC or phone (spec says: 66ft/20m)
bluetooth works great, directly from your phone (spec says: 32ft/10m - 320ft/100m)
433mhz ASK transmitter/receiver from another Arduino or other hand-designed circuit (spec says: 100m/320ft)
Infrared receiver - from a TV remote! (range unknown, depends on remote & conditions; would not trust it 10m outside without testing).
Cellphone network - longest range (nationwide!). If you get a cheap android to do some of the work, you can use the phone's compass & gps & extra processing power, as well as the camera(s)!
Remote control. I know you said you lost yours, but in case someone else is looking here, you can hook up an rc receiver to an Arduino fairly easily. https://www.sparkfun.com/tutorials/348 for more info.

Many of these ranges specified will depend on the antenna. If your car can tell it's lost signal, then it can stop; otherwise you have to outrun it, or wait for it to hit a wall.
Edited to include cellphone network, and added ranges to options

Here is a link to a pair of Arduino compatible wireless transceivers. One of the listed applications in the description is "remote control systems such as RC vehicles," so I think this product would suit your project well.
According to the reviews / answers to questions on Amazon, the transceivers have an reliable range of just around 120 feet, so this component would be entirely appropriate in a remote-controlled build.

You need two arduinos for this, and 120 feet isn't very far, but thanks. +1


text:
Fried two Arduino Nano's but works when powered
It took me about 4 hours to desolder an Arduino Nano I fried and solder on the new one. I'm not exactly sure how but I shorted it somehow while trying to install the nano onto my robot. I could smell a fait burning and the nano no longer powered on or allowed me to upload code via USB.
When I put the second nano on, before properly insulating exposed wire, I fried it again!! This time I actually saw a little smoke and quickly unplugged it. The nano no longer responds to the USB, but...
I have this nano also being powered by an Arduino Uno. When I turned on the battery connected to the Uno, the Nano turned on and everything was working fine!! I was pretty relieved after a short spout of depression! I plugged in the USB to the Nano and I was able to upload code... only with the nano being powered from the Uno. If I turn off the battery to the Uno the Nano doesn't work with USB.
I have no idea what happened exactly and I'm not sure what fried on my Nano but I sure am glad I have this work around instead of replacing the Nano again!
Does anyone know why it's doing this? What did I see smoking? Is it repairable?

Judging by your list of observations:

Cannot power through USB
Can power from external source
Can program through USB

it is most likely that the power feed from the USB to the +5V rail has been interrupted.  There is only one component in that link - the diode D1 (an MBR0520).  That is rated at an absolute maximum constant forward current of 0.5A and most USB ports these days are capable of providing far more than that.  A short circuit on the +5V to ground would draw considerably more current than that diode can handle and the Magic Smoke™ would escape.
The diode is on the underside of the Micro and close examination may show a small crack in the surface of it.  That is if it's still there.  I have used a similar PIC32 based board with 0.5A rated diodes on it, and a short of the power rail when powered from USB caused the diode to completely vaporise (at least I could find no trace of it afterwards).

Can program through USB only while powered from external source*

@MichaelRader The ability to program the board and the ability to provide power to the board (either while programming or at other times) are two separate things.  The issue here is not with programming, since programming works - the issue here is with providing power, which is a prerequisite to programming, not part of the act of programming.

Yes I understand, however it is part of the act of programming if it must have power to program. But anyway, thanks!


text:
How does the reset button work on the Arduino?
I'm confused about how and when to use the reset button on the Arduino. Do I simply press the button while it is on? Is it simply restarting the board or clearing the uploaded code as well? Currently when I press the button while my Uno is powered it does absolutely nothing.
I have been using this board for many weeks with no problem and just now I have been getting this error:
avrdude: stk500_getsync()

And I cannot upload code. I tried using the reset button but I see nothing happening on the board, no blink, no flicker, nothing indicating something was reset.

The reset button does pretty much the same as unplugging the board and plugging it back in.  It restarts your program from the beginning.
The same thing happens when you program the board - the USB interface presses the reset button for you.  That then enters the bootloader for a second or two so it can try and program it.
When you reset the board the LED on pin 13 should flash a couple of times while it's in the bootloader before it runs whatever program you have programmed in.  If that LED doesn't flash when you press the reset button then there is a serious fault with your board which will take further diagnostic.

If you have anything else plugged into the Arduino then unplug it.
Try powering the Arduino from different power supplies.
If you have another Arduino or an AVR programmer try re-flashing the bootloader.

Thank you. You've confirmed my suspicions. I've been trying to re-flash the bootloader with another Arduino but I keep getting errors for that too. Maybe it's because I didn't unplug everything or maybe because I have bad connections to the ATTINY pins. What sucks is that this Aruduino is part of a robot and I have all pins being used and hot glued into place. I was hoping for a better answer than unplugging everything. :|


text:
Bizarre compilation problem -- only compiles with the addition of a single Serial.println() line?
I have a SwitchDoc Labs DS3231 Real Time Clock Module that I am using with an Arduino Mega.  It's connected to 3.3V and the SDA(20)/SDL(21) pins.  I'm also using SwitchDoc's RTC_SDL_DS3231_ARDUINO library (see link to the example sketch below).
I can compile and run the example provided with the library just fine.  However, I'm running into a very bizarre compilation problem when I remove the Clock set function calls in the setup.
Rather than take up the space and copy the code that works I'll just link to it on github: 100% working for me example.
The problem I am running into happens when I remove (or comment out) the section in the setup function that sets the time:
void setup() {
  // Start the I2C interface
  Wire.begin();
  // Removed code
  // Start the serial interface
  Serial.begin(9600);
}

Then I get the following error when I try to compile/verify the sketch:
/Applications/Arduino/Arduino.app/Contents/Resources/Java/hardware/tools/avr/bin/../
lib/gcc/avr/4.3.2/../../../../avr/lib/avr6/crtm2560.o: In function `__vector_default':
(.vectors+0x90): relocation truncated to fit: R_AVR_13_PCREL against symbol `__vector_36'
defined in .text.__vector_36 section in core.a(HardwareSerial.cpp.o)

If I add back just one single clock set call it will compile:
void setup() {
  // Start the I2C interface
  Wire.begin();
  Clock.setYear(15);  //Set the year (Last two digits of the year)
  // Start the serial interface
  Serial.begin(9600);
}

However, the truly strange thing is that if I simply add a Serial.println() line to the setup function, the sketch compiles too!
void setup() {
  // Start the I2C interface
  Wire.begin();
  // Start the serial interface
  Serial.begin(9600);
  // Adding the following line allows the sketch to compile
  Serial.println("Why does this work now???");
}

Thanks for any help.

Ponderings: (1) Initialising or altering / clearing/setting a variable that is common to all routines?  (2) This sounds nasty and worth knowing more about -> "relocation truncated to fit"

Update: This seems to be a linker bug. Quick fix: upgrade your
Arduino installation. See the end of this answer for details. What
follows is the first version of this answer, with a detailed explanation
of the error message.

You have a problem linking the interrupt vector table with your program.
I quite understand what the error message means, but I do not understand
how in the world you can possibly have this error. This should not
happen. I will try to explain the error anyway.
The Arduino Mega is based on an AVR chip. The AVR instruction set has
“jump” and “call” instruction that come in two flavors:

“absolute” jumps and calls (opcodes: jmp and call) can address the
whole flash memory, which means you can branch from any part of the
program to any other part, without restrictions.
“relative” (a.k.a. “PC-relative”) jumps and calls (opcodes: rjmp and
rcall) have limited range: they can only bring you to nearby places,
no more than 4 K from your starting point.

The relative flavors take less space and execute faster, they are thus
better if the destination is close enough. On the smaller AVR chips
(up to 8 K of flash), they can access the whole flash, then these
chips lack the absolute flavors.
How the vector table is normally linked
Every program you build for an AVR starts with an “interrupt vector
table”. This is a series of jump instructions that are automatically
executed whenever an interrupt triggers: if the n-th supported
interrupt triggers, then the hardware automatically loads and executes
the n-th jump instruction, which will jump the execution of the
program to the corresponding ISR (interrupt service routine). The
table is chip-specific: on the smaller AVRs (up to 8 K), it's a
table of rjmp, whereas on the bigger ones it's a table of jmp. This
table is part of the CRT (C run time) provided by the avr-libc library
in a file named crtXXX.o, where XXX is a code identifying the chip. The
Arduino Mega being based on the ATmega2560 chip, it's CRT is crtm2560.o.
I disassembled my own copy of crtm2560.o and found this vector table:
00000000 <__vectors>:
   0:   0c 94 00 00     jmp 0
   4:   0c 94 00 00     jmp 0
   8:   0c 94 00 00     jmp 0
   ...
  e0:   0c 94 00 00     jmp 0

You can see these are all jmp instructions (absolute flavor), as
expected for any AVR with more than 8 K of flash. The address of
the jump, however, is always 0, which is obviously wrong. This is
because the proper addresses cannot be known until the program is fully
built. When you build your program, the linker will put all the pieces
together. It will then know where the ISRs are, and it will patch the
vector table to make it correct. This kind of patching is known as
“relocation”, and the linker performs this based on some “relocation
records” included in the CRT. Here are the relevant records from my copy
of crtm2560.o:
RELOCATION RECORDS FOR [.vectors]:
OFFSET   TYPE              VALUE
00000000 R_AVR_CALL        __init
00000004 R_AVR_CALL        __vector_1
00000008 R_AVR_CALL        __vector_2
...
00000090 R_AVR_CALL        __vector_36  [*]
...
000000e0 R_AVR_CALL        __vector_56

The record I marked with [*] means: “at offset 0x90 into the vector
table there is an absolute jump or call instruction, and the instruction
should be modified to point to __vector_36”. This tells the linker
how to fix the table when building the program.
If I instead disassemble a CRT for a smaller chip, I get a smaller table
made of rjmp (instead of jmp) instructions, and the relocation
records look like this:
RELOCATION RECORDS FOR [.vectors]:
OFFSET   TYPE              VALUE
00000000 R_AVR_13_PCREL    __init
00000002 R_AVR_13_PCREL    __vector_1
00000004 R_AVR_13_PCREL    __vector_2
...
00000032 R_AVR_13_PCREL    __vector_25

These records mean “at offset XXX into the vector table there is a
PC-relative jump or call instruction, and the instruction should be
modified to point to __vector_XXX”.
Your error message
Your error message provides the following information:

“crtm2560.o”: this is your CRT, where the vector table and the
relocation records live.
“.vectors+0x90”: this means the problem is at offset 0x90 into the
vector table.
“R_AVR_13_PCREL against symbol `__vector_36'”: this means there
is a relocation record of type R_AVR_13_PCREL (PC-relative jump or
call) referencing __vector_36. Here seems to be the problem.
“defined in [...] core.a(HardwareSerial.cpp.o)”: this __vector_36
is part of the serial port code from the Arduino core library.
“relocation truncated to fit”: __vector_36 is too far to be reached
by a PC-relative jump, thus the linker could not relocate properly.

The problem seems to be that the relocation record is of type
R_AVR_13_PCREL, which is what you expect on smaller chips but not on
your ATmega2560. You normally expect R_AVR_CALL.
Now, about the strange behavior: the exact point where the ISR lands
when the program is built is difficult to predict. Add or remove a few
lines in your code and the linker may bring the pieces together in a
different order. Then, the infamous __vector_36 may end up being in
range or out of range of a relative jump. Given the nature of the error,
the behavior you find “strange” is actually quite normal.
Further debugging
The root of the problem seems to be an incorrect relocation record in
your CRT. You can try to disassemble the CRT to see what is wrong:
search your computer for a file named crtm2560.o, probably in
/Applications/Arduino/Arduino.app/Contents/Resources/Java/hardware/tools/avr/avr/lib/avr6
or a similar place. The tool needed for disassembling is called
“avr-objdump” and should be hidden somewhere in your Arduino
installation folder. Once you find the files, start a terminal and type
/path/to/avr-objdump -d /path/to/crtm2560.o

with “/path/to” replaced by the actual paths. You should see something
very much like the first listing of my answer, with lots of jmp
instructions. If you have rjmp instructions instead, then something is
already wrong at this level.
To see the relocation records, type:
/path/to/avr-objdump -r /path/to/crtm2560.o

The output should look like my second listing, with lots of R_AVR_CALL
records. If you have R_AVR_13_PCREL instead, the records are wrong.
If this is the problem, then the obvious fix would be to replace the
broken CRT with a sane one. You may try to reinstall the whole Arduino
package. If you still have a corrupted CRT, you should report the error
to the Arduino folks. Then you may try to fetch a fresh copy of the
avr-libc and replace the relevant
parts of your Arduino installation. Replacing just the CRT may or may
not work: I don't know whether the last version of the CRT has
incompatibilities with older versions of the rest of the libc.
Update: this is a linker bug
I did some research, and I now believe you have hit a linker bug. There
is a gcc option called -mrelax that allows some link-time
optimizations. One if them is to have the linker replace some absolute
jumps and calls by the smaller and faster relative ones. Obviously, this
is only possible if the target address is within reach of the relative
jumps or calls. There was a bug in old versions of the GNU linker (up to
2.22) where, under some obscure circumstances, it would erroneously
believe the target was reachable, only to find out later that it was
not. This bug mainly affected the interrupt vector table, producing the
kind of error message you are seeing now.
Here is a partial timeline of this bug and its fix:

November 2011: this is filed as
bug 13410
on the bug tracker for the GNU binutils package.
January 2012: Vidya Praveen, from Atmel, publishes a fix.
February 2012: the fix is committed to the development version of
binutils.
October 2012: GNU binutils 2.23 is released, including the fix.
The same month, the bug is reported again as
issue 1071
on the Arduino issue tracker.
June 2013: Paul Stoffregen links this new issue to the old bug.
June 2014: Arduino gets an updated
toolchain
including binutils 2.23.2, which fixes the bug in the development
version of Arduino.
July 2014: Arduino 1.5.7 beta is
released including the
updated toolchain.
September 2014: Arduino 1.0.6 is released with the old toolchain.

A workaround for the bug has been
published by Mark Anderson on stackoverflow. The real fix, however,
would be to upgrade to the latest Arduino package (1.6.1 as of this
writing).


text:
Reading Arduino from Java is way too slow
I am trying to write a simple Java program to display the analog input fed to an Arduino board upon a stimulus from a user on some physical sensors.
If I use the Arduino program itself and look at the serial monitor, I see the analog read based on user input updated instantly. However, when reading the input from my Java program, there is a significant delay (8-12 seconds) between the physical stimulus and the display of the value.
The code uploaded to Arduino is very simple, just cycle through a bunch of analog ports and print the data:
void setup() {
  Serial.begin(9600);
  pinMode(30, OUTPUT);
}

void loop()
  digitalWrite(30, HIGH);

  for (int i = 0; i < 10; i++) {
    int sensorValue = analogRead(i);
    Serial.print(String(i) + ":");
    Serial.println(sensorValue);
  }
}

The Java code I am using is almost entirely copied from the example provided here, with the exception that I updated the port name to work for my system (Mac OS X 10.10.3).
Here is the Java code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.util.Enumeration;

public class SerialTest implements SerialPortEventListener {

    SerialPort serialPort;

    /** The port we're normally going to use. */
    private static final String PORT_NAMES[] = {
            "/dev/cu.usbmodem1411",
            "/dev/cu.usbmodem1451",
    };

    /**
    * A BufferedReader which will be fed by a InputStreamReader
    * converting the bytes into characters
    * making the displayed results codepage independent
    */
    private BufferedReader input;

    /** The output stream to the port */
    private OutputStream output;

    /** Milliseconds to block while waiting for port open */
    private static final int TIME_OUT = 2000;

    /** Default bits per second for COM port. */
    private static final int DATA_RATE = 9600;

    public void initialize() {
        CommPortIdentifier portId = null;
        Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

        //First, Find an instance of serial port as set in PORT_NAMES.
        while (portEnum.hasMoreElements()) {
            CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
            for (String portName : PORT_NAMES) {
                if (currPortId.getName().equals(portName)) {
                    portId = currPortId;
                    break;
                }
            }
        }
        if (portId == null) {
            System.out.println("Could not find COM port.");
            return;
        }

        try {
            // open serial port, and use class name for the appName.
            serialPort = (SerialPort) portId.open(this.getClass().getName(),
                    TIME_OUT);

            // set port parameters
            serialPort.setSerialPortParams(DATA_RATE,
                    SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);

            // open the streams
            input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
            output = serialPort.getOutputStream();

            // add event listeners
            serialPort.addEventListener(this);
            serialPort.notifyOnDataAvailable(true);
        } catch (Exception e) {
            System.err.println(e.toString());
        }
    }

    /**
     * This should be called when you stop using the port.
     * This will prevent port locking on platforms like Linux.
     */
    public synchronized void close() {
        if (serialPort != null) {
            serialPort.removeEventListener();
            serialPort.close();
        }
    }

    /**
     * Handle an event on the serial port. Read the data and print it.
     */
    public synchronized void serialEvent(SerialPortEvent oEvent) {
        if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            try {
                String inputLine=input.readLine();
                System.out.println(inputLine);
            } catch (Exception e) {
                System.err.println(e.toString());
            }
        }
        // Ignore all the other eventTypes, but you should consider the other ones.
    }

    public static void main(String[] args) throws Exception {
        SerialTest main = new SerialTest();
        main.initialize();
        Thread t=new Thread() {
            public void run() {
                //the following line will keep this app alive for 1000 seconds,
                //waiting for events to occur and responding to them (printing incoming messages to console).
                try {Thread.sleep(1000000);} catch (InterruptedException ie) {}
            }
        };
        t.start();
        System.out.println("Started");
    }
}

All the program does is print out the values of the Arduino serial monitor, yet it takes way longer (8-12 seconds) through Java than it does from the Arduino program itself.
1) Why is this happening?
2) How do I fix it?

Are you sending full lines each time, including a full line terminator?

I am just a beginner, I think you mean a string terminator to denote a new line, but I am not sure what you are referring to. You can see all of the code. And it does work both in Arduino IDE and in Java just that Java takes much much longer, so I would think that is not the issue? Please elaborate

After the 8-12 seconds, does it keep displaying at a fast enough speed?

This seems like a host OS / serial API / Java problem not an Arduino one.  Try putting the readLine method in a blocking loop in your main thread to simplify things.   Historically, there have been some very pathalogical interactions between application layers, operating systems, USB-serial firmwares, and the corresponding drivers - I've seen something that worked just fine with a C program effectively read at around 100 baud with a .NET client running on the same machine.

Try adding a delay (eg. delay(200);) into your main loop. You may be sending data too fast for the Java app to cope with.

Yes that was the issue!! I put some delays in there and the performance is way better. It is still not perfect, but I bet if I keep playing around with the delay I will get it. So far much improved though good thinking!

I'm glad that helped. I'm going to flag your "answer" as "not an answer" (if I don't someone else will) because the answers are supposed to be an answer to the question. Unfortunately I didn't post what turned out to be the answer, as an answer myself. Oops. Thanks for letting us know that it worked.

I turned my comment into an answer, mainly to help the next person who looks at this question. If you can mark it as "accepted" that will also help them. Thanks!

Timing tests show that the Java code lags something like 25 or more seconds behind the input from the Arduino. This can be fixed by changing in the Java code these lines:
       try {
            String inputLine=input.readLine();
            System.out.println(inputLine);
        } catch (Exception e) {

to:
       try {
            while (input.ready ())
              {
              String inputLine=input.readLine();
              System.out.println(inputLine);
              }
        } catch (Exception e) {

This extra loop "drains" the input buffer of data in the one serialEvent call, rather than relying upon a serialEvent call per line of data.
I found when testing that the output is now highly responsive, even without a delay on the Arduino side.

My other answer of adding a delay call slowed output down enough for the Java app to catch up, but I must admit it isn't the best solution.

One more thing you could do is create a while(true) loop, after initialize() and call input.readLine(), so that you don't wait for the event to appear.
For some reason the event is delayed, but doing the while loop hasn't created any issues or exceptions for me so far.
My code is like this:
public void initialize() {
   //initializing stuff
   while(true){
       try {
           String inputLine = input.readLine();
           //do stuff here
       } catch (Exception e) {
           System.err.println(e.toString());
       }
   }
}

Try adding a delay, eg.
delay(200);

into your main loop. You may be sending data too fast for the Java app to cope with.

No.  An arduino transmitting at a mere 9600 baud should not be able to outpace the program, unless there is something pathologically wrong with the program or the installation it is running on.  If this has any effect at all, it was probably only in changing some highly unfortunate "just missed it" to some slightly less problematic one, but that actual problem remains and may rear its head again in a different configuration.  This is not a sound solution or based on any sensible reasoning - if it helps at all, it is only by lucky accident.

Thank you for your comments, Chris. Rather than trying to salvage this answer (and have your comment make no sense) I have posted another answer.


text:
Arduino web server: redirect to mobile site on SD card?
Is there any way to have an Arduino web server redirect the client to a file on the SD card only if the client is using a mobile browser?
(My arduino server is already successfully serving pages on http://192.168.0.180, and successfully processes GET requests).
I was thinking of having this javascript code on the main page that's served by the arduino:
<script type="text/javascript">
  <!--
  if (screen.width <= 800) {
    window.location = "http://192.168.0.180?mobile";
  }
  //-->
</script>

My first thought was that maybe it's possible for the server to process that GET request and then serve a page from the SD card, instead of the regular page it serves.
Do you think this is possible, and how would you recommend to do it?

Yes, it is perfectly possible. you just have to look at the right bits.
Fundamentally there is no difference between an Arduino and any other website, it's just somewhat simpler in how it operates.
All browsers follow the same rules - if they didn't they wouldn't work on the web.  Two of the rules you are interested in are:

Browsers identify themselves along with their OS.
Browsers respond to the "result" code the website provides in a specific way.

Besides the GET request a browser also sends a list of headers.  These contain lots of extra information about the request, including the domain name of the website that is being accessed (so the web server knows which site you want - it's not one webserver per site, that would be impractical.  For instance, the request to show this page from Firefox on Linux has these headers:
Host: arduino.stackexchange.com
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0 Iceweasel/31.6.0
Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: (I won't bore you with this lot)
Connection: keep-alive

The header of note is the User-Agent: one.  That tells the web server that I am using firefox from a 64-bit Intel Linux computer.  If I were to do it from my Android phone it would tell you it's from Chrome on Android.
By looking for that header and parsing it for certain keywords you can find if you're serving to a mobile device or not.
Now the second bullet above - browsers respond to the response code in different ways.  Normally you send the response code 200 which means "I accepted your request and here is the page you asked for".  Another response code that is useful is code 301 which means "The page you asked for isn't at this address any more - here is the new address you should go to instead".  That will then cause the browser to go to the newly provided address instead.
So instead of responding with
HTTP/1.0 200 OK
Content-type: text/html

<web page content here>

You could instead respond with:
HTTP/1.0 301 Moved Permanently
Location: http://myarduino.local/mobile

And the browser will redirect to the new address you give in the Location: response header.
The full list of response codes is here: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
If you want to avoid the overhead of a browser redirect you can just serve different data to the browser depending on what the User-Agent header specifies.  After all, it's entirely down to you what is sent as the content of the page.  Whether you get that from purely programmatical means, or by reading a file off an SD card, is entirely up to you.

Does it make sense that serving a file from the SD card will be noticeably slower than just using "client.println" statements to serve the page? This is the code I'm using to read the file from the card (using the SDfat library, which is supposed to be faster than the main SD library): char c;     while ((c = mobileFile.read()) >= 0) {     client.write(c); }
edit: sorry I couldn't figure out how to properly format the code in the comments section.

It depends how big the file is. If it's a large file, like an image or lots of static text, then a file on the SD makes sense.  If it's just a few bytes then there's no point in using the SD.

Thanks! I ended up moving both files from the SD card onto the main program, because it ended up to be noticeably faster. It's big and clunky, but at least it does what I need it to do. :)


text:
Should long wires be kept separated from each other, to reduce interference?
Let's say someone has four CAT5 cables that are running along the ceiling for the length of a room (30 feet), of which most of the twisted pairs are connected to Arduino input/output pins on one end. Would it be okay to keep these wires bundled together when running along the ceiling? Or is it safer to keep them separated by a few inches? Is interference usually a problem only in very specific situations, or should it be considered for all long wire runs?
How about if there is a telephone cable (hooked up to a landline telephone) running along the same length? Is there any chance of interference if this is too close to the Arduino cables?
How about if there are 120v mains lines running the same length? Should these be kept at a distance from the Arduino cables?
On the other end of the cables that are hooked up to the Arduino, some of the following are connected: temperature sensors, light sensors, servo motors, LCDs, relays, and push-buttons.

Wouldn't it be better to have another Arduino at the sensors, and have this Arduino communicate with the other using e.g. RS485? That way you only need 4 wires (2 for power, 2 for communication). You also fix in case of RS485 (differential pair), or at least have the interference only on a single protocol. Alternatively use shielded CAT5/6 cables.

I like this idea, and try to use it whenever possible (I already have 1 Arduino at the other end to control an LCD, so that it only needs 4 long wires instead of 9). But because I reprogram the main Arduino so frequently, and because it needs to be connected via ethernet, that's why I need it close to the computer for now.

I just wanted to note that I'm not currently having any interference issues. I was just interested in learning what the best practice is. I'm planning on running another long CAT5 cable soon when I expand my system (planning on implementing an automatic indoor-garden control), and I just wanted to make sure I wasn't setting myself up for trouble later on.

A benefit of using CAT-5 is that the pairs are twisted.  You would want to look at how you are using the pairs so that you're not introducing cross talk inadvertently, but the twisted pairs tend to resist RFI which is why its used.  Telephone wire, however, can be a completely different story.  You may find some that is twisted pair, but most if it is simply flat cable.  Worse, much of it is very cheap flat cable with what amounts to a piece of thread with a very thin foil wrapped around it.  This is very high loss and very vulnerable to RFI.

Twisted Pair only "resists" interference if the right signals are used - i.e., differential signals (LVDS, RS485, RS422, etc). Anything else and it's just like any other wire but with the disadvantage that the wires in a pair have closer coupling with each other than with other wires, so can increase crosstalk.

It depends on the frequency/frequencies you care about transmitting on your cables. One simple approach is to put on both ends a filter that lets pass only those frequencies you care about.
You can also consider using some error detection/correction encoding or check if there is some existing library that suits your needs. This last approach will work if you do not get too many interferences and your application can tolerate that data is re-transmitted every now and then, making the communication timing not 100% deterministic.

CAT5 should work well with what you are trying to do, however stay away from power lines unless they are in a grounded conduit.  The phone lines would most likely generate interference when the phone is ringing as there is a lot of voltage transients on the line at that time.
To get the full benefit of the twisted pairs send and receive your signals with differential transceivers, one transceiver per pair.
Personally I will not connect a microprocessor pin to the outside world without some type of buffering isolation etc.  Those pins were not designed to drive long lines, although it may work eventually it will fail, that may be momentary to many years in the making but it will fail.
Lines connected directly to the microprocessor pins will all act as bidirectional antennas. They are not only are sustainable to interference they also generate it.  Remember the wires are small inductors which can generate some huge voltages when the transition time is short.
I typically use Schmidt devices such as a 74C14, 74HC etc. as my input receivers for switches etc.  I normally use an active low input signal, this help to keep noise out of the power supply. The input to the gate is pulled up to the 12VDC with a 10K resistor, this keeps a minimum of about 1 mA through the contact. The other end of the resistor is connected to a 100K resistor that in turn connects to the microprocessor input pin. You can add a cap to de-bounce at the gate if you want. The software is easier as it is looking for an active high which is a logic "1".  This circuit has been replicated hundreds of thousands of times and is very stable and reliable.
What you are doing will work for dorm room, testing etc...


text:
Any way to pass EthernetClient to function outside of loop automatically?
I have an Arduino webserver that displays many buttons over a webpage (73 at the moment) that toggle different switches. I shortened up the button-drawing code with this function:
void displayButton(String toggleName, byte toggle, byte link1, EthernetClient & client, boolean last) {
  if (toggle == 0) client.print("<a href=\"/?");
  else client.print("");
  client.print(toggleName);
  client.print("");
  if (last) client.print("

");
}

And this is a shortened version of my loop function:
void loop() {
  EthernetClient client = server.available();
  if (client) {
    boolean done = false;
    while (client.connected() && !done)
    {
      while (client.available () > 0 && !done)
        done = processIncomingByte (client.read ());
    }  // end of while client connected
      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type: text/html");
      client.println();
      client.print("");
      displayButton("F8", f8Toggle, 57, client, 0);
      displayButton("F9", f9Toggle, 58, client, 0);
      displayButton("F10", f10Toggle, 59, client, 1);
      client.println("");
      delay(5); client.stop();
  } // end of "if client"
} // end of loop

I'm wondering if there's any way to have the displayButton function use the EthernetClient instance without it having to be passed every time. I'm interested in this in order to clean up my code a little (since I would be able to remove 73 instances of the word "client"), and also as a learning experience.

If client is global then it already knows about it.

When I tried to remove the passed client, I was getting "'client' was not declared in this scope" for the displayButton function. Would it affect the webserver at all if I defined "EthernetClient client;" before the Setup and Loop functions? I just tested this out, and it seems to work, but I feel hesitant about it because I've never seen that in any other webserver code.

As long as you remove the EthernetClient from before the client in loop().

As Majenko has noted in the comments, the solution was to declare "EthernetClient client;" as a global variable, outside of the loop. Normally I would've tried something like this on my own, but was hesitant to do so because I had never seen anything like that in other code.

Using global variables is usually considered a sign of poor design (it can leaves you open to some kinds of errors that local variable are less subject to), is why you don't see it very often. The client variable in your program is one of the exceptions, where globalizing it probably reduces, rather than increases, the potential for errors.


text:
Measure LiPo / Li-Ion SOC or the ever standing question of how much juice is remaining in my battery?
So I have a project in which an arduino runs on a two cell LiPo battery and I need a fast, straight forward way to determine remaining battery charge (with an accuracy of 10% so I only have a readout with 10 LEDs on it) without using any major extra components (so using an external battery charge meter IC is cheating :P). How should I go about this?
(using arduino mini, LiPo is two cells: 7,4V 150mAh)

Use a low-leakage op amp to divide the battery voltage by 8 (AV of 1/8). Connect the output to an analog input. Set your reference to the internal 1.1V reference (INTERNAL). Perform analog reads. Full battery will be about 975 ((8.4V/8)/1.1V⋅1024 ~= 977.45455). Empty will be about 700 ((6.0V/8)/1.1V⋅1024 ~= 698.18182). Note that the voltage scaling for Li-ion cells is non-linear; see the datasheet for the cells for the appropriate scaling (and if you want more precise full and empty values).

could you suggest a "low-leakage op amp" model? Please?

http://www.ti.com/product/tlv2450

If you are using a single cell, then the Fuel gauge from Sparkfun would be great. Instead of reading analog values manually it sends the battery level via I2C.

"(so using an external battery charge meter IC is cheating :P)" - no can do, sir, also two cells in series.


text:
Arduino Due - Multiple Serial Lines
I'm trying to interface with a serial device utilizing Serial1 (pins 18,19) on the Arduino Due. The normal serial port (Serial) is working just fine and is acting as a debug port at the moment - It's also able to communicate with the serial device without a problem when using the normal port.
I noticed that within the libraries for the Arduino hardware, the avr directory contains HardwareSerial files for the Mega's multiple serial lines, but the header file under the sam director does not. Simply a declaration of the HardwareSerial class with no elaboration on Serial1,Serial2 or Serial3 like the Mega's header contains.
Has anyone modified the libraries to set up the Arduino Due's multiple serial lines? Thanks in advance!

I tried Serial2, it definitely works on Due without any modification of any libraries


text:
Arduino standard libraries location
I want to read the source code of an arduino library that comes with the IDE.
Specifically the GSM.h
I dont know the location of the standard libraries that come with the IDE.
I only know the location of the user installed libraries.
So where is the source code of GSM.h?

Ok, i found out the location.
In Win 7, it is C:\Program Files (x86)\Arduino\libraries

Those are the standard libraries. If you want to add libraries, it's (I think) preferred to add them to the My Documents\Arduino\libraries\ folder.

Definitely preferred. Otherwise you lose your user-installed libraries when you upgrade to the next version.


text:
Code flow for precission applications
This is a question about programming. Mainly about the loop() function
As an example
Consider code where you get data from an accelerometer, and if the Gs are high enough you do something.
Consider the following pseudocode:
void setup()
{
pinMode(1, INPUT);
bool flag = false;
}

void loop
{
int x= analogRead(1);
if (x>2)   //if the Gs we get from accelerometer
  flag = true;
if (button)  // if user hits the emergency button
  flag = true;

if (flag == true)
{
//GET SERIAL DATA (EG GPS COORDINATES)
//DO SOME HEAVY PROCESSING
}
}

Now loop runs repeatedly
That means all the commands are executed in a continuous/serial style
Since that happens, what will happen if the accelerometer reading where (x>2), which is what we look for, happen in the REAL world, at a time where in the CPU, the cpu is at that time processing or checking following commands in the program flow, like
if (button)  // if user hits the emergency button
      flag = true;

    if (flag == true)
    {
    //GET SERIAL DATA (EG GPS COORDINATES)
    //DO SOME HEAVY PROCESSING
    }
    }

Is there any chance that the cpu will miss real world events, because at that time the real world event occured, the cpu was processing other code. Or rather, not checking for that at that time. For our example, when the event occured, it wasnt checking the analogread() at that time, but was processing following code.
Should i worry about that?

one should take into account the frequency response of the signal versus the sample rate. Per Arduino's web site AnalogRead "It takes about 100 microseconds (0.0001 s) to read an analog input, so the maximum reading rate is about 10,000 times a second." or 5K/S for 2 AnalogRead's.
Where I read the output response of the accelerometer used on the Esplora is 300-400Hz. Note often there are additional filters between the accelerometer and the A2D input.
So in short there should be enough time to sample both X & Y along with a Z, leaving a margin of 10x. To do other things.
Just be careful not to do too much, with routines that block.
As a matter of practice, it is best not to rely on a loop for what ever timing it loops at. But rather setup a timer, either by interrupt or by watching the millis(), to trigger the analog reads at a known interval.
#include "TimerOne.h"
volatile int x,y,z;
void setup()
{
  Timer1.initialize(3000);         // initialize timer1 to overflow at 333hz
  Timer1.attachInterrupt(callback);  // attaches callback() as a timer overflow interrupt
}
void callback()
{
  x = analogRead(A0);
  y = analogRead(A1);
  z = analogRead(A2);
}
void loop()
{
  noInterrupts(); // to ensure they are all in sync.
  // do something with x,y&z
  interrupts();
  // do something else, that is not blocking.
}

Yes, in theory you can always miss events if you use a polling approach like that. Whether or not that's a problem depends on how accurate/frequent your data collection needs to be.
You can often mitigate the issue to an acceptable level if you are able to poll fast enough. That's determined largely by what else your main loop is doing. The more work it has to do elsewhere, the longer it will take between calls to analogRead() (and the more likely it is to miss something). Optimising your code can help.
You may also find that you can compensate sufficiently by interpolating between samples. Linear interpolation is very easy, although more complex options may also be possible, especially if you're processing the data offline afterwards.
If polling isn't working for you, then interrupts are the obvious alternative. Since you're reading an analog signal, you'd probably need some external circuitry which does a voltage comparison. You can get dedicated comparator IC's from all sorts of vendors, or use an op-amp circuit if you prefer.
If the signal goes over a pre-determined threshold, the comparator would have to pulse or assert a digital line. That could trigger an external interrupt pin on your microcontroller, which will execute custom handler code. See attachInterrupt() for more information.


text:
Any way to use F macro with a passed variable?
I want to know if it's possible to use the F() macro on text that is being passed to a function.
This is an example function:
void displayMenu(const char * txt, byte &var) {
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(txt);
  lcd.setCursor(0, 1);
  lcd.print(var);
}

This is how I'm calling the function:
displayMenu("Backlight:", backlight);

If I didn't separate the repeating code into a separate function, I would've been able to write it out like this:
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(F("Backlight: "));
lcd.setCursor(0, 1);
lcd.print(var);

If I try to do:
displayMenu(F("Backlight"), backlight);

it doesn't work. Also if I try to do this in the function:
lcd.print(F(txt));

that also doesn't work.
I'm just wondering if such a thing is possible.

There is a special type for just this occasion - the __FlashStringHelper type.
void displayMenu(const __FlashStringHelper *txt, byte var) {
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(txt);
  lcd.setCursor(0, 1);
  lcd.print(var);
}

Note I removed the & from var - you don't want that unless you are passing a complex class or are wanting to modify the contents of var in the function and have it reflected back outside the function.  Passing a reference to a byte (&var) requires two bytes of data - just passing the content of a byte only requires one byte of data.

That's awesome! Thanks a lot! At first I was getting "cannot convert from type X to type Y..." errors, but I fixed it by enclosing all the passed text inside the macro, like this: displayMenu(F("Backlight"), backlight); And thanks for pointing out the & problem! I probably had accidentally copied that from an older function I was using that actually needed to modify the passed variable.

I feel silly for asking the following, and I'm sure it's just the "Everything feels snappier!" bug, but just to confirm... Is there any way that this change in the code might've perceptibly increased the lcd display speed, like when switching between menus?

The removing of the & may have had a very slight effect on the speed, but it's unlikely the text changes have done anything...


text:
433Mhz transmitter interference when using long cable, only on Arduino Due
When the 433 transmitter is wired close to the Arduino Due (within 12" away), it works as expected. But when I put it on the end of a 15' cable, it has the following 2 symptoms:
-All the other nearby 433Mhz transmitters and receivers stop working. (I've never seen this happen from any other cause).
-My Extech 480836 EMF meter shows a big jump in electromagnetic radiation along the entire length of the 15' cable (it jumps from 0.1 uW/m2 to 3 mW/m2 a few inches away). The reading only goes down to normal if I unplug the transmitter's data wire from the Arduino.
The transmitter in question is still able to send signals correctly when wired with a 15' cable to the Due (properly activating remote switches), even though it disables every other 433 transmitter in the area.
I've tested this with 2 different kinds of 433 transmitters, getting the same result. Both of the transmitters work fine whenever wired closely to the Arduino Due, and both work as expected when connected to an Arduino Uno. The problems still occur even if I'm not sending any wireless transmissions from the code. Disconnecting the transmitter's data wire from the Arduino Due causes the problem to stop immediately.
I'm using the RCSwitch library. The simple code below works fine on an Arduino Uno, whether the transmitter is wired far or close to the Uno. The same code works fine with the Due when the transmitter is close to the Due. But when the transmitter is wired 15' away from the Due, then the problems occur. On the Due I've tested using 5v and 3v for powering the transmitter. Changing the voltages doesn't seem to affect the problem.
#include <RCSwitch.h>
RCSwitch mySwitch = RCSwitch();

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

  // Transmitter is connected to Arduino Pin #8
  mySwitch.enableTransmit(8);
}

void loop() {}

Why am I having this strange behavior? Do you have any suggestions on how to fix it?

Try adding a decoupling capacitor between VCC and GND on/near the transmitter. You could also try shielded wires. It might be helpful to know what specific kind/model of transmitter you use.

I just tried adding a 1uF decoupling capacitor, and it didn't seem to have an effect on the problem. One new thing I learned is that when the above code is run on the Due, the output pin is constantly outputting 3 volts. The same code on the Uno doesn't cause the pin to output voltage.

I found someone else who had the exact same problem on the Arduino forum: http://forum.arduino.cc/index.php?topic=215385.0 . Nobody responded to his question.

I think I found the problem. It seems that there's an anomaly with the Due where when a pinmode is set as OUTPUT, it sets the pin as HIGH by default, whereas with the other Arduinos it's set as LOW. This forum page is discussing the problem: http://forum.arduino.cc/index.php?topic=154869.0
Likewise this page suggests the problem is a bug with the wiring_digital.c file: http://forum.arduino.cc/index.php?topic=185230.0
In RCSwitch.cpp, this is the enableTransmit code:
void RCSwitch::enableTransmit(int nTransmitterPin) {
  this->nTransmitterPin = nTransmitterPin;
  pinMode(this->nTransmitterPin, OUTPUT);
}

It seems the code sets the pin as OUTPUT, which would cause an anomaly on the Due alone.
I solved the problem by calling the enableTransmit function just before sending a signal, and then calling disableTransmit() immediately afterwards. Can anyone think of a cleaner/better solution?
Out of curiosity, can anyone suggest what a standard transmitter might be sending when the data line is constantly held at HIGH?

It just sends a 433Mhz signal, all the time. Which would explain why all other receivers/transmitters don't work any more. These modules send data by turning the signal on an off (On-off keying).


text:
Why does Arduino Due Native Port change serial ports after every reset? (Linux)
Previously I had my Due connected via Programming Port for weeks, and it never changed serial ports after pressing the reset button. Recently I switched to having it connected via the Native Port instead, and was surprised to see that it changes port numbers every time I press the reset button.
For example if it was on ttyATM1 beforehand, after pressing reset it'll be on ttyATM2 instead. It changes numbers like this after every reset. Is this normal behavior?
I have a python script sending serial data to the Due, and I have to change the port number in the python code every time the Due changes ports.

It happens because of Linux, not because of the Arduino.
Since you unplug/reset the DUE while the port is still open, when it's back online, the old file name is still in use, so a new one is created.
Just close the port before resetting the DUE and you will see that after the reset it will have the same one.
You can easily reproduce the same issue with a serial to usb adapter (/dev/ttyUSBS0,1,2,etc) and screen or minicom.
To make your program more robust, you should listen for kernel events and open the port accordingly.

Thanks! I'm glad you mentioned that it's possible to make a check for those events. I found this nice page with lots of info on how to do it: http://stackoverflow.com/questions/2530096/how-to-find-all-serial-devices-ttys-ttyusb-on-linux-without-opening-them. And then the command:  "# ls /dev/serial/by-id" neatly lists the Due as: "usb-Arduino_LLC_Arduino_Due-if00". Maybe it won't be as difficult as I had thought.

There is a problem with that: if you have 2 devices with the same id, your program might get confused, if it has to tell them apart.  In such case, if you do not change the way they are plugged, but simply restart them, like with the Arduino reset, you can inspect the usb device tree.

Thanks. I also frequently plug/unplug the units. If I'm expecting to only have one Due in the foreseeable future, would it be suitable to just detect the text for "Due"?

Or for whatever is the id shown by your device. Yes, it's ok as long as you are aware of the potential issue and document it in the code, so that later on you or someone else doesn't have to remember it.


text:
Powering USB device from arduino uno?
I'm wanting to power a USB device from an Arduino Uno. Forgetting about the two data pins, it just requires power. Using a power meter, I can detect the 5v pin at about 4.95 volts, however I don't have access to any resistors at the moment so cannot test the amperage because it just shorts.
The USB device I want to power requires ~300mA (can't remember specifically). First of all, does the Arduino get 100mA or 500mA when getting power from the USB? Is this changeable depending on the setting on the USB Host (High 500mA, or Low 100mA)?
Secondly, how much would actually be usable? I assume the Arduino itself would require some of that current? Even more if a program where running on it at the same time? (I have no idea how computers utilize power) I would like to just hook up my usb device to ground and 5V with whatever resistors (and any other electrical components) in between to bring it down from 500mA to the required ~300mA.

If your Uno has access to a USB port for its own power then why not just use another USB port for the other USB device?

The Arduino receives 500mA max from USB power.  That is per the USB specification, and the Arduino has a 500mA resettable fuse on the USB power to protect your computer's USB port from 'accidents'.
As to the question of whether it is configurable between 500mA/100mA, generally no it's not. I believe that part of the USB negotiation that occurs when the Arduino connects to your PC is that the Arduino describes itself to the computer, and it reports that it is a 500mA device. Bottom line is, you won't need to do anything special in this regard.
Now, how much of the power is needed for the Arduino, and how much is left over - well that depends on what else the Arduino is doing and what else it's powering (LEDs, etc.). If the Arduino is not doing much else, than 200mA should be plenty of headroom for it.
If you power the Arduino through the PWR Jack (or the Vin), then the voltage should be a minimum of 7V. That is because it is feeding into a 5v regulator, which has some voltage drop, so it needs about 7V to be able to consistently supply 5V output.  If you power the Arduino manually (through the 5V pin), you want to give it 5V. Anything less than 5V would be considered overclocking. (The ATMEGA328P needs 5V to operate at 16mHz, but can run at lower voltages when clocked at lower speeds.)
Also, keep in mind that the USB port on the Arduino is a USB 'client', not a USB host or USB OTG. Therefore, the port can not be used to supply outbound power. You can power your extra device from the Arduino's 5V and GND pins.

The only AC/DC adapter I can find that matches is a switchable 6V/9V/12V with just under 1000mA. However it outputs via a negative and positive wire. So inputting directly to the vin pin is the same as inputting DC through the power jack? I would just need to connect positive DC output to vin and negative to any ground on the arduino, and that would give me a regulated 5V output on the 5V pin?

That's correct. The Vin pin and the PWR jack both feed into the power regulator. You can connect the positive DC output to Vin, and the negative output to any GND. Set the adapter to 9V.
The only thing the PWR jack has that the Vin does not, is a power diode that protects against incorrect polarity (the + and - reversed).  The Vin does not have that protection, so just don't hook it up backwards.

You'd have to test this but there's a chance you could supply the Arduino using a DC power supply on it's 5V pin. In this case DO NOT TURN YPUR SUPPLY HIGHER THAN 5V, as I don't believe there is any protection and will send the full voltage to the USB.
A safer option would be the Vin pin. Normally you'd want to put 7-12 Volts to this pin but you may want to start at 5V and work your way up just to be safe.
Someone please corrects if I am wrong, but if you never apply more than an external 5V your worst case scenario would be burning out the Arduino but not the USB device.

Please correct me if I'm wrong: The vin pin gets its power from the external DC jack at whatever voltage is supplied, and so can the 5V (limiting voltage to 5) and they both share the available current from the DC input? Could you explain why using the vin pin is safer? Wouldn't it be fine to use the 5V since I am powering a USB 5V device?
Also, I assume grounding a circuit on the arduino using a custom volt and/or amps DC power source may well damage the board? You stated max of 7-12Vs, any idea of what sort of max amps?

The Vin pin is the input for external DC voltage, whereas the 5V pin is regulated as a 5V output for powering other equipment.  For this reason using the Vin pin is safer because it regulates the outputs (including the 5V pin) to a constant 5V.  If say 6 or 7 volts were applied to the 5V pin, you may damage the Arduino or draw unnecessary current from your power supply.
I suggested 7-12V on Vin because this is the safe range specified by Arduino and will turn on the onboard voltage regulator. Turn the current to a max on the power supply, the actual current drawn is regulated by the Arduino

As far as current limits I believe they are 500 mA for the 5V pin and 50 mA on each of the signal output pins.  In regards to your original question, have you tried connecting ~9V DC to the Vin pin and testing for 5V on the USB port? I still believe this is your best option if it works.


text:
How to: soil moisture measurement with WaterMark?
I am new with Arduino, and i cant find documentation about how to connect Arduino with Watermark successfully.
I would like to connect my Arduino UNO with a watermark like this:
http://guideimg.alibaba.com/images/shop/72/08/19/4/watermark-soil-moisture-sensor-w-15-cable_3234944.jpg
Does anyone know any schema or documentation about how to do it? Have anyone tried it before?
I have found this: https://oceancontrols.com.au/datasheet/davis/ECS-014_07395-158_IM_06440_6470.pdf
but still not clear how to do it in Arduino.
Thanks you for your time.

The link to the PDF is not found, and the only other thing provided is a JPG image of the sensor, which is not helpful.

You can google
"Arduino-based system for soil moisture measurement"
and the author about this paper is "Vuk Radman" .

Now, I am also try to find the method using Arduino to connect WaterMark 200ss Sensor. The paper I share to you is what I have found from GoogleScholar, but I haven't used this method yet. Nevertheless, I think the method mentioned in the paper is feasible. Hopefully, this information can help you.