Scaling down a range of numbers in C

119 views Asked by At

I am reading values from a potentiometer that I can rotate to produce a range of numbers from 0-1023. I want to be able to display these numbers in terms of a horizontal bar graph on an LCD screen. The LCD screen is 20 blocks wide so the 0-1023 must be scaled down to 0-20. The character I want to use to produce the bar graph is a block that fills one entire block out of the 20 available. The bit pattern for this block is 0b11110001.

   block = 0b11110001; 
   BarGraph = ((DELVAL2/5115)*2000);

   lcd_putxy(2,0,buf);
   for (delay = 0; delay < 50000; delay++);      // introduce a delay 

   sprintf(buf, "*", BarGraph); 
   lcd_putxy(2,0,buf);

I was hoping somebody could explain to me how to achieve this and the best method for scaling down my potentiometer values.

2

There are 2 answers

1
Mazi On

Your calculation has mistake

 BarGraph = ((DELVAL2/5115)*2000);

DELVAL2 is 0-1023. You divide it by 5115, so you get value between 0 and 1. It's probably casted to 0. 0 Mutliplied by 2000 is still 0.

Try first multiply, then divide:

BarGraph = (DELVAL2*2000/5115);

Also for printing

 sprintf(buf, "*", BarGraph); 

will not work. Refer to sprintf function or simple use loop for putting symbol in buf array.

2
Brandon83 On

All you need to do is take the full range of the ADC and divide it by the number of LCD Characters (1024 / 20 = 51.2). Round the value up to 52 to include all possible values in the ADC Range. This means you have 20 available LCD characters to display a full range of 0 - 1023. Each LCD character will represent 0 to 52 ADC Counts (except the last one due to rounding).

Pseudo Code:

  • First, clear the display for a new update.
  • Check if ADC Counts >= 0 and ADC Counts <= 51: Turn 'ON' LCD Block 0.
  • Else if ADC Counts >= 52 and ADC Counts <=103: Turn 'ON' LCD Block 0 & 1.
  • Else if ADC Counts >=104 and ADC Counts <=155: Turn 'ON' LCD Block 0 & 1 & 2.

You would do this sort of pattern for all of the remaining 17 entries.

Cheers!