Go Down

Topic: Beginner struggling with basic two-digit 7-segment led display (Read 2 times) previous topic - next topic


This line will be potValueMapped = map(analogRead(potPin), 0, 1023, 0, 99);

Thank you.  That did the trick!  As simple as that.

The loop section of my program now reads (I also had to fix a bug):

Code: [Select]
void loop ()
  int sensorValue = analogRead(A0);
  sensorValue = map (sensorValue, 0, 1023, 0, 99);

  //display sensed value
  for(int j=0; j<50; j++){
    digit = sensorValue/10;  //determines value of 'tens' digit
    delay (5);
    digit = sensorValue - digit*10;  //determines value of 'units' digit
    delay (5);

BTW, I also have a few shift registers and am planning to try them out.  Once I have done that I can decide which system will best suit my purpose.


There is a problem in this line:

Code: [Select]
int displayValue = sensorValue*99/1024;

The * and / will be evaluated in that order because they have equal precedence, and equal precedence operators are evaluated from left to right. However, the maximum value of sensorValue*99 is 1023*99 = 101277 which is too large to fit in an int. Try:

Code: [Select]
unsigned int displayValue = (unsigned int)(((unsigned long)sensorValue * 99UL)/1024U);

btw there is no need to make variable 'digit' global. It would be better programming style to declare it locally instead, and this would probably make the code smaller.

Thank you for your helpful comments. I was wondering about the order of operations.  I did try previously to change the order by bracketing but it didn't help.  You have now explained why.

I prefer American2020's solution.  The 'map' statement seems to have been designed exactly for this purpose.

You're right.  I have now declared the variable 'digit' locally and it reduced the sketch size from 2158 to 2090.

Go Up