0

I have a simple task of toggling an output pin state on Arduino Due using Arduino IDE 1.5.2. I have tried the code like this:

int pinnum = 13;
void setup() {
  pinMode(pinnum, OUTPUT);  // use on-board LED
} 

void loop() {
  digitalWrite(pinnum, !digitalRead(pinnum));
  delay(1000);  // wait around for 1 sec (1000 ms)
}

This does nothing. Pin 13 stays HIGH all the time. What am I doing wrong?

user2113118
  • 3
  • 1
  • 2
  • Hi I deleted my answer as it was no help! http://stackoverflow.com/questions/6160963/how-can-i-digitalread-a-pin-that-is-in-pinmode-output I think you should be able to get something working from this url tho, – David K Feb 27 '13 at 22:22

2 Answers2

4

There is a bug when reading the state of a pin set as OUTPUT. As a temporary workaround, set the pin as an input at some point before setting it as an output if your circuit allows, like so:

int pinnum = 13;
void setup() {
  pinMode(pinnum, INPUT);   // Work around bug
  pinMode(pinnum, OUTPUT);  // use on-board LED
} 

void loop() {
  digitalWrite(pinnum, !digitalRead(pinnum));
  delay(1000);  // wait around for 1 sec (1000 ms)
}

For more details, see my post at http://forum.arduino.cc/index.php?topic=185291.0.

EDIT: Sorry for my previous terrible answer.

m3741
  • 56
  • 3
0

I think your problem is that you cannot read the digital value that you previously sent to pin 13. You always read a low level since an LED is connected to ground.

Solution: Have a copy of the logic level you send to pin 13 stored in a variable. This variable I name mem in my code below. You don't need to read pin 13 because now you have a copy in mem. This copy you invert before sending it to pin 13 as you have done in your code example.

Your problem is usually described as a warning when performing read-modify-write operations on port pins—refer to the datasheet taken from the microcontroller manufacturer.

int pinnum = 13;
int mem = 0;
void setup() {
  pinMode(pinnum, OUTPUT);  // use on-board LED
} 

void loop() {
  digitalWrite(pinnum, mem);
  mem=!mem;
  delay(1000);  // wait around for 1 sec (1000 ms)
}
Keith Pinson
  • 7,835
  • 7
  • 61
  • 104
Leif
  • 1