DeaD_EyE icon

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

DeaD_EyE | PRO | 10/19/22 05:33:22 PM UTC | 0 ⭐ | 1434 👁️ | Never ⏰ | []
Python |

1.75 KB

|

None

|

0 👍

/

0 👎

class CurrentSensor:
    """
    Converts an analog current with a resistor to a scaled unit, which was read by an ADC.
 
    The maximum analog voltage is defined with the resistor.
    At 20mA, a voltage drop of 3.2V occurs across a 160 Ω resistor.
 
    The lower_unit and upper_unit is to scale the unit.
 
    The order of conversion:
      1) current out from sensor e.G: 4mA - 20mA
      2) resistor to have a voltage drop. U = R * I
      3) raw_value from ADC what the microcontroller reads
      4) calculatig the voltage from raw_value
      5) calculating the current from voltage
      6) normalized value 0-1 from current
      7) scaled unit from normalized value
    """
 
    def __init__(
        self,
        bits=12,
        lower_current=0.004,
        upper_current=0.02,
        ref_voltage=3.3,
        resistor=160,
        lower_unit=0,
        upper_unit=100,
    ):
        self.bits = bits
        self.lower_current = lower_current
        self.upper_current = upper_current
        self.ref_voltage = ref_voltage
        self.resistor = resistor
        self.lower_unit = lower_unit
        self.upper_unit = upper_unit
 
    @property
    def delta_current(self):
        return self.upper_current - self.lower_current
 
    @property
    def delta_unit(self):
        return self.upper_unit - self.lower_unit
 
    @property
    def increments(self):
        return 2**self.bits - 1
 
    def convert(self, raw_value) -> float:
        """
        Return a scaled unit
        """
        voltage = raw_value / self.increments * self.ref_voltage
        current = voltage / self.resistor
        norm = (current - self.lower_current) / self.delta_current
        return norm * self.delta_unit + self.lower_unit
 

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎