Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int n = 0;
- int BUTTON = 4;
- int brightness = 20; //how bright the led is
- int fadeAmount = 10; // how many points to fade the LED by
- unsigned long currentTime;
- unsigned long loopTime;
- const int pin_A = 2; // pin 4
- const int pin_B = 3; // pin 5
- unsigned char encoder_A;
- unsigned char encoder_B;
- unsigned char encoder_A_prev=0;
- void setup() {
- // declare pin 9 to be an output:
- Serial.begin(9600);
- pinMode(9, OUTPUT);
- pinMode(pin_A, INPUT);
- pinMode(pin_B, INPUT);
- currentTime = millis();
- loopTime = currentTime;
- pinMode(BUTTON, INPUT);
- Serial.begin(9600);
- }
- void loop() {
- // get the current elapsed time:
- Serial.println(n);
- //delay(400);
- currentTime = millis();
- if(currentTime >= (loopTime + 3)){
- //5ms since last check of encoder = 200Hz
- encoder_A = digitalRead(pin_A); //Read encoder pins
- encoder_B = digitalRead(pin_B);
- Serial.print(encoder_A);
- Serial.print(encoder_B);
- if((!encoder_A) && (encoder_A_prev)){
- // A has gone from high to low
- if(encoder_B) {
- // B is high so clockwise
- // increase the brightness, dont go over 255
- if(brightness + fadeAmount <=255) brightness += fadeAmount;
- }
- else {
- //B is low so counter-clockwise
- // decrease the brightness, dont go below 0
- if(brightness - fadeAmount >= 0) brightness -= fadeAmount;
- }
- }
- encoder_A_prev = encoder_A; // store value of A for next time
- // set the brightness of pin 9:
- if(digitalRead(BUTTON) == HIGH)
- {
- analogWrite(9, brightness);
- }
- else
- {
- analogWrite(9, 0);
- }
- loopTime = currentTime; // Updates loopTime
- }
- //other processing can be done here
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement