I want to count from 0-99 with two 7 segment displays using one 8bit counter Variable and C .
Problem is when the Counter is 10 the 8bit has a Value of 0b00001010 but the displays are seperated so the right display needs 4bit binary number of 0b0000 and the left one needs 0b0001, so the display shows 10. How can I solve this problem working when both increasing the counter Variable Value and decreasing the counter Variable Value?
Sourcecode:
while(1)
{
__delay_ms(10);
if(button1 flank detected)
{
counter ;
}
if(button2 flank detected)
{
counter--;
}
PORTD = counter;
}
PORTD is a Port on my microcontroller with 8 pins. So if PORTD is set to 0b0000 0001 Pin 1 would be high. The firs 7 Segment display is connected to the first 4 Pins of PORTD and the second 7 Segment display is connected to the last 4 pins.
CodePudding user response:
To start with, I'd do something like this:
#include <stdint.h>
struct DisplayValues
{
uint8_t left;
uint8_t right;
};
DisplayValues getDisplayValues(uint8_t input)
{
DisplayValues r;
r.right = input % 10;
r.left = input / 10;
return r;
}
You could also just use some global variables or a vector or something instead of defining your own struct. The important thing in this answer is just showing you how to convert a number between 0 and 99 (input) into two numbers that represent the digits in the decimal representation.
CodePudding user response:
"Two 4 bit 0-9" is traditionally called binary-coded decimal.
Replace:
PORTD = counter;
With:
PORTD = (counter / 10) << 4 | (counter % 10);
// 10s digit ^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^ 1s digit
CodePudding user response:
if(Button1 flank detected)
{
counter ;
}
if(Button2 flank detected)
{
counter--;
}
left = (counter / 10) << 4;
right = counter % 10;
out = (left | right);
PORTD = out;