When I define an integer variable that is not a pin on arduino mega, the plotter is still floating

Hi, I am a newbie to Arduino and Arduino programming, so please bear with me. I was experimenting to see what will happen to the plotter if I define a variable that is completely out of the pin ranges on the board (I defined int sensePin = 100).
Here is my code:
'''
int sensePin = 100;

// the analogue pin number

void setup(){
analogReference(DEFAULT);

Serial.begin(9600);
};
// it's by default so not necessary

void loop(){
Serial.println(analogRead(sensePin));
delay(500);
}
'''

The plotter looks like:

What is the point of your tutorial?

The input mix calculation probably simply wraps - there'll be something like "inputPin &= 7;" or similar in the driver code - you're probably plotting the input on pin 4.

Please remember to use code tags when posting code

What is?

The Arduino runtime library does very little to protect you against using invalid pin numbers. Your results will be undefined and could do anything. It doesn't even fail safely for pins that exist. If you are using an Arduino NANO and write:
pinMode(A7, INPUT);
what you get is:
pinMode(9, INPUT);
That can cause a real mess if you had previously set Pin 9 as an OUTPUT.

Perhaps "Pin 100" maps to one of the actual pins. Try grounding each analog input pin, in turn, to see which one you have accidentally selected.

1 Like

Hi, thanks for the help and quick reply.

One last question, if I do pinMode(PF0, INPUT), is it equivalent to pinMode(A0, INPUT). Since PF0 and A0 are the same pin-in on the Arduino Mega 2560 board.

@roseroserose, your topic has been moved to a more suitable location on the forum. Introductory Tutorials is not for questions but for tutorials. Feel free to write a tutorial once you have mastered your problem :wink:

Simple way to find out; print the value of A0, and the value of PF0.

Also, please see reply #3

Thanks for pointing it out! I'm new to the forum and I didn't know what's the appropriate topic this question is subjected to lol.

A) Don't use pinMode() on analog input pins unless you are using them as digital pins (digitalRead() or digitalWrite()).

B) NO. PF0 has the value 0 so it will set the pinMode() on DIGITAL pin zero. If you use analogRead(PF0) that WILL map to A0, but only because analogRead() maps 0, 1, 2,... to A0, A1, A2...

C) The ATmega pin names are only used for Direct Port Access. For example, PORTF |= 1 << PF0; is roughly equivalent to digitalWrite(A0, HIGH);. The two sets of names are NOT interchangeable. PORTF |= 1 << A0; won't do anything because 'A0' is a value greater than 8 and digitalWrite(PF0, HIGH); sets Pin 0 to HIGH because 'PF0' is 0.

1 Like

Thanks for the detailed explanation. Very appreciated and it is very helpful solution, since I'm completely new to arduino! :))

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.