Go Down

Topic: Need some maths help please! (RESOLVED) (Read 700 times) previous topic - next topic


Apr 07, 2012, 03:59 pm Last Edit: Apr 07, 2012, 10:48 pm by BulletMagnet83 Reason: 1
This might sound pretty stupid, but I actually don't know WHAT to google to get a simple answer, so hopefully you guys can help me out :-) I bet it's one of those things that's really obvious once I know, but I'm hungover and my brain's not firing on all cylinders... hehe

Anyway, let's say I have a 4 digit number for example 1234. I want to split this up into thousands, hundreds, tens and units across 4 variables, ending up with each one holding a value of 0-9 so I can then push these out to my 7-segment module.

There MUST be a nice neat operation to do this, but hell if I can find it :-P Thanks in advance for the help!

EDIT: Here's the code I'm fiddling with, it should be apparent what I'm trying to accomplish.

Code: [Select]

int CLK = 10;
int SIN = 11;
int LAT = 12;

byte digitData[10] = {
 0x3F, 0x6, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x7, 0x7F, 0x67

// Array to hold segment patterns for digits 0 - 9

void setup () {
 pinMode(CLK, OUTPUT);
 pinMode(SIN, OUTPUT);
 pinMode(LAT, OUTPUT);

void loop () {
 while(1) {
unsigned long time = (millis() / 1000);

int D0 = time ?????????????

int D1 = time ?????????????

int D2 = time ?????????????

int D3 = time ?????????????

 digitalWrite(LAT, LOW);
 shiftOut(SIN, CLK, MSBFIRST, digitData[D0]);

 shiftOut(SIN, CLK, MSBFIRST, digitData[D1]);

 shiftOut(SIN, CLK, MSBFIRST, digitData[D2]);

 shiftOut(SIN, CLK, MSBFIRST, digitData[D3]);
 digitalWrite(LAT, HIGH);


I think you just need to use integer division and modulo division (remainder) like so:

Code: [Select]

int number = 1234;
int d1, d2, d3, d4;
int working;

d1 = number / 1000; // Gives 1 in this example
working = number % 1000; // Gives 234 in this example
d2 = working / 100; // Gives 2 in this example
working = working % 100; // Gives 34 in this example
d3 = working / 10; // Gives 3 in this example
d4 = working % 10; // Gives 4 in this example


That looks like exactly what I need! Thanks, I'll play with it now. I couldn't for the life of me figure out how to format the damn statements to do what I want.

Lifesaver!  8)


The search term is "AVR BCD conversion".
loved the 68000 assembler back then and now I have to deal with THIS 8 bit thingy


Noted for future reference, Marek. I really am amazed how much of a n00b I can be sometimes, I'm sure I've actually used that stuff in my old BASIC programming days  :smiley-roll:

Anyway, code works now... counting up like a beauty :D

Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131