#include <OneWire.h>
#include <DallasTemperature.h>
// Define the pin connected to the DS18B20 sensor
const int oneWireBus = 2;
// Setup a OneWire instance and pass it to DallasTemperature
OneWire oneWire(oneWireBus);
DallasTemperature sensors(&oneWire);
void setup() {
Serial.begin(115200);
sensors.begin(); // Initialize the DS18B20 sensor
}
void loop() {
sensors.requestTemperatures(); // Request temperature
float temperatureC = sensors.getTempCByIndex(0);
Serial.print("Temperature: ");
Serial.print(temperatureC);
Serial.println(" °C");
delay(1000); // Read temperature every second
}
#include <math.h> // For the log() function
const float BETA = 3950; // Beta coefficient of the thermistor
const int analogPin = 34; // ESP32 ADC pin
void setup() {
Serial.begin(115200); // Start serial monitor at 115200 baud
}
void loop() {
// Read the analog value (0-4095 range for ESP32)
int analogValue = analogRead(analogPin);
// Temperature calculation (adjusted for ESP32 ADC range)
float celsius = 1 / (log(1 / (4095.0 / analogValue - 1)) / BETA
+ 1.0 / 298.15) - 273.15;
// Output temperature to the serial monitor
Serial.print("Temperature: ");
Serial.print(celsius);
Serial.println(" ℃");
delay(1000); // Wait 1 second before reading again
}
// --- Configuration Constants ---
const int pwmPin = 13;
const int frequency = 5000;
const uint8_t resolution = 8; // 0-255 range
const uint32_t dutyCycle = 128; // ~50% for 8-bit
// ========================== SETUP ==========================
void setup() {
Serial.begin(115200); // Optional: for debug messages
Serial.println("ESP32 Fixed PWM Example (Pin-Based API)");
// 1. Configure and attach the PWM pin using LEDC
ledcAttach(pwmPin, frequency, resolution);
Serial.printf("Attached PWM to GPIO %d\n", pwmPin);
// 2. Set the fixed PWM duty cycle using ledcWrite with the PIN number
ledcWrite(pwmPin, dutyCycle); // Using pwmPin here
Serial.printf("Set fixed duty cycle %u on pin %d\n", dutyCycle,
pwmPin);
}
// ========================== LOOP ==========================
void loop() {
// PWM is handled by hardware. Nothing needed here for fixed output.
delay(1000);
}
Loading
ds18b20
ds18b20