Sensible … it’s not how I’d have done it but I picked up on bits and bytes early and I was a math head in school.
You have 10 digits,0 to 9, and each has a 4-bit pattern.
0000 = 0
0001
0010
0011
0100
0101
0110
0111
1000
1001 = 9
byte x = 5; // bit pattern is 00000101, in BCD it is 05
A byte is 8 bits, it can hold 2 4 bit patterns.
Once you have the byte, you write it to a Port you have wired up and the bits take care of themselves. You do not have to unpack bits to write to each pin one at a time.
x = x << 4; // moves the bits up 4 bit-places,pattern is now 01010000
// << is the left-shift operator, it moves bits in an integer ‘up’.
// >> is the right-shift operator, it moves bits down
// when I use these shift operators I almost always want to use unsigned variables to avoid sign bit complications.
// Arduino unsigned variables you can shifts bits in are 8-bit byte, 16-bit word and 32-bit unsigned long.
// You CAN shift bits in signed variables, it’s just got one look-out because sign is the top bit.
x = x + 7; // add the next digit 0 to 9 that can only fill 4 bits, will always fit in the 4 empty bits the left-shift vacated
// bit pattern is now 01010111
Yes, that is only 2 digits. The Ports are only 8 bits wide. It will take doing twice, should not be a problem.
I won’t go into using a loop to pull the 4 RPM digits out and etc, etc, but someone may mention that’s the way to do it.
Instead, I’ll use some of your code with some added
byte writeToPort; // this is a global variable declared up top
… in void setup() you will need to mode 2 Ports into OUTPUT
… let’s get what 2 Ports on your Mega2560 you will use/wire to and give you the 4 lines of code for that
… we’ll be looking at the pin map. PortD pins are labeled PD0, PD1, … PD7 right on the pin map, not hard.
… and down in void loop() we have
// firstdigit = RPM % 10;
// seconddigit = RPM/10 %10;
// thirddigit = RPM/100 %10;
// fourthdigit = RPM/1000 %10; // you don’t need 4 variables for these
writeToPort = ( RPM / 1000 % 10 ) << 4;
writeToPort = writeToPort + ( RPM / 100 % 10 ); // now has the 2 high-order digits
PORTE = writeToPort; // now those 8 bits are on those 8 Port E pins; bang, done.
writeToPort = ( RPM / 10 % 10 ) << 4;
writeToPort = writeToPort + ( RPM % 10 ); // now has the 2 low-order digits
PORTD = writeToPort; // now those 8 bits are on those 8 Port D pins; bang, done.
And that’s it for getting the pins set.
Picking Ports and those setup() lines is for another post.
It is getting harder to search the site and get the right hits up top even knowing what I want but here’s Port Manipulation 101 for those who want. There’s a link to the Bit Math Tutorial there.
https://playground.arduino.cc/Learning/PortManipulation