Go Down

Topic: arduino due- problem with pins (Read 823 times) previous topic - next topic

louk_leo

Hi everyone,
I have a problem. I have an arduino due and I just want to control a led. When I use pin 13 as a led pin it works just fine, but when I want to use pin 50 for example, it doesn't work.
thanks in advance,
Loukas

louk_leo

#1
Apr 10, 2013, 01:16 pm Last Edit: Apr 10, 2013, 01:21 pm by louk_leo Reason: 1
i have this code, button1 works fine with led1, while when i press button2 led2 goes on, but i cannot make it go off. buttons work the problem is with the led2 output.
Code: [Select]

const int led1=32;
const int led2=33;
const int button1=24;
const int button2=25;


void setup() {
 //pinmode setup
 pinMode (led1, OUTPUT);
 pinMode (button1, INPUT);
 pinMode (led2, OUTPUT);
 pinMode (button2, INPUT);
 digitalWrite (led1, LOW);
 digitalWrite (led2, LOW);
}

void loop() {
 //mapping betwenn leds and buttons
 buttonLed(button2, led2);
 buttonLed(button1, led1);
 
}


//if button pressed, changes the led's state but while the button is being pressed it gets into a loop,
// so if i keep the button pressed, my led doesn't blink
int buttonLed(int i, int j){
 if (getSample(i)){
   changeLedState(j);
   while (getSample(i)){}
 }
}

//gets sample from buttons periodically to deal with noise,
//if 8 (or more) out of 10 samples are high, button is being pressed
int getSample(int i){
 int count=0;
 for (int j=0; j < 10; j++){
   if (digitalRead(i)==HIGH) count++;
   delay (2);
 }
 if (count>=8){
   return HIGH;
 }
 else return LOW;
}

void changeLedState(int i){
 if (digitalRead(i)==LOW)
   digitalWrite(i, HIGH);
 else
   digitalWrite (i, LOW);
}

louk_leo

Having tested many things, I now know that digitalRead(led2) is always LOW, no matter if the led is on or off. Can anyone say why?

TheKitty

You should define two variable, such as ledstate1 and ledstate2.  In setup set them both to LOW.  When you toggle an LED, set the variable to HIGH.  When you want to toggle one, you don't check the pin state but the viariable state, then change the ledstate variable to opposite of what it is then digitalwrite that LED state.  Thus you are keeping track of the state and not  relying on the board to return its state.  A tiny bit of extra work but worth it.

louk_leo

thank you very much

i transformed the function:
Code: [Select]
void changeLedState(int i){
  if (digitalRead(i)==LOW)
    digitalWrite(i, HIGH);
  else
    digitalWrite (i, LOW);
}


into

Code: [Select]
void changeLedState(int i){
  int j=0;
  pinMode(i, INPUT);
  if (digitalRead(i)) j=1;
  pinMode(i, OUTPUT);
  if (j!=1)
    digitalWrite(i, HIGH);
  else
    digitalWrite (i, LOW);
   
}


and that works too.

Go Up