I am trying to read an analog pin using "analogRead" and when I use "Serial.print" the value always comes up as "54". I was wondering if anyone can shed some light as to what my problem may be. I have tried connecting a potentiometer and connecting the pin directly to ground and the output remains the same.
Could this problem be related to the Due in some way? I have tried reading various analog pins on 2 separate Due's and I can only get constant values to return.
Please name the analog pin like this: pinPotentionmeter
That way you see that it is the pin number.
When using analogRead, you don't have to set it as input, but it's no problem either.
int analog_value = analogRead (pinPotentiometer);
Serial.println (analog_value);
delay(1000);
Your program assigns the value represented by A0 to the variable Potentiometer. It never assigns anything else to it, so the value of Potentiometer never changes.
For the Due, the value of A0 is established in the file:
../hardware/arduino/sam/variants/arduino_due_x/variants.h.
If you look into that file, you'll find this line:static const uint8_t A0 = 54;When you print A0, you get, "54." Earlier replies in this thread describe how to store and print the analog value.
Here is your code doing what you wanted. Notice the use of constants for values that won't change. As sketches grow the more thankful you will be taking this approach.
const int POT_PIN = A0;
const long BAUD_RATE = 9600L;
const unsigned long PAUSE_TIME = 1000UL;
void setup() {
pinMode(POT_PIN, INPUT);
Serial.begin(BAUD_RATE);
}
void loop() {
int potVal = analogRead(POT_PIN);
Serial.println(potVal);
delay(PAUSE_TIME);
}
Suggested reading:
The read this before posting thread.
The Arduino style guide.
As much as you can about variables in C++. Pay attention to type and scope.
Jimmy60:
Here is your code doing what you wanted. Notice the use of constants for values that won't change. As sketches grow the more thankful you will be taking this approach.
const int POT_PIN = A0;
const long BAUD_RATE = 9600L;
const unsigned long PAUSE_TIME = 1000UL;
void loop() {
int potVal = analogRead(POT_PIN);
Serial.println(potVal);
delay(PAUSE_TIME);
}
Suggested reading:
The read this before posting thread.
The Arduino style guide.
As much as you can about variables in C++. Pay attention to type and scope.
Good stuff. And I'm more than sure you know this next step but the OP does not.
void loop() {
static int lastPotVal = 0; // function static variables stay and keep their value, this one STARTS at zero
int potVal = analogRead(POT_PIN);
if ( potVal != lastPotVal )
{
Serial.println(potVal);
}
lastPotVal = PotVal;
}
This gets rid of the delay and only prints when the pot is turning.
You get to see any change immediately.