Search code examples
vhdlunsigneddivision

VHDL - Need some advice on division & multiplication


Fellow SO users,

I'm trying to calibrate a resistive humidity sensor that I'm reading values from the ADC. The ADC outputs an 8-bit value. I'm using a Vref value of 5V.

My first step in calibrating is to divide the number by 255 and multiply by the Vref value. Hence, calibrated value = (output / 255) * Vref.

Now, in VHDL, I've come across some VHDL code to divide two numbers. The one I have divides two unsigned numbers so that shouldn't be a problem. It is over here; VHDL divide two unsigned numbers

Now, in my VHDL file, I have the 8 bit ADC value (humidity) and I have defined two constants, max_val (11111111 = 255) and Vref (00000101 = 5) both as unsigned. I'm first converting humidity to an unsigned by using unsigned(humidity) and then passing this value and the max_num value into the division function. With the result, I'm multiplying it by Vref.

Now, my question is;

  1. Is this a good approach? I.e; the way I'm dividing and multiplying.
  2. How do I convert the unsigned value back into a std_logic_vector?

Kind regards.


Solution

    1. I think it should divided by 256? Or with 255 i think your result will almost similar (note that max distance is between 255/256 and 255/255: = 0.00390625). Result will be with fixed point number. Multiply by 5: shift right 2 = multiply by 4 then add with this number (A*5 = A*4 + A), your code should like:

      A_Multiply_4 <= A&"00";
      A_Multiply_5 <= A_Multiply_4 + A;

    2. To convert from unsigned to std_logic_vector (i remember it exist in std_logic_1164):

      slv_array <= std_logic_vector(unsigned_number);

    If you wanna divide by 255, i think you should divide your num by 256 and add a little number after shift:

    1/255 = 1/256 + 1/x

    with x = 2 power something. Shifter is the best way.

    I tried with 1/3 and have to pleasant with this method.

    P/s x = 2^16 and you got diff between 2 case is 5.9838388480392156862745098039216e-8. But i don't think number you want have more than 8 bit after point.