Сотворил измеритель-регулятор температуры кузнечного газового горна с управлением по wi-FI и сигнализацией по телеграмм. Всё работает идеально. Для подключения термопары применил ADS1115. А вот управлять электрической муфельной печью не получается.
Проблемы с ШИМ. Не получается даже простые скетчи примеров открыть. В чём может быть проблема? IDE слишком новый для моей платы ESP32 divkid? Или там что то простое. Если кто решится помочь - скопирую ругательные ответы компилятора.
С “новосельем” Вас. Я как то лет пять назад начинал было Ардуино осваивать. Потом забросил. А теперь вот. Понадобилось. Если кому интересно - могу показать код.
Не «если», а «с этого нужно было начинать».
Так вопрос как бы не к моему коду относится. А к тому, которого ещё нету. Если только для… попробую разобраться как правильно вставить код.
#include <WiFi.h>
# include <Wire.h> /// SDA 21; SCL 22
#include "DHT.h"
#include <WebServer.h>
#include <WiFiClientSecure.h> //26
#include <UniversalTelegramBot.h> //26
#include <LCDI2C_Multilingual.h>
#include <Adafruit_ADS1X15.h>
LCDI2C_Generic lcd(0x27, 16, 2); // I2C address: 0x27; Display size: 16x2
IPAddress local_IP(192, 168, 1, 100);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
IPAddress primaryDNS(192, 168, 1, 1); // Primary DNS (optional)
IPAddress secondaryDNS(0, 0, 0, 0); // Secondary DNS (optional)
const char ssid[] = "ZTE46508";
const char password[] = "04112008";
const char hostname[] = "ESP32"; //26
#define DHTTYPE DHT22 //DHT dht(3, AM2301); //Как вариант
WebServer server(80);
#define BOTtoken "7888463419:AAHguxxft92waCOdbahw_s4yTy9NXoSLZrY"
#define CHAT_ID "5838389687"
WiFiClientSecure client; //26
UniversalTelegramBot bot(BOTtoken, client); //26
Adafruit_ADS1115 ads; // Use this for the 16-bit version 28_12
/*const float tha[165] = {3542, 3559, 3596, 3656, 3738, 3842, 3965, 4109, 4270, 4450, // Термопара Хромель - Алюмель
4646, 4859, 5087, 5331, 5589, 5862, 6148, 6446, 6757, 7080,
7413, 7757, 8111, 8473, 8844, 9222, 9608, 10000, 10397, 10798,
11203, 11612, 12023, 12436, 12851, 13267, 13682, 14096, 14509,
14920, 15328, 15735, 16138, 16540, 16941, 17340, 17739, 18138,
18539, 18940, 19343, 19747, 20153, 20561, 20971, 21382, 21795,
22209, 22624, 23040, 23457, 23874, 24293, 24713, 25133, 25554,
25975, 26397, 26820, 27243, 27667, 28091, 28516, 28941, 29366,
29792, 30218, 30644, 31071, 31497, 31924, 32350, 32776, 33203,
33629, 34055, 34480, 34905, 35330, 35755, 36179, 36602, 37025,
37447, 37869, 38289, 38710, 39129, 39548, 39965, 40382, 40798,
41213, 41628, 42041, 42453, 42865, 43275, 43685, 44093, 44501,
44908, 45313, 45718, 46121, 46524, 46925, 47326, 47725, 48124,
48522, 48918, 49314, 49708, 50101, 50494, 50885, 51276, 51665,
52053, 52440, 52826, 53211, 53595, 53978, 54359, 54740, 55119,
55497, 55873, 56249, 56623, 56995, 57367, 57737, 58105, 58473,
58838, 59202, 59565, 59926, 60286, 60644, 61000, 61355, 61708,
62060, 62410, 62759, 63106, 63451, 69795, 64138, 64479, 64819 };*/
const float tha[165] = { 1300, 1400, 1500, 1600, 1700, 1800, 1904, 2110, 2341, // Железо - константан
2598, 2878, 3179, 3501, 3841, 4199, 4574, 4964, 5368,
5785, 6215, 6656, 7108, 7569, 8040, 8519, 9005, 9499,
10000, 10507, 11019, 11536, 12058, 12585, 13315, 13649,
14186, 14725, 15268, 15812, 16359, 16907, 17457, 18008,
18560, 19113, 19667, 20222, 20777, 21332, 21887, 22442,
22998, 23553, 24108, 24663, 25217, 25771, 26325, 26879,
27432, 27984, 28537, 29029, 29640, 30192, 30743, 31295,
31846, 32397, 32949, 33501, 34054, 34607, 35161, 35716,
36272, 36829, 37388, 37949, 38511, 39075, 39642, 40210,
40782, 41356, 41933, 42513, 43096, 43683, 44273, 44867,
45464, 46066, 46671, 47280, 47893, 48510, 49130, 49754,
50382, 51013, 51647, 52283, 52922, 53563, 54207, 54852,
55498, 56144, 56790, 57434, 58076, 58716, 59354, 59989,
50621, 51249, 51875, 62496, 63145, 63729, 64341, 64948,
65553, 66155, 66753, 67349, 67942, 68533, 69121, 69708,
70293, 70876, 71459, 72039, 72619, 73199, 73777, 74355,
74933, 75510, 76087, 76644, 77240, 77815, 78390, 78964,
79536, 80000, 81000, 82000, 83000, 84000, 85000, 86000,
87000, 88000, 89000, 90000, 91000, 92000, 93000, 94000,
95000, 96000, };
const float thk[23] = {-1.27, -0.6, 0, 0.65, 1.31, 1.98, 2.66, 3.35, // (k - 10 000) / 1000 ////
4.05, 4.76, 5.48, 6.21, 6.95, 7.69, 8.43, 9.18,
9.93, 10.69, 11.46, 12.24, 13.03, 13.84, 14.66};
int i;
int j;
unsigned int x;
float tma;
float tmk;
float tempF;
float z;
float f; // 26
float r; // 29
float pta;
float ptk;
float Temperature;
float Humidity;
float tim;
float timer;
float timet;
uint8_t Relepin = 15;
bool Relestatus = LOW;
uint8_t Timkapin = 18;
bool Timkastatus = LOW;
uint8_t LED1pin = 4;
bool LED1status = LOW;
uint8_t LED2pin = 5;
bool LED2status = LOW;
uint8_t LED3pin = 2;
bool LED3status = LOW;
uint8_t DHTPin = 0;
DHT dht(DHTPin, DHTTYPE); // Initialize DHT sensor.
void setup() {
z = 22; //Предустановка температуры DHT22
r = 50; // Предустановка термопары
tim = 59; // Предустановка времени для таймера и Телеграмма
timet = 52; //52 это пока не сотворил таймер. А вообще это текущие показания этого таймера
timer = 55; // Мусор какой то
pinMode(Relepin, OUTPUT);
pinMode(Timkapin, OUTPUT); // Пищалка по таймеру
pinMode(DHTPin, INPUT);
pinMode(LED1pin, OUTPUT);
pinMode(LED2pin, OUTPUT);
pinMode(LED3pin, OUTPUT);
bool LED1status = LOW; // 26
bool LED2status = LOW; //26
bool LED3status = LOW;
bool Relestatus = LOW;
bool Timkastatus = LOW;
client.setCACert(TELEGRAM_CERTIFICATE_ROOT); //26
WiFi.mode(WIFI_STA);
WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS);
WiFi.hostname(hostname);
WiFi.begin(ssid, password);
Serial.begin(115200);
if (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial.println("WiFi Failed!");
while(true) yield();}
Serial.print("IP Address: "); Serial.println(WiFi.localIP());
delay(100);
server.on("/", handle_OnConnect);
server.on("/led1on", handle_led1on);
server.on("/led1off", handle_led1off);
server.on("/led2on", handle_led2on);
server.on("/led2off", handle_led2off);
server.on("/constant", HTTP_GET, handle_constant);
server.on("/rele", HTTP_GET, handle_rele); //29
server.on("/timer", HTTP_GET, handle_timer); //29
server.onNotFound(handle_NotFound);
server.begin();
Serial.println("HTTP server started");
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print(" TEMPERATURA *C ");
lcd.setCursor(0, 1);
lcd.println("TFC / THK / DHT"); //Железо - константан //lcd.println("THA / THK / LM35"); // Хромель - алюмель
delay(3000);
ads.setGain(GAIN_SIXTEEN); // 16x gain +/- 0.256V 1 bit = 0.125mV 0.0078125mV
if (!ads.begin()) {
Serial.println("Failed to initialize ADS.");
while (1);}
delay(1000);
}
void handle_OnConnect() {
Serial.println( Temperature); //На тестах раскоментить
LED1status = LOW;
LED2status = LOW;
LED3status = LOW;
Relestatus = LOW;
Timkastatus = LOW; //29
Serial.println("GPIO4 Status: OFF | GPIO5 Status: OFF");
server.send(200, "text/html", SendHTML(LED1status,LED2status)); }
void handle_led1on() {LED1status = HIGH;
Serial.println("GPIO4 Status: ON");
server.send(200, "text/html", SendHTML(true,LED2status)); }
void handle_led1off() {LED1status = LOW;
Serial.println("GPIO4 Status: OFF");
server.send(200, "text/html", SendHTML(false,LED2status)); }
void handle_led2on() {LED2status = HIGH;
Serial.println("GPIO5 Status: ON");
server.send(200, "text/html", SendHTML(LED1status,true)); }
void handle_led2off() {LED2status = LOW;
Serial.println("GPIO5 Status: OFF");
server.send(200, "text/html", SendHTML(LED1status,false)); }
void handle_constant() {String temperature = server.arg("temperature");
Serial.println(temperature);
z = (temperature.toFloat());
Serial.print("z = "); Serial.println(z);
server.send(200, "text/html", SendHTML(LED1status,false)); }
void handle_rele() {String relet = server.arg("relet"); // 29
Serial.println(relet); //
r = (relet.toFloat()); //
Serial.print("r = "); Serial.println(r); //
server.send(200, "text/html", SendHTML(LED2status,false)); } ///
void handle_timer() {String timet = server.arg("timet"); // 29
Serial.println(timet); //
tim = (timet.toFloat()); //
Serial.print("tim = "); Serial.println(tim); //
server.send(200, "text/html", SendHTML(LED2status,false)); } ///
void handle_NotFound(){server.send(404, "text/plain", "Not found");}
void loop() {
float multiplier = 0.0078125F; // ADS1115 @ +/- 6.144V gain (16-bit results)
float h = dht.readHumidity();//+++++++++++++++++++++++
float t = dht.readTemperature();
Serial.print("DHT = "); Serial.println(t);
delay(100);
// tma = 17000; //Для АЛЮМЕЛИ
tma = ((ads.readADC_Differential_2_3()) * (multiplier) * 1000 + 10000);
Serial.print("tma = "); Serial.println(tma);
for (i=0; i <= 164; i = i + 1) {
if (tha[i] > tma) break; }
i = i - 1;
float gda = tha[i];
float tda = ((i) * 10);
Serial.print("tda = "); Serial.println(tda);
Serial.print("gda = "); Serial.println(gda);
i = i + 1;
float gpa = tha[i];
float tpa = ((i) * 10);
Serial.print("tpa = "); Serial.println(tpa);
Serial.print("gpa = "); Serial.println(gpa);
float (ppa) = ((tma) - (gda)) / (((gpa) - (gda)) / 10) + (tda);
Serial.print("ppa = "); Serial.println(ppa);
pta = ((ppa) - 270 + (t));
Serial.print("pta = "); Serial.println(pta);
delay(100);
//tmk = 8.00; //Для КОПЕЛИ
tmk = ((ads.readADC_Differential_0_1()) * (multiplier));
Serial.print("tmk = "); Serial.println(tmk);
for (j=0; j <= 22; j = j + 1) {
if (thk[j] > tmk) break; }
j = j - 1;
float gdk = thk[j];
float tdk = (((j) * 10) - 20);
Serial.print("tdk = "); Serial.println(tdk);
Serial.print("gdk = "); Serial.println(gdk);
j = j + 1;
float gpk = thk[j];
float tpk = (((j) * 10) - 20);
Serial.print("tpk = "); Serial.println(tpk);
Serial.print("gpk = "); Serial.println(gpk);
ptk = ((tmk) - (gdk)) / (((gpk) - (gdk)) / 10) + (tdk) -1 + (t);
Serial.print("ptk = "); Serial.println(ptk);
delay(100);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("FC="); // lcd.print("TA="); //Для Хромель - Алюмель
lcd.print(pta);
lcd.setCursor(0, 1);
lcd.print("TK=");
lcd.print(ptk);
lcd.setCursor(12, 0);
lcd.print(t);
lcd.setCursor(12, 1);
lcd.print(h);
delay(500); ///26
server.handleClient();
Temperature = dht.readTemperature(); // Gets the values of the temperature //26d
Humidity = dht.readHumidity(); // Gets the values // int f = “z”.toInt()
if(Temperature > (z)) {
String message = "Temperature and Humidity!\n"; //Можно было и удалить
message += "Current temperature: " + String(Temperature, 1) + " °C ";
message += "Current humidate: " + String(Humidity, 1) + " %";
bot.sendMessage(CHAT_ID, message, "");
digitalWrite(LED3pin, HIGH);
delay(2000); }
digitalWrite(LED3pin, LOW);
Serial.println(Temperature);
Serial.print("z = "); Serial.println(z);
Serial.println(Humidity);// не выбрасывать! это для отладки
if(pta > (r)) {
String message = "ALARMA!\n"; //Можно было и удалить
message += "Temperature alumely: " + String(pta, 1) + " °C ";
bot.sendMessage(CHAT_ID, message, "");
digitalWrite(Relepin, HIGH);
delay(2000); }
digitalWrite(Relepin, LOW);
Serial.println(Temperature);
Serial.print("r = "); Serial.println(r);
delay(100); ///26
if(timet > (tim)) {
String message = "ALARMA!\n"; //Можно было и удалить
message += "Taimer: " + String(timet, 1) + " Min ";
bot.sendMessage(CHAT_ID, message, "");
digitalWrite(Timkapin, HIGH);
delay(2000); }
digitalWrite(Timkapin, LOW);
Serial.println(timet);
Serial.print("tim = "); Serial.println(tim);
delay(100); ///26
if(LED1status) {
digitalWrite(LED1pin, HIGH);}
else {digitalWrite(LED1pin, LOW);}
if(LED2status) {
digitalWrite(LED2pin, HIGH);}
else {digitalWrite(LED2pin, LOW);}
delay(500); ///26
}
String SendHTML(uint8_t led1stat, uint8_t led2stat) {
String ptr = "<!DOCTYPE html> <html>\n";
ptr += "<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\">\n";
ptr += "<title>ESP32 Weather Report</title>\n";
ptr += "<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}\n";
ptr += "body{margin-top: 0;} h1 {color: #444444;margin: 10px auto 10px;}\n";
ptr += "h3 {color: #444444;margin-bottom: 5px;}\n";
ptr += "button {height: 36px;}\n";
ptr += ".button {display: block;width: 80px;background-color: #3498db;border: none;color: white;padding: 13px 30px;text-decoration: none;font-size: 25px;margin: 0px auto 35px;cursor: pointer;border-radius: 4px;}\n";
ptr += ".button-on {background-color: #3498db;}\n";
ptr += ".button-off {background-color: #34495e;}\n";
ptr += ".button-led-1 {background-color: #4b5320;}\n";
ptr += "input {height: 30px;}\n";
ptr += ".button-off:active {background-color: #2c3e50;}\n";
ptr += "p {font-size: 14px;color: #888;margin-bottom: 10px;}\n";
ptr += "</style>\n";
ptr += "</head>\n";
ptr += "<body>\n";
ptr += "<script>setTimeout(function(){window.location.reload();}, 20000);</script>\n"; // Обновление сайтика 20 секунд
ptr += "<h1>ESP32 Web Server</h1>\n"; // Отображается на страничке Заголовок
ptr += "<h2>Temperature: " + String(Temperature) + " °C</h2>\n"; // Отображается на страничке от DHT
ptr += "<h2>Humidity: " + String(Humidity) + " %</h2>\n"; // Отображается на страничке oт DHT
ptr += "<h2>Termopara(A): " + String(pta) + " °C</h2>\n"; // Отображается на страничке oт ТХА
ptr += "<h2>Termopara(K): " + String(ptk) + " °C</h2>\n"; // Отображается на страничке от ТХК
ptr += "<h2>Taimer: " + String(timet) + " min</h2>\n"; // Отображается на страничке Таймер
ptr += "<hr />\n";
ptr += "<h3>Ulica: " + String(z) + "</h3>\n";
ptr += "<div><form action=\"/constant\" method=\"GET\"><input name=\"temperature\"><button type=\"submit\">Submit</button></form></div>\n"; //задатчик температуры DHT
ptr += "<h3>Termopara: " + String(r) + "</h3>\n";
ptr += "<div><form action=\"/rele\" method=\"GET\"><input name=\"relet\"><button type=\"submit\">Submit</button></form></div>\n"; //задатчик температуры на термопаре ТХА
ptr += "<h3>Taimer: " + String(tim) + "</h3>\n";
ptr += "<div><form action=\"/timer\" method=\"GET\"><input name=\"timet\"><button type=\"submit\">Submit</button></form></div>\n"; // Задатчик таймера
if (led1stat) {
ptr += "<p>LED1 Status: ON</p><a class=\"button button-off\" href=\"/led1off\">OFF</a>\n";}
else {ptr += "<p>LED1 Status: OFF</p><a class=\"button button-on button-led-1\" href=\"/led1on\">ON</a>\n";}
if (led2stat) {ptr += "<p>LED2 Status: ON</p><a class=\"button button-off\" href=\"/led2off\">OFF</a>\n";}
else { ptr += "<p>LED2 Status: OFF</p><a class=\"button button-on\" href=\"/led2on\">ON</a>\n"; }
ptr += "</body>\n";
ptr += "</html>\n";
return ptr;}
А фото экрана планшета со страничкой сайта по этому коду как пристроить?
А где pwm?
Я же говорил, что в этом коде его нету. Он здесь и не нужен.
ШИМ пробовал на “чистом листе”. Вот ответ ошибки на попытку компиляции кода из примера, зашитого в IDE
C:\Temp.arduinoIDE-unsaved202508-9052-bsqlaw.2xnb8\sketch_jan8a\sketch_jan8a.ino: In function ‘void setup()’:
C:\Temp.arduinoIDE-unsaved202508-9052-bsqlaw.2xnb8\sketch_jan8a\sketch_jan8a.ino:11:3: error: ‘ledcSetup’ was not declared in this scope
11 | ledcSetup(ledChannel, freq, resolution);
| ^~~~~~~~~
C:\Temp.arduinoIDE-unsaved202508-9052-bsqlaw.2xnb8\sketch_jan8a\sketch_jan8a.ino:14:3: error: ‘ledcAttachPin’ was not declared in this scope; did you mean ‘ledcAttach’?
14 | ledcAttachPin(ledPin, ledChannel);
| ^~~~~~~~~~~~~
| ledcAttach
exit status 1
Compilation error: ‘ledcSetup’ was not declared in this scope
Зачем тогда вываливать код, в котором не нужен неработающий pwm?
Так я же предупреждал! Недопоняли друг друга. Виноват.
Удалить?
Как правило показывают код, по которому задан вопрос.
Если считаете, что разработка достойна внимания общественности - создайте пост в “Проектах”, где и код запостите и описание.
Это пример старого ядра. У тебя скорее всего уже новое. Как правильно управлять ШИМ светодиода можно прочитать здесь.
https://espressif-docs.readthedocs-hosted.com/projects/arduino-esp32/en/latest/api/ledc.html?highlight=leds
Там и примеры работающие есть.
Или поставить старое ядро Arduino ESP32.
Спасибо большое. Помогло!
Откат версии платы в IDE до версии 2.0.17 решил проблему.
А я по наивности думал, что всё новое - лучшее. (Кроме вина, конечно же).
3.0.4
#define soundpin 38
void setup() {
Serial.begin(115200);
delay(1000);
Serial.println("Buzzer Start");
//ledcAttach(soundpin,NOTE_A,7); //ledcAttach(uint8_tpin,uint32_tfreq,uint8_tresolution); for ESP core V3
ledcAttachChannel(soundpin,32000,8, 1);
delay(250);
ledcWriteNote(soundpin,NOTE_C, 4); // PIN, frequency, octave for ESP core V3
delay(250);
ledcWriteNote(soundpin,NOTE_D, 4); // PIN, frequency, octave for ESP core V3
delay(250);
ledcWriteNote(soundpin,NOTE_F, 4); // PIN, frequency, octave for ESP core V3
delay(250);
ledcWriteNote(soundpin,NOTE_C, 4); // PIN, frequency, octave for ESP core V3
delay(250);
ledcWriteNote(soundpin,NOTE_D, 4); // PIN, frequency, octave for ESP core V3
delay(500);
ledcWriteNote(soundpin,NOTE_C, 4); // PIN, frequency, octave for ESP core V3
delay(500);
ledcWrite(soundpin,0); // No sound
ledcDetach(soundpin);
Serial.println("Buzzer Stop");
}
void loop() {
}
В данном случае дело не в ухудшении, а в изменении работы некоторых функций ядра. Например, в ядре 3.х наконец появилась функция analogWrite()
а ещё tone()