Analog Input & Output

Potentiometer:

Inside a potentiometer:
potentiometer1.gif (472×323)

Photoresistor:

Pulse Width Modulation:
What is PWM: Pulse Width Modulation

const int ledPin = 2;
bool ledState = LOW;

// a really longer number with no + or - sign
unsigned long toggleTime = 0;
int triggerInterval = 500;

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

void loop() {
  // read the analog input
  int knobValue = analogRead(A0);
  // map that input to a range appropriate for our use
  // in this case, we take the range of the photocell and map it to millis between 10 & 500
  // this is the blink interval for the LED
  triggerInterval = map(knobValue, 190, 860, 10, 500);

  // print out the original value and the mapped value on the same line
  Serial.print(knobValue);
  Serial.print(" ");
  Serial.println(triggerInterval);

  // if the current time (millis) is more than the exact time when we are supposed to toggle
  if (millis() > toggleTime) {
    // flip the LED to the opposite of what it was
    ledState = !ledState;
    // set the next time the LED should toggle
    // to the current time + whatever the blink interval amount of time is
    toggleTime = millis() + triggerInterval;
  }

  // turn the LED on or off based on the ledState vaviable
  digitalWrite(ledPin, ledState);
}

 

Leave a Reply