Advertisement
microrobotics

LM35 Temperature Sensor

Mar 30th, 2023 (edited)
986
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. The LM35 is an analog temperature sensor that outputs a voltage proportional to the temperature in degrees Celsius. Here's an example code in Arduino that reads the temperature from the sensor:
  3.  
  4. Note: This code assumes that the LM35 sensor is connected to pin A0 of the Arduino board. If you're using a different pin, you'll need to modify the SENSOR_PIN definition accordingly. Also, the LM35 outputs a voltage of 10 mV per degree Celsius, so the voltage is multiplied by 100 to convert it to degrees Celsius.
  5. */
  6.  
  7. const int SENSOR_PIN = A0;
  8. const int NUM_READINGS = 10;
  9. float readings[NUM_READINGS];  // the readings from the sensor
  10. int index = 0;  // the index of the current reading
  11. float total = 0;  // the running total
  12. float average = 0;  // the average
  13. float calibrationOffset = 0;  // the calibration offset
  14. bool isCalibrated = false;  // indicates if the sensor is calibrated
  15.  
  16. void setup() {
  17.   Serial.begin(9600);
  18.   pinMode(SENSOR_PIN, INPUT);
  19.  
  20.   // initialize all the readings to 0
  21.   for (int i = 0; i < NUM_READINGS; i++) {
  22.     readings[i] = 0;
  23.   }
  24.  
  25.   Serial.println("Enter a calibration offset (in degrees Celsius) and press Enter.");
  26. }
  27.  
  28. void loop() {
  29.   if (!isCalibrated) {
  30.     readCalibrationOffset();
  31.   } else {
  32.     // subtract the last reading and add the current reading to the total
  33.     total = total - readings[index];
  34.     readings[index] = analogRead(SENSOR_PIN) * (5.0 / 1023.0);
  35.     total = total + readings[index];
  36.  
  37.     // move to the next position in the array
  38.     index = (index + 1) % NUM_READINGS;
  39.  
  40.     // calculate the average
  41.     average = total / NUM_READINGS;
  42.  
  43.     // calculate the temperature in degrees Celsius
  44.     float temperature = average * 100.0 + calibrationOffset;
  45.  
  46.     // print the temperature
  47.     Serial.print("Temperature: ");
  48.     Serial.print(temperature);
  49.     Serial.println(" °C");
  50.  
  51.     // delay before reading from the sensor again
  52.     delay(1000);
  53.   }
  54. }
  55.  
  56. void readCalibrationOffset() {
  57.   if (Serial.available()) {
  58.     float inputOffset = Serial.parseFloat();
  59.     if (Serial.read() == '\n') {
  60.       calibrationOffset = inputOffset;
  61.       Serial.print("Calibration offset set to: ");
  62.       Serial.print(calibrationOffset);
  63.       Serial.println(" °C");
  64.       isCalibrated = true;
  65.     }
  66.   }
  67. }
  68.  
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement