I am trying to make a temperature sensor activate a servo motor. More or less, I want to be able to have it turn 180 degrees when the temperature gets to a certain point. Also, once the temperature falls below that level it goes back to 0.
I have been trying my best to learn and piece together some other projects but not having a lot of luck. I am able to get the temp sensor working by itself and the servo by itself but can't get the two to work together.
Currently the code I am trying to use is just showing from my understanding 0 at 50 degrees and 180 at 80 degrees. although I really want it to be any temp greater than 80F degrees 180 anything lower than 80 degrees would be 0.
Any help would be greatly appreciated because I am struggling a lot.
I am using a DS18B20 temp sensor & a SG90 servo with an Arduino Nano
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Servo.h>
const int SENSOR_PIN = 4; // Arduino pin connected to DS18B20 sensor's DQ pin
Servo mainServo;
int position = 0;
int previousPosition;
OneWire oneWire(SENSOR_PIN); // setup a oneWire instance
DallasTemperature tempSensor(&oneWire); // pass oneWire to DallasTemperature library
float tempCelsius; // temperature in Celsius
float tempFahrenheit; // temperature in Fahrenheit
void setup()
{
Serial.begin(9600); // initialize serial
tempSensor.begin(); // initialize the sensor
mainServo.attach(3);
Serial.begin(9600);
}
void loop()
{
tempSensor.requestTemperatures(); // send the command to get temperatures
tempCelsius = tempSensor.getTempCByIndex(0); // read temperature in Celsius
tempFahrenheit = tempCelsius * 9 / 5 + 32; // convert Celsius to Fahrenheit
Serial.print("Temperature: ");
Serial.print(tempCelsius); // print the temperature in Celsius
Serial.print("°C");
Serial.print(" ~ "); // separator between Celsius and Fahrenheit
Serial.print(tempFahrenheit); // print the temperature in Fahrenheit
Serial.println("°F");
delay(500);
int position = map(tempFahrenheit, 50, 80, 0, 180);
Serial.println(position);
if(previousPosition != position){
mainServo.write(position);
delay(1000);
}}