PIC - 4-20mA (Duty cycle formula)
Given your one data point, that 818 gives you 4V, I can apply some detective work and surmise that you are using the PWM in 10-bit mode and your supply / PWM reference voltage is 5V. 



Edit: That means that the output voltage after low-pass filtering is 

Vout = Vref * count/1024

so count must be 1024 * Vout/Vref. 

Count for 4V (20mA full scale @ 300cm in) is 819. 

Count for 0.8V (4mA minimum scale @ 12cm in) is 164. 



Edit: So start by determining the multiplier for the 'gain'- change in count for change in input cm. We call the change in input or output of an instrument from one extreme to the other the 'span'. Since this is linear we can ignore the zero intercept for now and calculate the slope- we'll add or subtract a number later to get the 'zero' right. 

The span of your output voltage must be 4-0.8V = 3.2V for an input change of (300-12) = 288cm, which corresponds to a count span of 819 (at 20mA out or 300cm in) - 164 (at 4mA out or 12cm in) = 655 counts. 

(You had 818 corresponding to 654 counts which might be because your 5V Vref is a touch higher than 5V).  

So the multiplier must be 654 or 655 divided by the input change 288 = 2.274. 

Now correct the zero intercept: 

At 12cm you desire an output voltage of 0.8V, or a count of 164. If we multiply 12 * 2.274 we get 27 counts, which is short of the desired 164 counts by 137 counts, so add 137 to the result. 

So, if x is the number of cm, you must multiply it by 654/288 = 137/144 (or 655/288 with exact 5V Vref) and add 137. 

12 cm would thus give you 164 counts for 0.802V and 300cm would give you 818 counts for 3.994V (or 819 for 3.999V).

Note that 16 bit integer multiplication is inadequate to multiply 137 x 300 without overflow, but if you're using floating point, no problem.