Friday, February 15, 2013

Potentiometer with Alternating LEDs

This was a difficult program, and I still didn't get it all the way...

This video explains what I was trying to do:


Above are two different versions of the code I was trying. In the COM3 window I was showing what happens after you do it a couple of times. Where there should be a zero, there is a two. Midway I reset it, and you can see it return to the state it should be. Here is the code from the one on the left:


const int potPin = A0;
const int led = 3;
const int led2 = 5;
int potValue = 0;
int newValue = 0;
int value2 = 0;

void setup() {
 
  pinMode(led, OUTPUT);
  pinMode(led2, OUTPUT);
  Serial.begin(9600);
 
}

void loop() {
 
  potValue = analogRead(potPin);
  potValue = map(potValue,0,1023,0,1020);
 
  if(potValue <= 510){
    if(potValue < 255){
      newValue = map(potValue,0,255,0,255);
    }
    else{
    newValue = map(potValue,256,510,255,0);
    value2 = 0;
    }
  }
  else if(potValue >=511){
    if(potValue <= 765){
      value2 = map(potValue,511,765,0,255);
    }
    else{
      value2 = map(potValue,766,1020,255,0);
      newValue = 0;
    }
  }
 
  analogWrite(led, newValue);
  analogWrite(led2, value2);
 
  Serial.print(potValue);
  Serial.print("   ");
  Serial.print(newValue);
  Serial.print("   ");
  Serial.println(value2);
  delay(50);
}

No comments:

Post a Comment