I am having trouble using digital pin 4 for output and analog pin A4 for input AT THE SAME TIME.
In case it matters, I have a photoresistor and a fixed resistor connected like this to A4 on
5V ---
|
photoresistor (variable)
|
A4
|
5k resistor (fixed)
|
GND
I.e. voltage divider being read by A4
I have created the following test script that illustrates the problem.
When I run this script as it is below, my Serial monitor outputs a stream of values like this:
944
948
948
944
949
947
947
949
and the values change as I change the light on the photoresistor.
BUT, if I uncomment the line that tries to set up pin 4 for digital OUTPUT, the values output change to this:
79
78
79
78
79
78
79
78
79
78
(I notice that 1023 - 947 = 76, so it is as if the values are inverted!)
I very much appreciate your help as I am stumped as to why I can't I use digital pin 4 and A4 at the same time?
-Doug
void setup() {
pinMode(A4, INPUT);
// pinMode(4, OUTPUT); // Uncomment this line and the analog port reads differently
Serial.begin(9600);
while (!Serial);
Serial.print("Starting");
}
void loop() {
Serial.println(analogRead(A4));
}
Analogue pin 4 and digital pin 4 are different pins, it should not be an issue. Something is not as you think it is. Please provide a clear photo of what you have, maybe something will show up on that.
Thank you 6v6gt for suggesting that I check what I have connected to pin 4. I intended to have it connected to an LED is all, but in the end (long story below) pins 4 and A4 were accidentally connected to each other! (not what I intended to do).
Long story as to how this happened: I am using a ribbon cable to connect the NANO on one prototyping board to a second prototyping board which has screw terminals to connect the photocell and LED at a remote location. The cable is a 6 conductor ribbon cable with 2x3 socket connectors on either end.
Connector with numbers indicating what conductor on the cable should be connected to each:
1 3 5
2 4 6
As it happens, the ribbon cable I used to make the cables is slightly smaller than it should be to work with the crimp on connectors, so while most of the connections were OK, some of the adjacent wires in the cable were actually connected to each other. The wires to the LED and the photocell were positions 3 and 4 in the diagram above, and they were actually connected to each other! I did not notice this when making the cables, but I will check that from now on.
I knew my code should work and I am sorry I did not look more closely at the cable and the other connections before posting.
Hi Perry,
Thank you for your reply. Seem my reply to an earlier poster above. You were on the right track, too! -- I did not realize that I had accidentally connected 4 and A4 together.
Cheers,
Doug