You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
1.7KB

  1. import machine
  2. class CSMS12:
  3. AirValue = 852 # Totally dry in air
  4. WaterValue = 374 # Totally wet in water
  5. Interval = 0
  6. SoilMoistureValue = 0
  7. def __init__(self, pin = 0):
  8. # Set up port for reading values
  9. self.Adc = machine.ADC(pin)
  10. # Calculate range of intervals for Wet/Okay Wet/Dry
  11. # This is based on the ranges of wet and dry values that I found by
  12. # having the sensor in water and by having it in dry air.
  13. self.Interval = (self.AirValue - self.WaterValue) / 3
  14. # Just a wrapper to read the value
  15. def getRawValue(self):
  16. return self.Adc.read()
  17. # Do the varying scale of the moisture for Capacinance readers
  18. def getScaledValue(self):
  19. scaledValue = 0
  20. rawValue = self.getRawValue()
  21. # Calculate percentage within the calibrated range
  22. scaledValue = (
  23. ((self.WaterValue - rawValue) * 100) / (self.WaterValue - self.AirValue)
  24. )
  25. # Make sure that we don't go out of range
  26. if scaledValue < 0:
  27. scaledValue = 0
  28. if scaledValue > 100:
  29. scaledValue = 100
  30. # Convert so 0% is completely dry and 100% is completely wet.
  31. return 100 - scaledValue
  32. # Get current interval of how wet the sensor is
  33. def getInterval(self):
  34. value = self.getScaledValue()
  35. if 75 <= value <= 100:
  36. return("Very Moist (Value: {}%)".format(value))
  37. elif 50 <= value <= 75:
  38. return("Quite Moist (Value: {}%)".format(value))
  39. elif 25 <= value <= 50:
  40. return("Kinda Dry (Value: {}%)".format(value))
  41. elif 0 <= value <= 25:
  42. return("Very Dry (Value: {}%)".format(value))