Skip to content

Commit 0894a02

Browse files
author
Martin Crossley
committed
display negative numbers in pio_seven_segment example
1 parent 4542b5a commit 0894a02

File tree

1 file changed

+16
-6
lines changed

1 file changed

+16
-6
lines changed

pio/seven_segment/pio_7_segment_library/7_segment_lib.c

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,24 +30,34 @@ static const uint8_t segments[] = {
3030
};
3131

3232

33-
// Simple example of how to convert a positive integer into a 32-bit word
34-
// representing up to four 7-segment digits. Could be extended to handle
35-
// negative numbers.
33+
// Simple example of how to convert an integer between -999 and 9999
34+
// into a 32-bit word representing up to four 7-segment digits.
35+
// Credit to @lurch for the code to handle negative numbers.
3636
//
3737
uint32_t int_to_seven_segment (int num) {
3838
uint32_t word = 0;
39-
if (num > 9999 || num < 0) {
39+
if (num < -999 || num > 9999) {
4040
// number out of range, display 'E' symbol
4141
// EDBGACF.
42-
word = 0b11011010
42+
word = 0b11011010;
4343
} else {
4444
if (num == 0) {
4545
word = segments[0];
4646
} else {
47-
for (int bitshift = 0; bitshift < 32 && num > 0; bitshift += 8) {
47+
bool negative = num < 0;
48+
if (negative) {
49+
num *= -1;
50+
}
51+
int bitshift;
52+
for (bitshift = 0; bitshift < 32 && num > 0; bitshift += 8) {
4853
word |= segments[num % 10] << bitshift;
4954
num /= 10;
5055
}
56+
if (negative) {
57+
// display '-' symbol
58+
// EDBGACF.
59+
word |= 0b00010000 << bitshift;
60+
}
5161
}
5262
}
5363
return word;

0 commit comments

Comments
 (0)