Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- 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:
- 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.
- */
- const int SENSOR_PIN = A0;
- const int NUM_READINGS = 10;
- float readings[NUM_READINGS]; // the readings from the sensor
- int index = 0; // the index of the current reading
- float total = 0; // the running total
- float average = 0; // the average
- float calibrationOffset = 0; // the calibration offset
- bool isCalibrated = false; // indicates if the sensor is calibrated
- void setup() {
- Serial.begin(9600);
- pinMode(SENSOR_PIN, INPUT);
- // initialize all the readings to 0
- for (int i = 0; i < NUM_READINGS; i++) {
- readings[i] = 0;
- }
- Serial.println("Enter a calibration offset (in degrees Celsius) and press Enter.");
- }
- void loop() {
- if (!isCalibrated) {
- readCalibrationOffset();
- } else {
- // subtract the last reading and add the current reading to the total
- total = total - readings[index];
- readings[index] = analogRead(SENSOR_PIN) * (5.0 / 1023.0);
- total = total + readings[index];
- // move to the next position in the array
- index = (index + 1) % NUM_READINGS;
- // calculate the average
- average = total / NUM_READINGS;
- // calculate the temperature in degrees Celsius
- float temperature = average * 100.0 + calibrationOffset;
- // print the temperature
- Serial.print("Temperature: ");
- Serial.print(temperature);
- Serial.println(" °C");
- // delay before reading from the sensor again
- delay(1000);
- }
- }
- void readCalibrationOffset() {
- if (Serial.available()) {
- float inputOffset = Serial.parseFloat();
- if (Serial.read() == '\n') {
- calibrationOffset = inputOffset;
- Serial.print("Calibration offset set to: ");
- Serial.print(calibrationOffset);
- Serial.println(" °C");
- isCalibrated = true;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement