I didn't quite understand your difficulty, but see if the code below meets your needs.
/* Atmega 328 (Nano)
sensor type DS18B20
22/01/2024
*/
#include <Servo.h>
#include <OneWire.h>
#include <DallasTemperature.h>
const int SERVO_PIN = 5; // Arduino pin connected to Servo Motor's pin
const int SENSOR_PIN = 2; // Arduino pin connected to DS18B20 sensor's DATA pin
const float TEMPERATURE_THRESHOLD = 30; // °C 20
Servo servo; // create servo object to control a servo
OneWire oneWire(SENSOR_PIN); // setup a oneWire instance
DallasTemperature sensor(&oneWire); // pass oneWire to DallasTemperature library
float temperature;
float servoposraw;
float servopos;
void setup() {
Serial.begin(9600); // initialize serial
servo.attach(SERVO_PIN); // attaches the servo on pin 5 to the servo object, pin 5? servo.write(0);
servo.write(0);
sensor.begin(); // initialize the sensor
}
void loop() {
delay(1000);
sensor.requestTemperatures(); // send the command to get temperatures
temperature = sensor.getTempCByIndex(0); // read temperature in Celsius
if (temperature >= 10 and temperature <= 30) {
servoposraw = (180. / 60.) * temperature;
servopos = 180 - servoposraw;
servo.write(servopos);
Serial.println(servopos);
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print("°C => servo angle: ");
}
}