// ตัวอย่าง การเขียนโปรแกรมบอร์ด Multi Function - Arduino uno r3
// MFB LAB29 DS18B20 F - Multiple DS18B20 & SSD1306 OLED
// ครูวิบูลย์ กัมปนาวราวรรณ ศุกร์ 5 กรกฏาคม 2567
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <OneWire.h>
#include <DallasTemperature.h>
// Define the dimensions of the OLED display
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
// Define the OLED reset pin
#define OLED_RESET -1
// Create an instance of the Adafruit_SSD1306 class
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
// Connect DS18B20 to Arduino pin D2
const byte ONE_WIRE_BUS = 2;
// Setup a OneWire instance to communicate with any OneWire devices
OneWire oneWire(ONE_WIRE_BUS);
// Pass our OneWire reference to Dallas Temperature sensor
DallasTemperature sensors(&oneWire);
byte numDevices = 0;
// Initialization of sensor and serial communication
void setup() {
Serial.begin(115200);
Serial.println("Reading Multiple DS18B20 sensors");
// Initialize the display
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x64
Serial.println(F("SSD1306 allocation failed"));
for (;;);
}
display.display();
delay(2000); // Pause for 2 seconds
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
sensors.begin();
byte address[8];
while (oneWire.search(address)) {
Serial.print("Bus index=");
Serial.print(numDevices);
Serial.print("; Device address=");
for (byte i = 0; i < 8; i++) {
Serial.print(address[i], HEX);
Serial.print(" ");
}
Serial.println();
numDevices++;
}
}
void loop() {
if (numDevices > 0) {
sensors.requestTemperatures();
display.clearDisplay();
// Display the header
display.setCursor(0, 0);
display.print("Temperature:");
for (byte i = 0; i < numDevices; i++) {
float temperatureCelsius = sensors.getTempCByIndex(i);
Serial.print("Bus index=");
Serial.print(i);
Serial.print("; Temperature=");
Serial.print(temperatureCelsius);
Serial.println("°C");
// Display each sensor's temperature on a new line
display.setCursor(0, 16 + (i * 16)); // Adjust cursor position for each sensor
display.print("Sensor ");
display.print(i + 1);
display.print(": ");
display.print(temperatureCelsius, 2); // Display temperature with 2 decimal places
display.print((char)247); // Display the degree symbol
display.print("C");
}
display.display(); // Update the display with the new data
}
delay(2000); // Delay for 2 seconds before the next reading
}