Advertisement
chayanforyou

8 Bit Binary Counter - Arduino

Jun 24th, 2018
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.49 KB | None | 0 0
  1. class BinaryCounter {
  2.   private:
  3.     static const uint8_t showSingleValuePin = 0;
  4.     static const uint8_t digitCount = 8;
  5.     const uint8_t pins[digitCount] = {12, 11, 10, 9, 8, 7, 6, 5};
  6.     uint8_t count = 0;
  7.     uint8_t valuetoShow = 255;
  8.  
  9.   public:
  10.     BinaryCounter();
  11.     void increment();
  12.     uint8_t* getBinaryDigits(uint8_t num);
  13. };
  14.  
  15.  
  16. BinaryCounter::BinaryCounter() {
  17.   //set LED all pins to output mode
  18.   for(int i = 0; i < digitCount; i++) {
  19.     pinMode(pins[i], OUTPUT);  
  20.   }
  21. }
  22.  
  23.  
  24. uint8_t* BinaryCounter::getBinaryDigits(uint8_t num) {
  25.   // Make a byte array to hold all of the binary digits.
  26.   uint8_t *digits = new uint8_t[digitCount];
  27.   memset(digits, 0, digitCount * sizeof(uint8_t));
  28.  
  29.   uint8_t remaining = num;
  30.   uint8_t currentPosition = digitCount-1;
  31.  
  32.   while(remaining > 0) {
  33.     digits[currentPosition] = remaining % 2;
  34.     remaining /= 2;
  35.     currentPosition--;
  36.   }
  37.  
  38.   return digits;
  39. }
  40.  
  41. void BinaryCounter::increment() {
  42.  
  43.   uint8_t* binaryDigits;
  44.  
  45.   if(analogRead(showSingleValuePin) > 500) {
  46.     binaryDigits = getBinaryDigits(valuetoShow );
  47.   }
  48.   else {
  49.     binaryDigits = getBinaryDigits(count);
  50.  
  51.     if(count == 255) {
  52.       count = 0;
  53.     } else {
  54.       count++;  
  55.     }
  56.   }
  57.  
  58.   for(int i = 0; i < digitCount; i++) {
  59.       digitalWrite(pins[i], binaryDigits[i]);
  60.   }
  61.  
  62.   delete binaryDigits;
  63.   delay(500);
  64. }
  65.  
  66. BinaryCounter *counter;
  67.  
  68. void setup()
  69. {
  70.   counter = new BinaryCounter();
  71. }
  72.  
  73. void loop()
  74. {
  75.   counter->increment();
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement