I have just started playing around with 7-segment led displays.
My objective is to display a voltage of 0 to 5 presented to one of the analogue inputs (Arduino Uno) to a reading of 0 to 99 on a dual digit display. In my experiments to sort out the basics I am using two common-cathode display elements.
I am copying hereunder what I have got so far in the way of code (parts cribbed from what I have found on this forum – thank you). In the set-up procedure the program correctly steps through (and displays) the numbers 0 to 99, so the “void setSegments(byte digit)” part of the code (as also the hardware) seems to be working okay.
It correctly displays 00 when the A0 pin is grounded, and the first digit (‘tens’) steps from 0 to 1 to 2 as I increase the voltage. For the rest I get gibberish (both ‘tens’ and ‘units’). I suspect the line “int displayValue = sensorValue*99/1024” is the source of the trouble.
Can someone here please point me in the right direction.
// --a--
// f | | b
// |--g--|
// e | | c
// --d-- O h
// define the pins connected to the segments
#define segment_a 3
#define segment_b 4
#define segment_c 5
#define segment_d 6
#define segment_e 7
#define segment_f 8
#define segment_g 9
#define segment_h 10
//define the common sink pins
#define sink_1 11 // enables 1st digit
#define sink_2 12 // enables 2nd digit
int digit;
byte segmentPin[] = {
segment_a, segment_b, segment_c, segment_d, segment_e, segment_f, segment_g, segment_h};
byte segmentPattern_1[] = {
0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f, 0x80, 0x40};
void setup()
{
pinMode (segment_a, OUTPUT);
pinMode (segment_b, OUTPUT);
pinMode (segment_c, OUTPUT);
pinMode (segment_d, OUTPUT);
pinMode (segment_e, OUTPUT);
pinMode (segment_f, OUTPUT);
pinMode (segment_g, OUTPUT);
pinMode (segment_h, OUTPUT);
pinMode (sink_1, OUTPUT);
pinMode (sink_2, OUTPUT);
//counts from 00 to 99 and calls for display the two digits after each increment
for(int i=0; i<100; i++){
for(int j=0; j<10; j++){
digit = i/10; //determines value of 'tens' digit
digitalWrite(sink_1,HIGH);
digitalWrite(sink_2,LOW);
setSegments(digit);
delay (5);
digit = i - digit*10; //determines value of 'units' digit
digitalWrite(sink_1,LOW);
digitalWrite(sink_2,HIGH);
setSegments(digit);
delay (5);
}
}
}
void loop ()
{
int sensorValue = analogRead(A0);
int displayValue = sensorValue*99/1024;
//display sensed value
for(int j=0; j<50; j++){
digit = displayValue/10; //determines value of 'tens' digit
digitalWrite(sink_1,HIGH);
digitalWrite(sink_2,LOW);
setSegments(digit);
delay (5);
digit = displayValue - displayValue*10; //determines value of 'units' digit
digitalWrite(sink_1,LOW);
digitalWrite(sink_2,HIGH);
setSegments(digit);
delay (5);
}
}
// setting the bits of the digit to be displayed
void setSegments(byte digit){
byte mask = 1;
for(int i=0; i<8; i++){
if((segmentPattern_1[digit] & mask) == 0) digitalWrite(segmentPin[i],LOW);
else digitalWrite(segmentPin[i],HIGH);
mask = mask <<1;
}
}