 # Transfer function for PWM

I need to generate a PWM output in proportion to a voltage signal on A0 input. The input will vary from 1 to 5V and this needs to be converted to a proportionate PWM out. I calculated as below :

Maximum Counts (A0) : 1024 = 5V

Hence each Volt = 1024 / 5 = 205 counts

1 to 5V will correspond to 205 to 1024 Counts

205 Counts = 0 PWMValue ( PWMV)

1024 Counts = 255 PWMV

Or each count = (255-0) / ( 1024-205) = 0.311 PWMV

Transfer Function for PWMV = (Input Count – 205) x 0.311

Finally the above calculation involves a int and float whereas the range for PWMV is a byte.

Can I cast the Input Count to a float() before the final calculation and then again cast the result PWMV to a byte() ? Will it work?

I need to generate a PWM output in proportion to a voltage signal on A0 input.

Does the input voltage range from 1 to 5 volts (a 4 volt range) or from 0 to 5V (a 5 volt range)

Can you not just divide the input value by 4 (or 5) and use it as the PWM value ?

UKHeliBob: Does the input voltage range from 1 to 5 volts (a 4 volt range) or from 0 to 5V (a 5 volt range)

Can you not just divide the input value by 4 (or 5) and use it as the PWM value ?

Correct. My range is 1 to 5V so I need to divide by 4. But this will entail a loss of precision as the value will change only once every 4 input counts....

Or is this something that cannot be avoided as the PWM value is a byte ??

( Actually I am getting a 4-20mA input signal from the user and converting it into a Voltage signal using a 250 Ohm resistor. Maybe I now need to work out what will be the minimum mA step that the PWM will respond to ??

Or is this something that cannot be avoided as the PWM value is a byte ??

Correct. You cannot get more than 255 discrete steps of PWM output when the value is held in a byte.

UKHeliBob:
Correct. You cannot get more than 255 discrete steps of PWM output when the value is held in a byte.

OK got it. For a moment was wondering if a finer resolution can be achieved by some other means but then realised for a 4-20mA span covering 819 counts on A0 pin each count is about 16/819 = 0.0195 mA !! And four counts will be 4 x 0.0195 = 0.078 mA.

No the user will be able to use even this precision so I think I will simply divide by 4 and get going.

Thanks for the help !