Hackster is hosting Hackster Holidays, Ep. 7: Livestream & Giveaway Drawing. Watch previous episodes or stream live on Friday!Stream Hackster Holidays, Ep. 7 on Friday!
Tal O
Published © GPL3+

Binary Arithmetic and Port Manipulation – Part II

One port to read them all!

BeginnerFull instructions provided1,993
Binary Arithmetic and Port Manipulation – Part II

Things used in this project

Hardware components

Arduino UNO
Arduino UNO
×1
momentary push button
×8
I2C 16x2 Arduino LCD Display Module
DFRobot I2C 16x2 Arduino LCD Display Module
×1

Software apps and online services

Arduino IDE
Arduino IDE
wokwi Arduino web simulator

Story

Read more

Schematics

schmatics_bb_s7Ql4lY7uM.png

Code

Untitled file

Arduino
//YWROBOT
//Compatible with the Arduino IDE 1.0
//Library version:1.1
#include <LiquidCrystal_I2C.h>

byte currentButtonState = 0;
byte prevButtonState = 99; // set to diffretn number then curren to trigger update on load

// set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27,20,4);  

void setup()
{
   // initialize the LCD
  lcd.init();

  // set pull ups
  for (int i = 0; i < 8; i++) {
    pinMode(i, INPUT_PULLUP);
  } //end for


  // Turn on the blacklight.
  lcd.backlight();


  //startTimer();
  //  DDRD = B00000000; // input
  //  PORTD = B11111111; // pullup
  //endTimerAndPrint();
  
}


void loop()
{
  // reset
  currentButtonState = 0;

  //collect state
  for (int i = 0; i < 8; i++) {
    currentButtonState |= (!digitalRead(i)) << i;
  } //end for

  //currentButtonState = ~PIND ; //read state

  // if state chnaged
  if (prevButtonState != currentButtonState) {
    //clear screen
    lcd.clear();

    // print hex
    lcd.setCursor(0, 0);
    lcd.print("0x");
    if (currentButtonState < 16) {
      lcd.print("0"); // in case we got single digit hex
    }//end if
    lcd.print(currentButtonState, HEX);

    // print binnary
    for (int i = 0; i < 8; i++) {
      lcd.setCursor((7 - i), 1);
      if (bitRead(currentButtonState, i)) {
        lcd.print("1");
      } else {
        lcd.print("0");
      } //end if
    } //end for

    // special key combination
    switch (currentButtonState) {
      case B10000001:
        lcd.noBacklight();
        break;
      case B01000010:
        lcd.backlight();
        break;

    } // end switch

  } //end if

  // set prev to current for change
  prevButtonState = currentButtonState;



  //startTimer();
  //currentButtonState = ~PIND ; //read state
  //endTimerAndPrint();
  //delay(1000);
}


void startTimer() {
  TCCR1A = 0;
  TCCR1B = bit(CS10);
  TCNT1 = 0;
}

void endTimerAndPrint() {
  unsigned int cycles = TCNT1;
  //clear screen
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Cyc: ");
  lcd.print(cycles - 1);
  lcd.setCursor(0, 1);
  lcd.print("Mic: ");
  lcd.print((float)(cycles - 1) / 16);

}

Credits

Tal O
20 projects • 55 followers
Maker @ heart

Comments