#include <mutex>
#define BITS 10
#define ADC_RES 4095
const byte thermalPin = 34;
const byte cdsPin = 32;
float cdsVal, tempVal = 0;
typedef struct sensorStruct {
byte pin;
float value;
} Sensor_t;
QueueHandle_t queue;
std::mutex cdsMutex;
std::mutex tempMutex;
std::mutex queueMutex;
float temperature(uint16_t adc, float T0 = 25.0, uint16_t R0 = 10000, float beta = 3950.0) {
T0 += 273.15;
float r = (adc * R0) / (ADC_RES - adc);
return 1 / (1 / T0 + 1 / beta * log(r / R0)) - 273.15;
}
void taskQueueProcessing(void* pvParam) {
Sensor_t data;
while (1) {
xQueueReceive(queue, &data, portMAX_DELAY);
switch (data.pin) {
case cdsPin:
{
std::lock_guard<std::mutex> lock(cdsMutex);
cdsVal = data.value;
}
break;
case thermalPin:
{
std::lock_guard<std::mutex> lock(tempMutex);
tempVal = data.value;
}
break;
}
}
}
void taskCds(void* pvParam) {
int adc = 0;
Sensor_t cds;
cds.pin = cdsPin;
while (1) {
adc = analogRead(cdsPin);
cds.value = (float)adc;
{
std::lock_guard<std::mutex> lock(queueMutex);
xQueueSend(queue, &cds, portMAX_DELAY);
}
vTaskDelay(pdMS_TO_TICKS(250));
}
}
void taskTemp(void* pvParam) {
uint16_t adc = 0;
Sensor_t thermal;
thermal.pin = thermalPin;
while (1) {
adc = analogRead(thermalPin);
thermal.value = temperature(adc);
{
std::lock_guard<std::mutex> lock(queueMutex);
xQueueSend(queue, &thermal, portMAX_DELAY);
}
vTaskDelay(pdMS_TO_TICKS(250));
}
}
void setup() {
Serial.begin(115200);
analogSetAttenuation(ADC_11db);
analogSetWidth(BITS);
queue = xQueueCreate(10, sizeof(Sensor_t));
if (queue == NULL) {
Serial.println("~");
return;
}
xTaskCreate(taskCds, "Cds task", 1500, NULL, 1, NULL);
xTaskCreate(taskTemp, "thermal task", 1500, NULL, 1, NULL);
xTaskCreate(taskQueueProcessing, "display task", 1500, NULL, 1, NULL);
}
void loop() {
{
std::lock_guard<std::mutex> lock(cdsMutex);
Serial.print("CDS 值: ");
Serial.println(cdsVal);
}
{
std::lock_guard<std::mutex> lock(tempMutex);
Serial.print("Temperature: ");
Serial.print(tempVal);
Serial.println(" ℃");
}
delay(1000);
}