Advertisement
Guest User

Untitled

a guest
Jun 20th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. int n = 0;
  2. int BUTTON = 4;
  3. int brightness = 20; //how bright the led is
  4. int fadeAmount = 10; // how many points to fade the LED by
  5. unsigned long currentTime;
  6. unsigned long loopTime;
  7. const int pin_A = 2; // pin 4
  8. const int pin_B = 3; // pin 5
  9. unsigned char encoder_A;
  10. unsigned char encoder_B;
  11. unsigned char encoder_A_prev=0;
  12.  
  13.  
  14. void setup() {
  15. // declare pin 9 to be an output:
  16. Serial.begin(9600);
  17. pinMode(9, OUTPUT);
  18. pinMode(pin_A, INPUT);
  19. pinMode(pin_B, INPUT);
  20. currentTime = millis();
  21. loopTime = currentTime;
  22. pinMode(BUTTON, INPUT);
  23.  
  24.  
  25. Serial.begin(9600);
  26.  
  27. }
  28.  
  29. void loop() {
  30. // get the current elapsed time:
  31. Serial.println(n);
  32. //delay(400);
  33. currentTime = millis();
  34. if(currentTime >= (loopTime + 3)){
  35. //5ms since last check of encoder = 200Hz
  36. encoder_A = digitalRead(pin_A); //Read encoder pins
  37. encoder_B = digitalRead(pin_B);
  38. Serial.print(encoder_A);
  39. Serial.print(encoder_B);
  40. if((!encoder_A) && (encoder_A_prev)){
  41. // A has gone from high to low
  42. if(encoder_B) {
  43. // B is high so clockwise
  44. // increase the brightness, dont go over 255
  45. if(brightness + fadeAmount <=255) brightness += fadeAmount;
  46. }
  47. else {
  48. //B is low so counter-clockwise
  49. // decrease the brightness, dont go below 0
  50. if(brightness - fadeAmount >= 0) brightness -= fadeAmount;
  51. }
  52.  
  53. }
  54. encoder_A_prev = encoder_A; // store value of A for next time
  55.  
  56. // set the brightness of pin 9:
  57.  
  58. if(digitalRead(BUTTON) == HIGH)
  59. {
  60. analogWrite(9, brightness);
  61. }
  62. else
  63. {
  64. analogWrite(9, 0);
  65. }
  66.  
  67. loopTime = currentTime; // Updates loopTime
  68. }
  69. //other processing can be done here
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement