#include <OneWire.h>
#include <DallasTemperature.h>
#include <TimerOne.h>
#define ONE_WIRE_BUS 2
#define BUFFER_SIZE 10
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
float buffer[BUFFER_SIZE];
volatile int head = 0;
volatile int tail = 0;
volatile int count = 0;
// Overflow counter
volatile int overflowCount = 0;
unsigned long lastSend = 0;
void setup() {
Serial.begin(9600);
sensors.begin();
Timer1.initialize(200000); // Interrupt setiap 200 ms
Timer1.attachInterrupt(readTemperatureISR);
Serial.println("System started...");
}
void loop() {
unsigned long now = millis();
// Simulasi sistem sibuk: buffer terus penuh
if (now > 5000 && now < 12000) {
// Tampilkan pesan full SECEPAT mungkin
if (overflowCount > 0) {
Serial.println("BUFFER FULL");
overflowCount--; // kurangi, sehingga muncul sering
}
return;
}
// Saat tidak sibuk, juga tampilkan overflow yg tersisa
if (overflowCount > 0) {
Serial.println("BUFFER FULL");
overflowCount--;
}
// Kirim data tiap 1 detik
if (now - lastSend >= 1000) {
lastSend = now;
if (count == 0) {
Serial.println("Buffer empty");
} else {
noInterrupts();
while (count > 0) {
float value = buffer[tail];
tail = (tail + 1) % BUFFER_SIZE;
count--;
interrupts();
Serial.println(value);
noInterrupts();
}
interrupts();
}
}
}
void readTemperatureISR() {
sensors.requestTemperatures();
float tempC = sensors.getTempCByIndex(0);
if (count < BUFFER_SIZE) {
buffer[head] = tempC;
head = (head + 1) % BUFFER_SIZE;
count++;
} else {
overflowCount++; // Tambah counter setiap overflow
}
}
Loading
ds18b20
ds18b20