Advertisement
DeaD_EyE

sensor (4-20mA) on an ADC with resistor -> scaled unit

Oct 19th, 2022
910
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.75 KB | None | 0 0
  1. class CurrentSensor:
  2.     """
  3.    Converts an analog current with a resistor to a scaled unit, which was read by an ADC.
  4.  
  5.    The maximum analog voltage is defined with the resistor.
  6.    At 20mA, a voltage drop of 3.2V occurs across a 160 Ω resistor.
  7.  
  8.    The lower_unit and upper_unit is to scale the unit.
  9.  
  10.    The order of conversion:
  11.      1) current out from sensor e.G: 4mA - 20mA
  12.      2) resistor to have a voltage drop. U = R * I
  13.      3) raw_value from ADC what the microcontroller reads
  14.      4) calculatig the voltage from raw_value
  15.      5) calculating the current from voltage
  16.      6) normalized value 0-1 from current
  17.      7) scaled unit from normalized value
  18.    """
  19.  
  20.     def __init__(
  21.         self,
  22.         bits=12,
  23.         lower_current=0.004,
  24.         upper_current=0.02,
  25.         ref_voltage=3.3,
  26.         resistor=160,
  27.         lower_unit=0,
  28.         upper_unit=100,
  29.     ):
  30.         self.bits = bits
  31.         self.lower_current = lower_current
  32.         self.upper_current = upper_current
  33.         self.ref_voltage = ref_voltage
  34.         self.resistor = resistor
  35.         self.lower_unit = lower_unit
  36.         self.upper_unit = upper_unit
  37.  
  38.     @property
  39.     def delta_current(self):
  40.         return self.upper_current - self.lower_current
  41.  
  42.     @property
  43.     def delta_unit(self):
  44.         return self.upper_unit - self.lower_unit
  45.  
  46.     @property
  47.     def increments(self):
  48.         return 2**self.bits - 1
  49.  
  50.     def convert(self, raw_value) -> float:
  51.         """
  52.        Return a scaled unit
  53.        """
  54.         voltage = raw_value / self.increments * self.ref_voltage
  55.         current = voltage / self.resistor
  56.         norm = (current - self.lower_current) / self.delta_current
  57.         return norm * self.delta_unit + self.lower_unit
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement