Wednesday, May 27, 2015

Splitting numbers up

Using modulo

So we can display different numbers but how can we make a function to display a certain number?  To do this we are going to use an operator called modulo which select the remainder of a number after a division.
Our new function will have two parts, one to split up the number and another to display the digits.  To select each digit separately we are going to use a combination of modulo and division.  Modulo 10 will give us a number between 0 and 9 since this is the largest any remainder can be.  We will use this to get a number for a single column.  The function will be called show and it will take one parameter, an int called num.


  int unit = num % 10;
  int tens = (num / 10) % 10;
  int hundreds = (num / 100) % 10;
  int thousands = (num / 1000) % 10;


If we use the number 3456 as an example you can see how this code works.
For units 3456 % 10 = 6, since there is a remainder of 6
For tens 3456 / 10 = 345, remember there is no decimal with integer division.
345 % 10 = 5
This is repeated twice more with the divisor increasing by a factor of 10.

We do the modulo on the thousands column too so we can handle numbers larger than 9999.  This will display the last 4 digits so 10000 will be 0000.

Show numbers


In this part of the function we turn on each segment one by one with the correct value.  The delay time is 1250us so that the entire function takes 5ms to run.  This will be useful when we try and make a timer.


To test our new function we can call our function in the loop.
void loop(){

This should display the number 4321.  The wiring is the same as before

No comments:

Post a Comment