Setting PORTD as BCD question..

is there anyway i can set PORTD as BCD?

for example i have connected 8 leds to pin 0-7

and i want the leds to light up as following using the line of code “PORTD = 10;”

pins 7 6 5 4 3 2 1 0

leds 0 0 0 1 0 0 0 0

I want this to happen so i can hook the portd with two bcd-decoder ICs and display the 2-digit number on two 7 segment displays.

my code currently: (but leds lights up as binary: 00001010)

void setup() {

  pinMode(A0,INPUT); 
  DDRD = B11111111;
  PORTD = 0;

}

void loop() {
  
int button = digitalRead(A0);

  if(button == HIGH){
    
    PORTD = 10;
    
    }

  if(button == LOW){
    PORTD = 0;
 
    }



}

There isn't any hardware setting you can set that will make PORTD convert that automatically for you. I think standard operating procedure is to convert it before you send it to the port.

void setup() {
  pinMode(A0,INPUT); 
  DDRD = B11111111;
  PORTD = 0;
}

void loop() {
  
int button = digitalRead(A0);

  if(button == HIGH){
    byte decimal = 10;
    byte bcd = ((decimal / 10) * 16) + (decimal % 10);    // Convert decimal to bcd
    PORTD = bcd;
   }

  if(button == LOW){
    PORTD = 0;
  }
}

Jimmus:
There isn't any hardware setting you can set that will make PORTD convert that automatically for you. I think standard operating procedure is to convert it before you send it to the port.

Thank you for the information. I initially thought that arduino's portd works similar to pic16's port.

I will now be using the code you provided. Thanks a lot!!!

byte bcd;
byte decimal;
int number;

void setup() {
  pinMode(A0,INPUT); 
  DDRD = B11111111;
  PORTD = 0;
}


void convertndisplay(byte decimal){

    bcd = ((decimal / 10) * 16) + (decimal % 10);    // Convert decimal to bcd
    PORTD = bcd;
}

void loop() {


  
int button = digitalRead(A0);

  if(button == HIGH){
   
   number = 14+15;
   convertndisplay(number); 
   
   }

  if(button == LOW){
    number = 10;
    convertndisplay(number);
  }
}

just another way of converting decimal to bdc:

uint8_t x=10;

uint8_t y = ((x/10)<<4)|(x%10); //decimal to bdc

PORTD = y;

There are processors that can shift 4 bits more efficiently than multiplying by 16. The ATmega328P is not one of them. Fortunately, the compiler recognizes this and implements the bit shifts by a multiply instruction.

I think I've seen this somewhere:

int bcd_num = num + (6 * (num/10));