Why does reading an analog pin give a different results when interfacing with Processing? I am interested in measuring the voltage over an analog pin (A6). When I use the Arduino IDE to print the results through the serial I get values around 300.

Here's the code

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

void loop(){
   Serial.println(analogRead(A6));
   delay(50);
}


When I try to run a equivalent program using Processing and interfacing it through Firmata and the corresponding library, I get values around 900.

Here's the Processing code:

import cc.arduino.*;
import processing.serial.*;

Arduino arduino;

void setup(){
   arduino = new Arduino(this,Arduino.list()[0], 57600);
   delay(2000);
}

void draw(){
  System.out.println(arduino.analogRead(6));
  delay(50);
}


Does anybody know what could be the issue? I should probably rather trust the values given directly by the Arduino without interfacing, right?

The pin is connected to a circuit with supply voltage.
I also tried reading the values directly using Serial in Processing (so without using the cc.arduino.* - library) and that showed me the values around 300. So I guess the difference is caused by the arduino.analogRead() method. I am puzzled as to whether that's a bug in the library or something else.

The problem seems to be me not properly initialising the pins. But calling

arduino.pinMode(6,Arduino.ANALOG);


in the setup method does nothing, as does Arduino.PWM, SERVO and any combination I tried. I thought, maybe Processing tried to assign D6 as analog instead of A6, but changing the value to 20 (as it's the pin number according to this) simply caused an OutOfBoundsException.
You have not provided a schematic of how the Arduino is wired up.

However, if nothing is connected to the pin, i.e. it is not connected to ground or a supply voltage, then the input will float. That means that just by placing your hand near the Arduino, then analogRead() will produce a different value than when your hand in not near it.

I would hazard a guess that if you ran both sets of code multiple times then you will get different answers each time, if you start waving your hand around the Arduino.

Try that first, and then tie the input to either HIGH or LOW and then repeat the previous experiment.

In the second case the results should be consistent, and equal in the Arduino and Processing alike.



However, according to your comment, that is not your issue, as your inputs are not floating.

I think that issue is actually this:


  Even with Firmata installed, the Processing application needs to define the pin mode for ALL the pins being referenced, telling the Arduino instance that xPin, yPin, and zPin are ANALOG pins.


Source: Re: Firmata problem with analogRead in Processing Library

Looking at your Processing code the pins are not defined. You need to do so.

With the Arduino code, there is no need to define the analogue pins.