MegaLight - контроллер освещения на Arduino Mega 2560+W5100
Модератор: immortal
-
- Сообщения: 113
- Зарегистрирован: Пт июн 09, 2017 11:18 pm
- Благодарил (а): 17 раз
- Поблагодарили: 13 раз
Re: MegaLight - контроллер освещения на Arduino Mega 2560+W5
olehs Подскажите пожалуйста. Второй день бьюсь над проблемой интеграции DHT-22 датчика температуры и влажности в ваш ML2 контроллер (версия с загрузкой с карты). Проблема в том, что в коде датчика DH-T22 (с отправкой данных на МЖД), который вставляю в void loop() (вкладка SETUP) есть задержка для считывания данных delay(2000);. Так вот при такой задержке в цикле перестаёт работать управление, а при удаления задержки управление работает, но не считывается нормально показание датчика. Подскажите пожалуйста как сделать дополнительный void loop в void loop(). Пробовал через Thread, но что то не компелировалось, да и чувствую, что это не тот путь к решению данной проблемы.
-
- Сообщения: 1115
- Зарегистрирован: Вс июн 14, 2015 11:08 am
- Благодарил (а): 85 раз
- Поблагодарили: 342 раза
Re: MegaLight - контроллер освещения на Arduino Mega 2560+W5
MegaLight использует библиотеку TaskScheduler
Для своего цикла Вам нужно создать свой таск и назначить ему время выполнения раз в 2 секунды.
P.S. Можете скинуть мне скетч с Вашими изменениями - я попробую его поправить для работы с планировщиком
Для своего цикла Вам нужно создать свой таск и назначить ему время выполнения раз в 2 секунды.
P.S. Можете скинуть мне скетч с Вашими изменениями - я попробую его поправить для работы с планировщиком
-
- Сообщения: 113
- Зарегистрирован: Пт июн 09, 2017 11:18 pm
- Благодарил (а): 17 раз
- Поблагодарили: 13 раз
Re: MegaLight - контроллер освещения на Arduino Mega 2560+W5
Я пытаюсь вставить вот такой простой код для одного DHT датчика:
Пробовал ещё код с "вэб мордой":
, там вообше капец, "морда" не поднимается.
СпойлерПоказать
/*---------------- 1 часть ----------------*/
#include "DHT.h" //библиотека для работы с DHT
#include "SPI.h" //библиотека для работы с SPI
#include "Ethernet.h" //библиотека для работы с Ethernet
#define DHTPIN1 14 //Обозначаем номер пина, к которому подключен датчик
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xDD };//вводим mac адрес, обычно он такого вида, может отличаться
byte ip[] = { 192, 168, 21, 60 };
byte server[] = { 192, 168, 21, 80 };
EthernetClient client;
DHT dht1(DHTPIN1, DHT22); //инициируем датчик DHT
int old_temperature1=0;
int old_humidity1=0;
char buf[80];
// Функция отправки HTTP-запроса на сервер
void sendHTTPRequest() {
Serial.println(buf);
if (client.connect(server, 80)) {
Serial.println("OK");
client.println(buf);
client.println("Host: 192.168.21.80");
client.println();
delay(2000);
client.stop();
} else {
Serial.println("FAILED");
}
}
void setup() {
Ethernet.begin (mac, ip);//запускаем сервер с указанными ранее MAC и вашим IP
Serial.begin (57200);
dht1. begin();
}
void loop()
{
delay(1000); // задержка в 1 сек.
// SENSOR 1 --------------------------------------
//Считываем температуру
float current_temp1=0;
float t1 = dht1.readTemperature(); //Считываем температуру в переменную "t"
{
current_temp1 = t1; // получаем температуру
Serial.println(current_temp1);
if ((old_temperature1!=(int)current_temp1)) {
int temp1 = (current_temp1 - (int)current_temp1) * 100; // выделяем дробную часть
sprintf(buf, "GET /objects/?object=DHTsensor1&op=m&m=temp1&&t=%0d.%d HTTP/1.0", (int)current_temp1, abs(temp1));
sendHTTPRequest();
}
old_temperature1=(int)current_temp1;
}
//Считываем влажность
float current_hum1=0;
float h1 = dht1.readHumidity(); //Считываем температуру в переменную "t"
{
current_hum1 = h1; // получаем влажность
Serial.println(current_hum1);
if ((old_humidity1!=(int)current_hum1)) {
int hum1 = (current_hum1 - (int)current_hum1) * 100; // выделяем дробную часть
sprintf(buf, "GET /objects/?object=DHTsensor1&op=m&m=hum1&&t=%0d.%d HTTP/1.0", (int)current_hum1, abs(hum1));
sendHTTPRequest();
}
old_humidity1=(int)current_hum1;
}
delay(2000); // задержка в 2 сек.
}
#include "DHT.h" //библиотека для работы с DHT
#include "SPI.h" //библиотека для работы с SPI
#include "Ethernet.h" //библиотека для работы с Ethernet
#define DHTPIN1 14 //Обозначаем номер пина, к которому подключен датчик
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xDD };//вводим mac адрес, обычно он такого вида, может отличаться
byte ip[] = { 192, 168, 21, 60 };
byte server[] = { 192, 168, 21, 80 };
EthernetClient client;
DHT dht1(DHTPIN1, DHT22); //инициируем датчик DHT
int old_temperature1=0;
int old_humidity1=0;
char buf[80];
// Функция отправки HTTP-запроса на сервер
void sendHTTPRequest() {
Serial.println(buf);
if (client.connect(server, 80)) {
Serial.println("OK");
client.println(buf);
client.println("Host: 192.168.21.80");
client.println();
delay(2000);
client.stop();
} else {
Serial.println("FAILED");
}
}
void setup() {
Ethernet.begin (mac, ip);//запускаем сервер с указанными ранее MAC и вашим IP
Serial.begin (57200);
dht1. begin();
}
void loop()
{
delay(1000); // задержка в 1 сек.
// SENSOR 1 --------------------------------------
//Считываем температуру
float current_temp1=0;
float t1 = dht1.readTemperature(); //Считываем температуру в переменную "t"
{
current_temp1 = t1; // получаем температуру
Serial.println(current_temp1);
if ((old_temperature1!=(int)current_temp1)) {
int temp1 = (current_temp1 - (int)current_temp1) * 100; // выделяем дробную часть
sprintf(buf, "GET /objects/?object=DHTsensor1&op=m&m=temp1&&t=%0d.%d HTTP/1.0", (int)current_temp1, abs(temp1));
sendHTTPRequest();
}
old_temperature1=(int)current_temp1;
}
//Считываем влажность
float current_hum1=0;
float h1 = dht1.readHumidity(); //Считываем температуру в переменную "t"
{
current_hum1 = h1; // получаем влажность
Serial.println(current_hum1);
if ((old_humidity1!=(int)current_hum1)) {
int hum1 = (current_hum1 - (int)current_hum1) * 100; // выделяем дробную часть
sprintf(buf, "GET /objects/?object=DHTsensor1&op=m&m=hum1&&t=%0d.%d HTTP/1.0", (int)current_hum1, abs(hum1));
sendHTTPRequest();
}
old_humidity1=(int)current_hum1;
}
delay(2000); // задержка в 2 сек.
}
СпойлерПоказать
#include "DHT.h" //библиотека для работы с DHT
#include "SPI.h" //библиотека для работы с SPI
#include "Ethernet.h" //библиотека для работы с Ethernet
#define DHTTYPE DHT22 // DHT 22 (AM2302)
#define DHTPIN1 14 //Обозначаем номер пина, к которому подключен датчик
#define DHTPIN2 15
#define DHTPIN3 16
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x60 }; //вводим mac адрес
IPAddress ip(192, 168, 21, 60); //вводим любой IP
EthernetServer server(80); //инифиализация библиотеки Ethernet server library
EthernetClient client;
DHT dht1(DHTPIN1, DHT22); //инициируем датчик DHT
DHT dht2(DHTPIN2, DHT22);
DHT dht3(DHTPIN3, DHT22);
void setup() {
Ethernet.begin (mac, ip);//запускаем сервер с указанными ранее MAC и вашим IP
Serial.begin (57600);
server. begin();
dht1. begin();
dht2. begin();
dht3. begin();
}
void loop() {
float t1 = dht1.readTemperature(); //Считываем температуру в переменную "t"
float h1 = dht1.readHumidity(); //Считываем влажность в переменную "h"
delay(2000);
float t2 = dht2.readTemperature();
float h2 = dht2.readHumidity();
delay(2000);
float t3 = dht3.readTemperature();
float h3 = dht3.readHumidity();
delay(2000);
EthernetClient client = server.available();
{ //выводим HTML страницу
client. println ("HTTP/1.1 200 OK"); //заголовочная информация
client. println ("Content-Type: text/html");
client. println ("Connection: close");
client. println (); //Так должно быть
client. println ("<!DOCTYPE HTML>"); //HTML тип документа
client. println ("<html>"); //открытие тега HTML
client. println ("<head> "); //открытие тега Head
client. println ("<meta http-equiv='Content-Type' content='text/html ; charset=utf-8'/> ");
client. print ("<title>DHT Controller-1</title>"); //название страницы
client. println ("</head>"); //заголовочная информация
client. println ("<body>");
client. print ("<H1>DHT Controller-1</H1>"); //заголовк на странице
client. println ("<br>"); //перенос на след. строчку
client. println ("Tемпература1 = "); //Температура с DHT1
client. println (t1,1); //переменная температуры
client. println (" C");
client. println ("Влажность1 = "); //Влажность с DHT1
client. println (h1,1); //переменная влажности
client. println (" %");
client. println ("<br>");
client. println ("Tемпература2 = ");
client. println (t2,1);
client. println (" C");
client. println ("Влажность2 = ");
client. println (h2,1);
client. println (" %");
client. println ("<br>");
client. println ("Tемпература3 = ");
client. println (t3,1);
client. println (" C");
client. println ("Влажность3 = ");
client. println (h3,1);
client. println (" %");
client. println ("</body>");
client. println ("</html>"); //закрываем тег HTMLbreak;
client. stop(); //закрываем соеднение
}
}
#include "SPI.h" //библиотека для работы с SPI
#include "Ethernet.h" //библиотека для работы с Ethernet
#define DHTTYPE DHT22 // DHT 22 (AM2302)
#define DHTPIN1 14 //Обозначаем номер пина, к которому подключен датчик
#define DHTPIN2 15
#define DHTPIN3 16
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x60 }; //вводим mac адрес
IPAddress ip(192, 168, 21, 60); //вводим любой IP
EthernetServer server(80); //инифиализация библиотеки Ethernet server library
EthernetClient client;
DHT dht1(DHTPIN1, DHT22); //инициируем датчик DHT
DHT dht2(DHTPIN2, DHT22);
DHT dht3(DHTPIN3, DHT22);
void setup() {
Ethernet.begin (mac, ip);//запускаем сервер с указанными ранее MAC и вашим IP
Serial.begin (57600);
server. begin();
dht1. begin();
dht2. begin();
dht3. begin();
}
void loop() {
float t1 = dht1.readTemperature(); //Считываем температуру в переменную "t"
float h1 = dht1.readHumidity(); //Считываем влажность в переменную "h"
delay(2000);
float t2 = dht2.readTemperature();
float h2 = dht2.readHumidity();
delay(2000);
float t3 = dht3.readTemperature();
float h3 = dht3.readHumidity();
delay(2000);
EthernetClient client = server.available();
{ //выводим HTML страницу
client. println ("HTTP/1.1 200 OK"); //заголовочная информация
client. println ("Content-Type: text/html");
client. println ("Connection: close");
client. println (); //Так должно быть
client. println ("<!DOCTYPE HTML>"); //HTML тип документа
client. println ("<html>"); //открытие тега HTML
client. println ("<head> "); //открытие тега Head
client. println ("<meta http-equiv='Content-Type' content='text/html ; charset=utf-8'/> ");
client. print ("<title>DHT Controller-1</title>"); //название страницы
client. println ("</head>"); //заголовочная информация
client. println ("<body>");
client. print ("<H1>DHT Controller-1</H1>"); //заголовк на странице
client. println ("<br>"); //перенос на след. строчку
client. println ("Tемпература1 = "); //Температура с DHT1
client. println (t1,1); //переменная температуры
client. println (" C");
client. println ("Влажность1 = "); //Влажность с DHT1
client. println (h1,1); //переменная влажности
client. println (" %");
client. println ("<br>");
client. println ("Tемпература2 = ");
client. println (t2,1);
client. println (" C");
client. println ("Влажность2 = ");
client. println (h2,1);
client. println (" %");
client. println ("<br>");
client. println ("Tемпература3 = ");
client. println (t3,1);
client. println (" C");
client. println ("Влажность3 = ");
client. println (h3,1);
client. println (" %");
client. println ("</body>");
client. println ("</html>"); //закрываем тег HTMLbreak;
client. stop(); //закрываем соеднение
}
}
-
- Сообщения: 1115
- Зарегистрирован: Вс июн 14, 2015 11:08 am
- Благодарил (а): 85 раз
- Поблагодарили: 342 раза
Re: MegaLight - контроллер освещения на Arduino Mega 2560+W5
попробуйте так (вставить в setup.ino)
Кроме того в setup() нужно добавить
СпойлерПоказать
Код: Выделить всё
#include "DHT.h" //библиотека для работы с DHT
#define DHTPIN1 14 //Обозначаем номер пина, к которому подключен датчик
byte server[] = { 192, 168, 21, 80 };
DHT dht1(DHTPIN1, DHT22); //инициируем датчик DHT
Task tDHT(2000, TASK_FOREVER, &DHTloop, &runner);
int old_temperature1 = 0;
int old_humidity1 = 0;
char buf[80];
// Функция отправки HTTP-запроса на сервер
void sendHTTPRequest() {
Serial.println(buf);
if (client.connect(server, 80)) {
Serial.println("OK");
client.println(buf);
client.println("Host: 192.168.21.80");
client.println();
delay(2000);
client.stop();
} else {
Serial.println("FAILED");
}
}
void DHTloop()
{
// SENSOR 1 --------------------------------------
//Считываем температуру
float current_temp1 = 0;
float t1 = dht1.readTemperature(); //Считываем температуру в переменную "t"
{
current_temp1 = t1; // получаем температуру
Serial.println(current_temp1);
if ((old_temperature1 != (int)current_temp1)) {
int temp1 = (current_temp1 - (int)current_temp1) * 100; // выделяем дробную часть
sprintf(buf, "GET /objects/?object=DHTsensor1&op=m&m=temp1&&t=%0d.%d HTTP/1.0", (int)current_temp1, abs(temp1));
sendHTTPRequest();
}
old_temperature1 = (int)current_temp1;
}
//Считываем влажность
float current_hum1 = 0;
float h1 = dht1.readHumidity(); //Считываем температуру в переменную "t"
{
current_hum1 = h1; // получаем влажность
Serial.println(current_hum1);
if ((old_humidity1 != (int)current_hum1)) {
int hum1 = (current_hum1 - (int)current_hum1) * 100; // выделяем дробную часть
sprintf(buf, "GET /objects/?object=DHTsensor1&op=m&m=hum1&&t=%0d.%d HTTP/1.0", (int)current_hum1, abs(hum1));
sendHTTPRequest();
}
old_humidity1 = (int)current_hum1;
}
}
Код: Выделить всё
tDHT.enable();
runner.addTask(tDHT);
-
- Сообщения: 113
- Зарегистрирован: Пт июн 09, 2017 11:18 pm
- Благодарил (а): 17 раз
- Поблагодарили: 13 раз
Re: MegaLight - контроллер освещения на Arduino Mega 2560+W5
Ругается: 'tDHT' does not name a type
Без этих двух строк компилируется, но соответственно не работает датчик:
tDHT.enable();
runner.addTask(tDHT
Может я ни туда вставляю эти строки? Я кинул их тудаже, на вкладку setup.
Без этих двух строк компилируется, но соответственно не работает датчик:
tDHT.enable();
runner.addTask(tDHT
Может я ни туда вставляю эти строки? Я кинул их тудаже, на вкладку setup.
-
- Сообщения: 113
- Зарегистрирован: Пт июн 09, 2017 11:18 pm
- Благодарил (а): 17 раз
- Поблагодарили: 13 раз
Re: MegaLight - контроллер освещения на Arduino Mega 2560+W5
Я очень извиняюсь за глупые вопросы, не силён я в программировании, только изучаю. Я вставил эти строки в void setup()
опять ругается: 'tDHT' was not declared in this scope
Вот как сейчас выглядит вся страница setup вашего кода ML
опять ругается: 'tDHT' was not declared in this scope
Вот как сейчас выглядит вся страница setup вашего кода ML
СпойлерПоказать
#include <avr/wdt.h>
#include "DHT.h" //библиотека для работы с DHT
#define DHTPIN1 14 //Обозначаем номер пина, к которому подключен датчик
Scheduler runner;
Task t1(1, TASK_FOREVER, &buttonLoop, &runner);
Task t2(1, TASK_FOREVER, &relayLoop, &runner);
Task t3(1, TASK_FOREVER, &webLoop, &runner);
Task t4(1, TASK_FOREVER, &externalLoop, &runner);
void buttonLoop() {
inputList.check();
outputEM.processAllEvents();
}
void relayLoop() {
inputEM.processAllEvents();
outputList.check();
}
#define WBSIZE 1024
void webLoop()
{
char webBuffer[WBSIZE];
int buflen = WBSIZE;
webserver.processConnection(webBuffer, &buflen);
}
void externalLoop()
{
externalEM.processEvent();
}
bool loadConfig() {
const uint8_t CONFIG_LINE_LENGTH = 127;
// The open configuration file.
SDConfigFile cfg;
// Open the configuration file.
if (!cfg.begin(CONFIG_FILE, CONFIG_LINE_LENGTH)) {
Serialprint("Failed to open configuration file: %s\r\n", CONFIG_FILE);
return false;
}
// Read each setting from the file.
while (cfg.readNextSetting()) {
if (cfg.nameIs("mac")) {
parseBytes(cfg.getValue(), '-', mac, 6, 16);
Serial.print("MAC="); Serial.println(cfg.getValue());
} else if (cfg.nameIs("ip")) {
parseBytes(cfg.getValue(), '.', ip, 4, 10);
} else if (cfg.nameIs("mdHost")) {
mdHost = cfg.getValue();
} else if (cfg.nameIs("mdPort")) {
mdPort = cfg.getIntValue();
} else if (cfg.nameIs("mdAuth")) {
mdAuth = cfg.getValue();
}
}
// clean up
cfg.end();
return true;
}
bool setupSD() {
if (!SD.begin(4)) {
Serialprint("SD unavailable. Trying to load config from EEPROM.\r\n");
return false;
}
Serialprint("SD initialization done.\r\n");
return true;
}
void setupTasks()
{
t1.enable();
t2.enable();
t3.enable();
t4.enable();
runner.init();
runner.addTask(t1);
runner.addTask(t2);
runner.addTask(t3);
runner.addTask(t4);
}
int setupInputsSD() {
const uint8_t CONFIG_LINE_LENGTH = 127;
String configDir = F("/INPUTS");
File dir = SD.open(configDir);
if (!dir.isDirectory())
return 0;
inputList.clearInputs();
storageHeader.cntInputs = 0;
int sz = 0;
SDConfigFile cfg;
while (true) {
File inp = dir.openNextFile();
if (!inp)
break;
if (inp.isDirectory())
{
inp.close();
continue;
}
const char *id = inp.name();
inp.close();
ML2Input *b = new ML2Input(id);
// The open configuration file.
if (!cfg.begin(String(configDir + "/" + String(id)).c_str(), CONFIG_LINE_LENGTH)) {
Serialprint("Failed to open input file: %s\r\n", id);
delete b;
cfg.end();
continue;
}
// Read each setting from the file.
while (cfg.readNextSetting()) {
if (cfg.nameIs("pin")) {
b->setPin(cfg.getIntValue());
} else if (cfg.nameIs("pullup")) {
const char *pu = cfg.getValue();
if (!strcmp(pu, "intup"))
b->setPullup(InputPullup::IntPullup);
else if (!strcmp(pu, "extup"))
b->setPullup(InputPullup::ExtPullup);
else if (!strcmp(pu, "extdown"))
b->setPullup(InputPullup::PullDown);
} else if (cfg.nameIs("bounceint")) {
b->setBounceInterval(cfg.getIntValue());
} else if (cfg.nameIs("holdint")) {
b->setHoldInterval(cfg.getIntValue());
} else if (cfg.nameIs("repeat")) {
b->setRepeat(cfg.getBooleanValue());
} else if (cfg.nameIs("repeatint")) {
b->setRepeatInterval(cfg.getIntValue());
} else if (cfg.nameIs("dclickint")) {
b->setDoubleClickInterval(cfg.getIntValue());
} else if (cfg.nameIs("prevclick")) {
b->setPreventClick(cfg.getBooleanValue());
}
}
// clean up
cfg.end();
if (!inputList.addInput(b))
{
Serialprint("Failed to add input %s\r\n", id);
delete b;
}
else
{
Serialprint("Added input %s on pin %d\r\n", id, b->pin());
sz += saveInputEEPROM(b, storageHeader.addrInputs + sz);
storageHeader.cntInputs++;
}
}
dir.close();
return sz;
}
int setupOutputsSD() {
const uint8_t CONFIG_LINE_LENGTH = 127;
String configDir = F("/OUTPUTS");
File dir = SD.open(configDir);
if (!dir.isDirectory())
return 0;
outputList.clearOutputs();
storageHeader.cntOutputs = 0;
int sz = 0;
SDConfigFile cfg;
while (true) {
File inp = dir.openNextFile();
if (!inp)
break;
if (inp.isDirectory())
{
inp.close();
continue;
}
const char *id = inp.name();
inp.close();
ML2Output *b = new ML2Output(id);
// The open configuration file.
if (!cfg.begin(String(configDir + "/" + String(id)).c_str(), CONFIG_LINE_LENGTH)) {
Serialprint("Failed to open output file: %s\r\n", id);
delete b;
cfg.end();
continue;
}
// Read each setting from the file.
while (cfg.readNextSetting()) {
if (cfg.nameIs("pin")) {
b->setPin(cfg.getIntValue());
} else if (cfg.nameIs("pwm")) {
b->setPWM(cfg.getBooleanValue());
} else if (cfg.nameIs("invert")) {
b->setInvert(cfg.getBooleanValue());
} else if (cfg.nameIs("noreport")) {
b->setNoreport(cfg.getBooleanValue());
} else if (cfg.nameIs("on")) {
cfg.getBooleanValue() ? b->setOn() : b->setOff();
} else if (cfg.nameIs("value")) {
b->setValue(cfg.getIntValue());
} else if (cfg.nameIs("save")) {
const char *pu = cfg.getValue();
if (!strcmp(pu, "state"))
b->setSaveState(OutputStateSave::State);
else if (!strcmp(pu, "value"))
b->setSaveState(OutputStateSave::Value);
else if (!strcmp(pu, "both"))
b->setSaveState(OutputStateSave::StateAndValue);
}
}
// clean up
cfg.end();
if (!outputList.addOutput(b))
{
Serialprint("Failed to add output %s\r\n", id);
delete b;
}
else
{
Serialprint("Added output %s on pin %d\r\n", id, b->pin());
sz += saveOutputEEPROM(b, storageHeader.addrOutputs + sz);
storageHeader.cntOutputs++;
}
}
dir.close();
return sz;
}
int loadRulesFromFile(File &dir, String path) {
int sz = 0;
while (true) {
File entry = dir.openNextFile();
if (! entry) {
// no more files
break;
}
String npath = path + String("/") + entry.name();
if (entry.isDirectory()) {
sz += loadRulesFromFile(entry, npath);
entry.close();
continue;
}
entry.close();
ML2Rule *rule = ML2Rule::fromFile(npath);
if (rule) {
int s = saveRuleEEPROM(rule, storageHeader.addrRules);
sz += s;
storageHeader.addrRules += s;
storageHeader.cntRules++;
delete rule;
Serialprint("Loaded rule: %s\r\n", npath.c_str());
}
}
return sz;
}
int setupRulesSD() {
storageHeader.cntRules = 0;
File root = SD.open(RULES_PATH);
if (root) {
return loadRulesFromFile(root, "");
}
}
bool loadAllFromEEPROM() {
int addr = CONFIG_START;
int sz = loadConfigEEPROM(addr);
if (!sz)
return false;
addr += sz;
sz = loadHeaderEEPROM(addr);
addr += sz;
for (int i = 0; i < storageHeader.cntInputs; i++) {
ML2Input *input = new ML2Input("");
sz = loadInputEEPROM(input, addr);
if (inputList.addInput(input))
Serialprint("Added input %s on pin %d\r\n", input->ID, input->pin());
addr += sz;
}
for (int i = 0; i < storageHeader.cntOutputs; i++) {
ML2Output *output = new ML2Output("");
sz = loadOutputEEPROM(output, addr);
if (outputList.addOutput(output))
Serialprint("Added output %s on pin %d\r\n", output->ID, output->pin());
addr += sz;
}
for (int i = 0; i < storageHeader.cntRules; i++) {
ML2Rule *rule = new ML2Rule("");
sz = loadRuleEEPROM(rule, addr, true);
Serialprint("Added rule %s\r\n", rule->ID.c_str());
addr += sz;
delete rule;
}
return true;
}
int setupConfigSD() {
const uint8_t CONFIG_LINE_LENGTH = 127;
SDConfigFile cfg;
if (!cfg.begin(CONFIG_FILE, CONFIG_LINE_LENGTH)) {
Serialprint("Failed to open configuration file: %s\r\n", CONFIG_FILE);
return 0;
}
while (cfg.readNextSetting()) {
if (cfg.nameIs("mac")) {
parseBytes(cfg.getValue(), '-', mac, 6, 16);
Serial.print("MAC="); Serial.println(cfg.getValue());
} else if (cfg.nameIs("ip")) {
parseBytes(cfg.getValue(), '.', ip, 4, 10);
} else if (cfg.nameIs("mdHost")) {
mdHost = cfg.getValue();
} else if (cfg.nameIs("mdPort")) {
mdPort = cfg.getIntValue();
} else if (cfg.nameIs("mdAuth")) {
mdAuth = cfg.getValue();
}
}
// clean up
cfg.end();
return saveConfigEEPROM(CONFIG_START, false);
}
void saveAllToEEPROM() {
int sz = setupConfigSD();
if (!sz) {
Serialprint("Failed to store config\r\n");
return;
}
int addr = CONFIG_START + sz;
int addrHeader = addr;
addr += sizeof(storageHeader);
storageHeader.addrInputs = addr;
sz = setupInputsSD();
addr += sz;
Serialprint("Stored %d inputs (%d bytes)\r\n\r\n", storageHeader.cntInputs, sz);
storageHeader.addrOutputs = addr;
sz = setupOutputsSD();
addr += sz;
Serialprint("Stored %d outputs (%d bytes)\r\n\r\n", storageHeader.cntOutputs, sz);
storageHeader.addrRules = addr;
sz = setupRulesSD();
addr += sz;
Serialprint("Stored %d rules (%d bytes)\r\n\r\n", storageHeader.cntRules, sz);
saveHeaderEEPROM(addrHeader);
saveConfigEEPROM(CONFIG_START, true);
Serialprint("Stored config to EEPROM (%d bytes)\r\n\r\n", addr - CONFIG_START);
}
int freeRam () {
extern int __heap_start, *__brkval;
int v;
return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}
void setup() {
tDHT.enable();
runner.addTask(tDHT);
wdt_disable();
Serial.begin(115200);
Serialprint("Starting...\r\n");
if (setupSD()) {
saveAllToEEPROM();
} else {
loadAllFromEEPROM();
}
setupWeb();
setupEMs();
setupTasks();
Serialprint("Started (free RAM: %d)\r\n", freeRam());
wdt_enable(WDTO_4S);
}
void loop() {
wdt_reset();
runner.execute();
}
void reset() {
wdt_enable(WDTO_1S);
while (1);
}
byte server[] = { 192, 168, 21, 80 };
DHT dht1(DHTPIN1, DHT22); //инициируем датчик DHT
Task tDHT(2000, TASK_FOREVER, &DHTloop, &runner);
int old_temperature1 = 0;
int old_humidity1 = 0;
char buf[80];
// Функция отправки HTTP-запроса на сервер
void sendHTTPRequest() {
Serial.println(buf);
if (client.connect(server, 80)) {
Serial.println("OK");
client.println(buf);
client.println("Host: 192.168.21.80");
client.println();
delay(2000);
client.stop();
} else {
Serial.println("FAILED");
}
}
void DHTloop()
{
// SENSOR 1 --------------------------------------
//Считываем температуру
float current_temp1 = 0;
float t1 = dht1.readTemperature(); //Считываем температуру в переменную "t"
{
current_temp1 = t1; // получаем температуру
Serial.println(current_temp1);
if ((old_temperature1 != (int)current_temp1)) {
int temp1 = (current_temp1 - (int)current_temp1) * 100; // выделяем дробную часть
sprintf(buf, "GET /objects/?object=DHTsensor1&op=m&m=temp1&&t=%0d.%d HTTP/1.0", (int)current_temp1, abs(temp1));
sendHTTPRequest();
}
old_temperature1 = (int)current_temp1;
}
//Считываем влажность
float current_hum1 = 0;
float h1 = dht1.readHumidity(); //Считываем температуру в переменную "t"
{
current_hum1 = h1; // получаем влажность
Serial.println(current_hum1);
if ((old_humidity1 != (int)current_hum1)) {
int hum1 = (current_hum1 - (int)current_hum1) * 100; // выделяем дробную часть
sprintf(buf, "GET /objects/?object=DHTsensor1&op=m&m=hum1&&t=%0d.%d HTTP/1.0", (int)current_hum1, abs(hum1));
sendHTTPRequest();
}
old_humidity1 = (int)current_hum1;
}
}
#include "DHT.h" //библиотека для работы с DHT
#define DHTPIN1 14 //Обозначаем номер пина, к которому подключен датчик
Scheduler runner;
Task t1(1, TASK_FOREVER, &buttonLoop, &runner);
Task t2(1, TASK_FOREVER, &relayLoop, &runner);
Task t3(1, TASK_FOREVER, &webLoop, &runner);
Task t4(1, TASK_FOREVER, &externalLoop, &runner);
void buttonLoop() {
inputList.check();
outputEM.processAllEvents();
}
void relayLoop() {
inputEM.processAllEvents();
outputList.check();
}
#define WBSIZE 1024
void webLoop()
{
char webBuffer[WBSIZE];
int buflen = WBSIZE;
webserver.processConnection(webBuffer, &buflen);
}
void externalLoop()
{
externalEM.processEvent();
}
bool loadConfig() {
const uint8_t CONFIG_LINE_LENGTH = 127;
// The open configuration file.
SDConfigFile cfg;
// Open the configuration file.
if (!cfg.begin(CONFIG_FILE, CONFIG_LINE_LENGTH)) {
Serialprint("Failed to open configuration file: %s\r\n", CONFIG_FILE);
return false;
}
// Read each setting from the file.
while (cfg.readNextSetting()) {
if (cfg.nameIs("mac")) {
parseBytes(cfg.getValue(), '-', mac, 6, 16);
Serial.print("MAC="); Serial.println(cfg.getValue());
} else if (cfg.nameIs("ip")) {
parseBytes(cfg.getValue(), '.', ip, 4, 10);
} else if (cfg.nameIs("mdHost")) {
mdHost = cfg.getValue();
} else if (cfg.nameIs("mdPort")) {
mdPort = cfg.getIntValue();
} else if (cfg.nameIs("mdAuth")) {
mdAuth = cfg.getValue();
}
}
// clean up
cfg.end();
return true;
}
bool setupSD() {
if (!SD.begin(4)) {
Serialprint("SD unavailable. Trying to load config from EEPROM.\r\n");
return false;
}
Serialprint("SD initialization done.\r\n");
return true;
}
void setupTasks()
{
t1.enable();
t2.enable();
t3.enable();
t4.enable();
runner.init();
runner.addTask(t1);
runner.addTask(t2);
runner.addTask(t3);
runner.addTask(t4);
}
int setupInputsSD() {
const uint8_t CONFIG_LINE_LENGTH = 127;
String configDir = F("/INPUTS");
File dir = SD.open(configDir);
if (!dir.isDirectory())
return 0;
inputList.clearInputs();
storageHeader.cntInputs = 0;
int sz = 0;
SDConfigFile cfg;
while (true) {
File inp = dir.openNextFile();
if (!inp)
break;
if (inp.isDirectory())
{
inp.close();
continue;
}
const char *id = inp.name();
inp.close();
ML2Input *b = new ML2Input(id);
// The open configuration file.
if (!cfg.begin(String(configDir + "/" + String(id)).c_str(), CONFIG_LINE_LENGTH)) {
Serialprint("Failed to open input file: %s\r\n", id);
delete b;
cfg.end();
continue;
}
// Read each setting from the file.
while (cfg.readNextSetting()) {
if (cfg.nameIs("pin")) {
b->setPin(cfg.getIntValue());
} else if (cfg.nameIs("pullup")) {
const char *pu = cfg.getValue();
if (!strcmp(pu, "intup"))
b->setPullup(InputPullup::IntPullup);
else if (!strcmp(pu, "extup"))
b->setPullup(InputPullup::ExtPullup);
else if (!strcmp(pu, "extdown"))
b->setPullup(InputPullup::PullDown);
} else if (cfg.nameIs("bounceint")) {
b->setBounceInterval(cfg.getIntValue());
} else if (cfg.nameIs("holdint")) {
b->setHoldInterval(cfg.getIntValue());
} else if (cfg.nameIs("repeat")) {
b->setRepeat(cfg.getBooleanValue());
} else if (cfg.nameIs("repeatint")) {
b->setRepeatInterval(cfg.getIntValue());
} else if (cfg.nameIs("dclickint")) {
b->setDoubleClickInterval(cfg.getIntValue());
} else if (cfg.nameIs("prevclick")) {
b->setPreventClick(cfg.getBooleanValue());
}
}
// clean up
cfg.end();
if (!inputList.addInput(b))
{
Serialprint("Failed to add input %s\r\n", id);
delete b;
}
else
{
Serialprint("Added input %s on pin %d\r\n", id, b->pin());
sz += saveInputEEPROM(b, storageHeader.addrInputs + sz);
storageHeader.cntInputs++;
}
}
dir.close();
return sz;
}
int setupOutputsSD() {
const uint8_t CONFIG_LINE_LENGTH = 127;
String configDir = F("/OUTPUTS");
File dir = SD.open(configDir);
if (!dir.isDirectory())
return 0;
outputList.clearOutputs();
storageHeader.cntOutputs = 0;
int sz = 0;
SDConfigFile cfg;
while (true) {
File inp = dir.openNextFile();
if (!inp)
break;
if (inp.isDirectory())
{
inp.close();
continue;
}
const char *id = inp.name();
inp.close();
ML2Output *b = new ML2Output(id);
// The open configuration file.
if (!cfg.begin(String(configDir + "/" + String(id)).c_str(), CONFIG_LINE_LENGTH)) {
Serialprint("Failed to open output file: %s\r\n", id);
delete b;
cfg.end();
continue;
}
// Read each setting from the file.
while (cfg.readNextSetting()) {
if (cfg.nameIs("pin")) {
b->setPin(cfg.getIntValue());
} else if (cfg.nameIs("pwm")) {
b->setPWM(cfg.getBooleanValue());
} else if (cfg.nameIs("invert")) {
b->setInvert(cfg.getBooleanValue());
} else if (cfg.nameIs("noreport")) {
b->setNoreport(cfg.getBooleanValue());
} else if (cfg.nameIs("on")) {
cfg.getBooleanValue() ? b->setOn() : b->setOff();
} else if (cfg.nameIs("value")) {
b->setValue(cfg.getIntValue());
} else if (cfg.nameIs("save")) {
const char *pu = cfg.getValue();
if (!strcmp(pu, "state"))
b->setSaveState(OutputStateSave::State);
else if (!strcmp(pu, "value"))
b->setSaveState(OutputStateSave::Value);
else if (!strcmp(pu, "both"))
b->setSaveState(OutputStateSave::StateAndValue);
}
}
// clean up
cfg.end();
if (!outputList.addOutput(b))
{
Serialprint("Failed to add output %s\r\n", id);
delete b;
}
else
{
Serialprint("Added output %s on pin %d\r\n", id, b->pin());
sz += saveOutputEEPROM(b, storageHeader.addrOutputs + sz);
storageHeader.cntOutputs++;
}
}
dir.close();
return sz;
}
int loadRulesFromFile(File &dir, String path) {
int sz = 0;
while (true) {
File entry = dir.openNextFile();
if (! entry) {
// no more files
break;
}
String npath = path + String("/") + entry.name();
if (entry.isDirectory()) {
sz += loadRulesFromFile(entry, npath);
entry.close();
continue;
}
entry.close();
ML2Rule *rule = ML2Rule::fromFile(npath);
if (rule) {
int s = saveRuleEEPROM(rule, storageHeader.addrRules);
sz += s;
storageHeader.addrRules += s;
storageHeader.cntRules++;
delete rule;
Serialprint("Loaded rule: %s\r\n", npath.c_str());
}
}
return sz;
}
int setupRulesSD() {
storageHeader.cntRules = 0;
File root = SD.open(RULES_PATH);
if (root) {
return loadRulesFromFile(root, "");
}
}
bool loadAllFromEEPROM() {
int addr = CONFIG_START;
int sz = loadConfigEEPROM(addr);
if (!sz)
return false;
addr += sz;
sz = loadHeaderEEPROM(addr);
addr += sz;
for (int i = 0; i < storageHeader.cntInputs; i++) {
ML2Input *input = new ML2Input("");
sz = loadInputEEPROM(input, addr);
if (inputList.addInput(input))
Serialprint("Added input %s on pin %d\r\n", input->ID, input->pin());
addr += sz;
}
for (int i = 0; i < storageHeader.cntOutputs; i++) {
ML2Output *output = new ML2Output("");
sz = loadOutputEEPROM(output, addr);
if (outputList.addOutput(output))
Serialprint("Added output %s on pin %d\r\n", output->ID, output->pin());
addr += sz;
}
for (int i = 0; i < storageHeader.cntRules; i++) {
ML2Rule *rule = new ML2Rule("");
sz = loadRuleEEPROM(rule, addr, true);
Serialprint("Added rule %s\r\n", rule->ID.c_str());
addr += sz;
delete rule;
}
return true;
}
int setupConfigSD() {
const uint8_t CONFIG_LINE_LENGTH = 127;
SDConfigFile cfg;
if (!cfg.begin(CONFIG_FILE, CONFIG_LINE_LENGTH)) {
Serialprint("Failed to open configuration file: %s\r\n", CONFIG_FILE);
return 0;
}
while (cfg.readNextSetting()) {
if (cfg.nameIs("mac")) {
parseBytes(cfg.getValue(), '-', mac, 6, 16);
Serial.print("MAC="); Serial.println(cfg.getValue());
} else if (cfg.nameIs("ip")) {
parseBytes(cfg.getValue(), '.', ip, 4, 10);
} else if (cfg.nameIs("mdHost")) {
mdHost = cfg.getValue();
} else if (cfg.nameIs("mdPort")) {
mdPort = cfg.getIntValue();
} else if (cfg.nameIs("mdAuth")) {
mdAuth = cfg.getValue();
}
}
// clean up
cfg.end();
return saveConfigEEPROM(CONFIG_START, false);
}
void saveAllToEEPROM() {
int sz = setupConfigSD();
if (!sz) {
Serialprint("Failed to store config\r\n");
return;
}
int addr = CONFIG_START + sz;
int addrHeader = addr;
addr += sizeof(storageHeader);
storageHeader.addrInputs = addr;
sz = setupInputsSD();
addr += sz;
Serialprint("Stored %d inputs (%d bytes)\r\n\r\n", storageHeader.cntInputs, sz);
storageHeader.addrOutputs = addr;
sz = setupOutputsSD();
addr += sz;
Serialprint("Stored %d outputs (%d bytes)\r\n\r\n", storageHeader.cntOutputs, sz);
storageHeader.addrRules = addr;
sz = setupRulesSD();
addr += sz;
Serialprint("Stored %d rules (%d bytes)\r\n\r\n", storageHeader.cntRules, sz);
saveHeaderEEPROM(addrHeader);
saveConfigEEPROM(CONFIG_START, true);
Serialprint("Stored config to EEPROM (%d bytes)\r\n\r\n", addr - CONFIG_START);
}
int freeRam () {
extern int __heap_start, *__brkval;
int v;
return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}
void setup() {
tDHT.enable();
runner.addTask(tDHT);
wdt_disable();
Serial.begin(115200);
Serialprint("Starting...\r\n");
if (setupSD()) {
saveAllToEEPROM();
} else {
loadAllFromEEPROM();
}
setupWeb();
setupEMs();
setupTasks();
Serialprint("Started (free RAM: %d)\r\n", freeRam());
wdt_enable(WDTO_4S);
}
void loop() {
wdt_reset();
runner.execute();
}
void reset() {
wdt_enable(WDTO_1S);
while (1);
}
byte server[] = { 192, 168, 21, 80 };
DHT dht1(DHTPIN1, DHT22); //инициируем датчик DHT
Task tDHT(2000, TASK_FOREVER, &DHTloop, &runner);
int old_temperature1 = 0;
int old_humidity1 = 0;
char buf[80];
// Функция отправки HTTP-запроса на сервер
void sendHTTPRequest() {
Serial.println(buf);
if (client.connect(server, 80)) {
Serial.println("OK");
client.println(buf);
client.println("Host: 192.168.21.80");
client.println();
delay(2000);
client.stop();
} else {
Serial.println("FAILED");
}
}
void DHTloop()
{
// SENSOR 1 --------------------------------------
//Считываем температуру
float current_temp1 = 0;
float t1 = dht1.readTemperature(); //Считываем температуру в переменную "t"
{
current_temp1 = t1; // получаем температуру
Serial.println(current_temp1);
if ((old_temperature1 != (int)current_temp1)) {
int temp1 = (current_temp1 - (int)current_temp1) * 100; // выделяем дробную часть
sprintf(buf, "GET /objects/?object=DHTsensor1&op=m&m=temp1&&t=%0d.%d HTTP/1.0", (int)current_temp1, abs(temp1));
sendHTTPRequest();
}
old_temperature1 = (int)current_temp1;
}
//Считываем влажность
float current_hum1 = 0;
float h1 = dht1.readHumidity(); //Считываем температуру в переменную "t"
{
current_hum1 = h1; // получаем влажность
Serial.println(current_hum1);
if ((old_humidity1 != (int)current_hum1)) {
int hum1 = (current_hum1 - (int)current_hum1) * 100; // выделяем дробную часть
sprintf(buf, "GET /objects/?object=DHTsensor1&op=m&m=hum1&&t=%0d.%d HTTP/1.0", (int)current_hum1, abs(hum1));
sendHTTPRequest();
}
old_humidity1 = (int)current_hum1;
}
}
-
- Сообщения: 1115
- Зарегистрирован: Вс июн 14, 2015 11:08 am
- Благодарил (а): 85 раз
- Поблагодарили: 342 раза
Re: MegaLight - контроллер освещения на Arduino Mega 2560+W5
Все верно, только порядок получился неправильный. Проще всего теперь перенести саму функцию setup() в конец
СпойлерПоказать
Код: Выделить всё
#include <avr/wdt.h>
#include "DHT.h" //библиотека для работы с DHT
#define DHTPIN1 14 //Обозначаем номер пина, к которому подключен датчик
Scheduler runner;
Task t1(1, TASK_FOREVER, &buttonLoop, &runner);
Task t2(1, TASK_FOREVER, &relayLoop, &runner);
Task t3(1, TASK_FOREVER, &webLoop, &runner);
Task t4(1, TASK_FOREVER, &externalLoop, &runner);
void buttonLoop() {
inputList.check();
outputEM.processAllEvents();
}
void relayLoop() {
inputEM.processAllEvents();
outputList.check();
}
#define WBSIZE 1024
void webLoop()
{
char webBuffer[WBSIZE];
int buflen = WBSIZE;
webserver.processConnection(webBuffer, &buflen);
}
void externalLoop()
{
externalEM.processEvent();
}
bool loadConfig() {
const uint8_t CONFIG_LINE_LENGTH = 127;
// The open configuration file.
SDConfigFile cfg;
// Open the configuration file.
if (!cfg.begin(CONFIG_FILE, CONFIG_LINE_LENGTH)) {
Serialprint("Failed to open configuration file: %s\r\n", CONFIG_FILE);
return false;
}
// Read each setting from the file.
while (cfg.readNextSetting()) {
if (cfg.nameIs("mac")) {
parseBytes(cfg.getValue(), '-', mac, 6, 16);
Serial.print("MAC="); Serial.println(cfg.getValue());
} else if (cfg.nameIs("ip")) {
parseBytes(cfg.getValue(), '.', ip, 4, 10);
} else if (cfg.nameIs("mdHost")) {
mdHost = cfg.getValue();
} else if (cfg.nameIs("mdPort")) {
mdPort = cfg.getIntValue();
} else if (cfg.nameIs("mdAuth")) {
mdAuth = cfg.getValue();
}
}
// clean up
cfg.end();
return true;
}
bool setupSD() {
if (!SD.begin(4)) {
Serialprint("SD unavailable. Trying to load config from EEPROM.\r\n");
return false;
}
Serialprint("SD initialization done.\r\n");
return true;
}
void setupTasks()
{
t1.enable();
t2.enable();
t3.enable();
t4.enable();
runner.init();
runner.addTask(t1);
runner.addTask(t2);
runner.addTask(t3);
runner.addTask(t4);
}
int setupInputsSD() {
const uint8_t CONFIG_LINE_LENGTH = 127;
String configDir = F("/INPUTS");
File dir = SD.open(configDir);
if (!dir.isDirectory())
return 0;
inputList.clearInputs();
storageHeader.cntInputs = 0;
int sz = 0;
SDConfigFile cfg;
while (true) {
File inp = dir.openNextFile();
if (!inp)
break;
if (inp.isDirectory())
{
inp.close();
continue;
}
const char *id = inp.name();
inp.close();
ML2Input *b = new ML2Input(id);
// The open configuration file.
if (!cfg.begin(String(configDir + "/" + String(id)).c_str(), CONFIG_LINE_LENGTH)) {
Serialprint("Failed to open input file: %s\r\n", id);
delete b;
cfg.end();
continue;
}
// Read each setting from the file.
while (cfg.readNextSetting()) {
if (cfg.nameIs("pin")) {
b->setPin(cfg.getIntValue());
} else if (cfg.nameIs("pullup")) {
const char *pu = cfg.getValue();
if (!strcmp(pu, "intup"))
b->setPullup(InputPullup::IntPullup);
else if (!strcmp(pu, "extup"))
b->setPullup(InputPullup::ExtPullup);
else if (!strcmp(pu, "extdown"))
b->setPullup(InputPullup::PullDown);
} else if (cfg.nameIs("bounceint")) {
b->setBounceInterval(cfg.getIntValue());
} else if (cfg.nameIs("holdint")) {
b->setHoldInterval(cfg.getIntValue());
} else if (cfg.nameIs("repeat")) {
b->setRepeat(cfg.getBooleanValue());
} else if (cfg.nameIs("repeatint")) {
b->setRepeatInterval(cfg.getIntValue());
} else if (cfg.nameIs("dclickint")) {
b->setDoubleClickInterval(cfg.getIntValue());
} else if (cfg.nameIs("prevclick")) {
b->setPreventClick(cfg.getBooleanValue());
}
}
// clean up
cfg.end();
if (!inputList.addInput(b))
{
Serialprint("Failed to add input %s\r\n", id);
delete b;
}
else
{
Serialprint("Added input %s on pin %d\r\n", id, b->pin());
sz += saveInputEEPROM(b, storageHeader.addrInputs + sz);
storageHeader.cntInputs++;
}
}
dir.close();
return sz;
}
int setupOutputsSD() {
const uint8_t CONFIG_LINE_LENGTH = 127;
String configDir = F("/OUTPUTS");
File dir = SD.open(configDir);
if (!dir.isDirectory())
return 0;
outputList.clearOutputs();
storageHeader.cntOutputs = 0;
int sz = 0;
SDConfigFile cfg;
while (true) {
File inp = dir.openNextFile();
if (!inp)
break;
if (inp.isDirectory())
{
inp.close();
continue;
}
const char *id = inp.name();
inp.close();
ML2Output *b = new ML2Output(id);
// The open configuration file.
if (!cfg.begin(String(configDir + "/" + String(id)).c_str(), CONFIG_LINE_LENGTH)) {
Serialprint("Failed to open output file: %s\r\n", id);
delete b;
cfg.end();
continue;
}
// Read each setting from the file.
while (cfg.readNextSetting()) {
if (cfg.nameIs("pin")) {
b->setPin(cfg.getIntValue());
} else if (cfg.nameIs("pwm")) {
b->setPWM(cfg.getBooleanValue());
} else if (cfg.nameIs("invert")) {
b->setInvert(cfg.getBooleanValue());
} else if (cfg.nameIs("noreport")) {
b->setNoreport(cfg.getBooleanValue());
} else if (cfg.nameIs("on")) {
cfg.getBooleanValue() ? b->setOn() : b->setOff();
} else if (cfg.nameIs("value")) {
b->setValue(cfg.getIntValue());
} else if (cfg.nameIs("save")) {
const char *pu = cfg.getValue();
if (!strcmp(pu, "state"))
b->setSaveState(OutputStateSave::State);
else if (!strcmp(pu, "value"))
b->setSaveState(OutputStateSave::Value);
else if (!strcmp(pu, "both"))
b->setSaveState(OutputStateSave::StateAndValue);
}
}
// clean up
cfg.end();
if (!outputList.addOutput(b))
{
Serialprint("Failed to add output %s\r\n", id);
delete b;
}
else
{
Serialprint("Added output %s on pin %d\r\n", id, b->pin());
sz += saveOutputEEPROM(b, storageHeader.addrOutputs + sz);
storageHeader.cntOutputs++;
}
}
dir.close();
return sz;
}
int loadRulesFromFile(File &dir, String path) {
int sz = 0;
while (true) {
File entry = dir.openNextFile();
if (! entry) {
// no more files
break;
}
String npath = path + String("/") + entry.name();
if (entry.isDirectory()) {
sz += loadRulesFromFile(entry, npath);
entry.close();
continue;
}
entry.close();
ML2Rule *rule = ML2Rule::fromFile(npath);
if (rule) {
int s = saveRuleEEPROM(rule, storageHeader.addrRules);
sz += s;
storageHeader.addrRules += s;
storageHeader.cntRules++;
delete rule;
Serialprint("Loaded rule: %s\r\n", npath.c_str());
}
}
return sz;
}
int setupRulesSD() {
storageHeader.cntRules = 0;
File root = SD.open(RULES_PATH);
if (root) {
return loadRulesFromFile(root, "");
}
}
bool loadAllFromEEPROM() {
int addr = CONFIG_START;
int sz = loadConfigEEPROM(addr);
if (!sz)
return false;
addr += sz;
sz = loadHeaderEEPROM(addr);
addr += sz;
for (int i = 0; i < storageHeader.cntInputs; i++) {
ML2Input *input = new ML2Input("");
sz = loadInputEEPROM(input, addr);
if (inputList.addInput(input))
Serialprint("Added input %s on pin %d\r\n", input->ID, input->pin());
addr += sz;
}
for (int i = 0; i < storageHeader.cntOutputs; i++) {
ML2Output *output = new ML2Output("");
sz = loadOutputEEPROM(output, addr);
if (outputList.addOutput(output))
Serialprint("Added output %s on pin %d\r\n", output->ID, output->pin());
addr += sz;
}
for (int i = 0; i < storageHeader.cntRules; i++) {
ML2Rule *rule = new ML2Rule("");
sz = loadRuleEEPROM(rule, addr, true);
Serialprint("Added rule %s\r\n", rule->ID.c_str());
addr += sz;
delete rule;
}
return true;
}
int setupConfigSD() {
const uint8_t CONFIG_LINE_LENGTH = 127;
SDConfigFile cfg;
if (!cfg.begin(CONFIG_FILE, CONFIG_LINE_LENGTH)) {
Serialprint("Failed to open configuration file: %s\r\n", CONFIG_FILE);
return 0;
}
while (cfg.readNextSetting()) {
if (cfg.nameIs("mac")) {
parseBytes(cfg.getValue(), '-', mac, 6, 16);
Serial.print("MAC="); Serial.println(cfg.getValue());
} else if (cfg.nameIs("ip")) {
parseBytes(cfg.getValue(), '.', ip, 4, 10);
} else if (cfg.nameIs("mdHost")) {
mdHost = cfg.getValue();
} else if (cfg.nameIs("mdPort")) {
mdPort = cfg.getIntValue();
} else if (cfg.nameIs("mdAuth")) {
mdAuth = cfg.getValue();
}
}
// clean up
cfg.end();
return saveConfigEEPROM(CONFIG_START, false);
}
void saveAllToEEPROM() {
int sz = setupConfigSD();
if (!sz) {
Serialprint("Failed to store config\r\n");
return;
}
int addr = CONFIG_START + sz;
int addrHeader = addr;
addr += sizeof(storageHeader);
storageHeader.addrInputs = addr;
sz = setupInputsSD();
addr += sz;
Serialprint("Stored %d inputs (%d bytes)\r\n\r\n", storageHeader.cntInputs, sz);
storageHeader.addrOutputs = addr;
sz = setupOutputsSD();
addr += sz;
Serialprint("Stored %d outputs (%d bytes)\r\n\r\n", storageHeader.cntOutputs, sz);
storageHeader.addrRules = addr;
sz = setupRulesSD();
addr += sz;
Serialprint("Stored %d rules (%d bytes)\r\n\r\n", storageHeader.cntRules, sz);
saveHeaderEEPROM(addrHeader);
saveConfigEEPROM(CONFIG_START, true);
Serialprint("Stored config to EEPROM (%d bytes)\r\n\r\n", addr - CONFIG_START);
}
int freeRam () {
extern int __heap_start, *__brkval;
int v;
return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}
void loop() {
wdt_reset();
runner.execute();
}
void reset() {
wdt_enable(WDTO_1S);
while (1);
}
byte server[] = { 192, 168, 21, 80 };
DHT dht1(DHTPIN1, DHT22); //инициируем датчик DHT
Task tDHT(2000, TASK_FOREVER, &DHTloop, &runner);
int old_temperature1 = 0;
int old_humidity1 = 0;
char buf[80];
// Функция отправки HTTP-запроса на сервер
void sendHTTPRequest() {
Serial.println(buf);
if (!client.connected())
client.stop();
if (client.connect(mdHost.c_str(), mdPort)) {
Serial.println("OK");
client.println(buf);
client.println("Host: 192.168.21.80");
client.println();
delay(10);
while (client.available()) {
client.read();
}
client.stop();
} else {
Serial.println("FAILED");
}
}
void DHTloop()
{
// SENSOR 1 --------------------------------------
//Считываем температуру
float current_temp1 = 0;
float t1 = dht1.readTemperature(); //Считываем температуру в переменную "t"
{
current_temp1 = t1; // получаем температуру
Serial.println(current_temp1);
if ((old_temperature1 != (int)current_temp1)) {
int temp1 = (current_temp1 - (int)current_temp1) * 100; // выделяем дробную часть
sprintf(buf, "GET /objects/?object=DHTsensor1&op=m&m=temp1&t=%0d.%d HTTP/1.0", (int)current_temp1, abs(temp1));
sendHTTPRequest();
}
old_temperature1 = (int)current_temp1;
}
//Считываем влажность
float current_hum1 = 0;
float h1 = dht1.readHumidity(); //Считываем температуру в переменную "t"
{
current_hum1 = h1; // получаем влажность
Serial.println(current_hum1);
if ((old_humidity1 != (int)current_hum1)) {
int hum1 = (current_hum1 - (int)current_hum1) * 100; // выделяем дробную часть
sprintf(buf, "GET /objects/?object=DHTsensor1&op=m&m=hum1&t=%0d.%d HTTP/1.0", (int)current_hum1, abs(hum1));
sendHTTPRequest();
}
old_humidity1 = (int)current_hum1;
}
}
void setup() {
tDHT.enable();
runner.addTask(tDHT);
wdt_disable();
Serial.begin(115200);
Serialprint("Starting...\r\n");
if (setupSD()) {
saveAllToEEPROM();
} else {
loadAllFromEEPROM();
}
setupWeb();
setupEMs();
setupTasks();
Serialprint("Started (free RAM: %d)\r\n", freeRam());
wdt_enable(WDTO_4S);
}
Последний раз редактировалось olehs Вт дек 26, 2017 9:03 pm, всего редактировалось 2 раза.
-
- Сообщения: 113
- Зарегистрирован: Пт июн 09, 2017 11:18 pm
- Благодарил (а): 17 раз
- Поблагодарили: 13 раз
Re: MegaLight - контроллер освещения на Arduino Mega 2560+W5
Теперь матерится по другому: 'runner' was not declared in this scope
в строке runner.addTask(tDHT);
в строке runner.addTask(tDHT);
-
- Сообщения: 1115
- Зарегистрирован: Вс июн 14, 2015 11:08 am
- Благодарил (а): 85 раз
- Поблагодарили: 342 раза
Re: MegaLight - контроллер освещения на Arduino Mega 2560+W5
Пардон, на скорую руку правил по своему коду.
Я исправил код выше, попробуйте еще раз.
Я исправил код выше, попробуйте еще раз.