Arduino Mega Server
Модератор: Alex
Re: Arduino Mega Server
5. Нет, ты создал объект и его не удалил. Куча, очень опасная вещь, не надо её использовать без крайней надобности.
Код дам завтра.
Код дам завтра.
Re: Arduino Mega Server
Премного благодарен!
UPD Починил по наводке Димы! Действительно sizeof должным образом отрабатывает и не переполняет буффер!
Ну и рабочий код оставлю на всякий случай
Еще раз спасибо Диме!
UPD Починил по наводке Димы! Действительно sizeof должным образом отрабатывает и не переполняет буффер!
Ну и рабочий код оставлю на всякий случай
Код: Выделить всё
===Объявлено снаружи===
struct port_param_t{String name; int value;};
#define MAX_PARAMS 20 // сколько параметров максимально мы умеем парсить
port_param_t params[MAX_PARAMS];
===Объявлено снаружи===
void setRGBA() {
byte parsedParams=0;
int r, g, b, a;
unsigned char* buf = new unsigned char[parameter.length()]; // С sizeof(parameter) НЕ РАБОТАЕТ!!!
parameter.getBytes(buf, parameter.length()); // С sizeof(parameter) НЕ РАБОТАЕТ!!!
char* inputString = (char*)buf;
parsedParams=0;
char* buffer = strtok(inputString,"&");
if(buffer!=NULL){
for(buffer=strtok(NULL,"&"); buffer!=NULL; buffer=strtok(NULL,"&") )
{
String buffer1= String(buffer);
params[parsedParams].name= buffer1.substring(0,buffer1.indexOf('='));
params[parsedParams].value=strtoint(buffer1.substring(buffer1.indexOf('=')+1));
parsedParams++; // отмечаем сколько удалось распарсить
}
if(parsedParams>MAX_PARAMS-1)return; // больше нет места куда сохранять парсенное.
}
r = params[0].value;
g = params[1].value;
b = params[2].value;
a = params[3].value;
color(led1, r, g, b);
}
int strtoint(String str) // Процедура переобразования строки в число
{
int tempInt;
char rez[str.length()+1];
str.toCharArray(rez, sizeof(rez));
tempInt = atoi(rez);
return tempInt;
}
Последний раз редактировалось Xseon Пн фев 01, 2016 10:25 pm, всего редактировалось 3 раза.
Re: Arduino Mega Server
Рабочий код это хорошо. Вопрос: эта штука универсальная (в смысле количества параметров)?
Как она себя поведёт при 2-х парамерах? А при 10-и?
Имеется в виду сам парсинг, не обёртка в виде rgba.
Как она себя поведёт при 2-х парамерах? А при 10-и?
Имеется в виду сам парсинг, не обёртка в виде rgba.
Re: Arduino Mega Server
Да, абсолютно универсальная у меня в скетче стоит константа обработки до 20 параметров. Но ключевое слово в запросе rgb=1, но само собой тоже правится на нужное.
На правильность кода не претендую, думаю Дима лучше вариант опубликует.
На правильность кода не претендую, думаю Дима лучше вариант опубликует.
Re: Arduino Mega Server
Почти универсальный. Почти - по причине пропуска значения до первого амперсанда. Значение может быть и ненужно, но это надо учитывать.
И, непонятно, зачем используется "params[parsedParams]."? Который, в добавок, объявлен где то снаружи.
Для чего params[parsedParams].name? Если нет контроля? Да и вообще, нужно ли имя параметра в строке?
И, непонятно, зачем используется "params[parsedParams]."? Который, в добавок, объявлен где то снаружи.
Для чего params[parsedParams].name? Если нет контроля? Да и вообще, нужно ли имя параметра в строке?
Re: Arduino Mega Server
Обновил свой предыдущий пост с кодом!
Как выяснилось тестил не ту функцию и потом только увидел, что sizeof(parameter) определяет размер в конкретном примере как int 6, а длина строки как раз в моём случае должна быть 20.
Код выше исправил и оттестировал многократно, проблем и зависаний при обработке переданных параметров не обнаружил.
По поводу универсальности. Мне примерно так и надо было, чтобы штатным парсером отсекалась команда, если команда найдена в списке команд, то я вызываю нужный мне обработчик.
Как выяснилось тестил не ту функцию и потом только увидел, что sizeof(parameter) определяет размер в конкретном примере как int 6, а длина строки как раз в моём случае должна быть 20.
Код выше исправил и оттестировал многократно, проблем и зависаний при обработке переданных параметров не обнаружил.
По поводу универсальности. Мне примерно так и надо было, чтобы штатным парсером отсекалась команда, если команда найдена в списке команд, то я вызываю нужный мне обработчик.
Re: Arduino Mega Server
Исключительно для красоты и полноты ООП))) А вот имена параметров в строке считаю очень правильным и с МД удобнее обращаться да и в скетче тоже, хотя если обратить вничание на мою функцию, то на данный момент они не используются и не проверяются!SPbDima писал(а):Почти универсальный. Почти - по причине пропуска значения до первого амперсанда. Значение может быть и ненужно, но это надо учитывать.
И, непонятно, зачем используется "params[parsedParams]."? Который, в добавок, объявлен где то снаружи.
Для чего params[parsedParams].name? Если нет контроля? Да и вообще, нужно ли имя параметра в строке?
Re: Arduino Mega Server
Подскажите , на стадии загрузки скетча выходит ошибка на вкладке "noo"!!
Папку темп очистил( пустая)
Arduino: 1.6.5 (Windows 7), Плата"Arduino/Genuino Uno"
noo.ino: In function 'void nooInit()':
noo:18: error: 'Serial1' was not declared in this scope
noo.ino: In function 'void nooSendCommand(byte, byte, byte, byte)':
noo:50: error: 'Serial1' was not declared in this scope
'Serial1' was not declared in this scope
Папку темп очистил( пустая)
Arduino: 1.6.5 (Windows 7), Плата"Arduino/Genuino Uno"
noo.ino: In function 'void nooInit()':
noo:18: error: 'Serial1' was not declared in this scope
noo.ino: In function 'void nooSendCommand(byte, byte, byte, byte)':
noo:50: error: 'Serial1' was not declared in this scope
'Serial1' was not declared in this scope
Re: Arduino Mega Server
Автор, но все таки что не правильно делаю.
1. подключил Arduinu mega 2560. выбрал настройки подключения в IDE
2. раскрыл библиотеки в arduino/lib/ (получил dallastemperature,ds1307rtc,..) причем и в текущую где скетч и туда где скетч
3. указал в IDE путь запуска скетча, почистил Temp
4. открыл скетч. заливаю. и получаю ошибки
такое ощущение, что не видится библиотеки.
Arduino: 1.6.5 (Windows 8.1), Плата"Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"
arduino_mega_server.ino: In function 'void setup()':
arduino_mega_server:181: error: 'timersInit' was not declared in this scope
arduino_mega_server:183: error: 'ethernetInit' was not declared in this scope
arduino_mega_server:187: error: 'SDcardInit' was not declared in this scope
arduino_mega_server:188: error: 'serverInit' was not declared in this scope
arduino_mega_server:192: error: 'rtcInit' was not declared in this scope
arduino_mega_server:197: error: 'majordomoInit' was not declared in this scope
arduino_mega_server:198: error: 'majordomoMegaLive' was not declared in this scope
arduino_mega_server:223: error: 'uploadInit' was not declared in this scope
arduino_mega_server:228: error: 'pirsInit' was not declared in this scope
arduino_mega_server:232: error: 'contactsInit' was not declared in this scope
arduino_mega_server:236: error: 'tempInit' was not declared in this scope
arduino_mega_server:240: error: 'electroInit' was not declared in this scope
arduino_mega_server:248: error: 'ledsInit' was not declared in this scope
arduino_mega_server.ino: In function 'void loop()':
arduino_mega_server:257: error: 'uploadWorks' was not declared in this scope
arduino_mega_server:262: error: 'rtcWorks' was not declared in this scope
arduino_mega_server:266: error: 'profStart' was not declared in this scope
arduino_mega_server:267: error: 'timersWorks' was not declared in this scope
arduino_mega_server:270: error: 'serverWorks' was not declared in this scope
arduino_mega_server:282: error: 'pirsWorks' was not declared in this scope
arduino_mega_server:286: error: 'contactsWorks' was not declared in this scope
arduino_mega_server:291: error: 'tempWorks' was not declared in this scope
arduino_mega_server:298: error: 'electroWorks' was not declared in this scope
arduino_mega_server:299: error: 'freqWorks' was not declared in this scope
arduino_mega_server:303: error: 'freqWorks' was not declared in this scope
arduino_mega_server:309: error: 'majordomoMegaLive' was not declared in this scope
arduino_mega_server:341: error: 'rtcSync' was not declared in this scope
arduino_mega_server:346: error: 'cyclosInSecWork' was not declared in this scope
arduino_mega_server:355: error: 'eraseCyclos' was not declared in this scope
arduino_mega_server:356: error: 'profCalc' was not declared in this scope
arduino_mega_server:358: error: 'cyclosDelayWork' was not declared in this scope
'timersInit' was not declared in this scope
1. подключил Arduinu mega 2560. выбрал настройки подключения в IDE
2. раскрыл библиотеки в arduino/lib/ (получил dallastemperature,ds1307rtc,..) причем и в текущую где скетч и туда где скетч
3. указал в IDE путь запуска скетча, почистил Temp
4. открыл скетч. заливаю. и получаю ошибки
такое ощущение, что не видится библиотеки.
Arduino: 1.6.5 (Windows 8.1), Плата"Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"
arduino_mega_server.ino: In function 'void setup()':
arduino_mega_server:181: error: 'timersInit' was not declared in this scope
arduino_mega_server:183: error: 'ethernetInit' was not declared in this scope
arduino_mega_server:187: error: 'SDcardInit' was not declared in this scope
arduino_mega_server:188: error: 'serverInit' was not declared in this scope
arduino_mega_server:192: error: 'rtcInit' was not declared in this scope
arduino_mega_server:197: error: 'majordomoInit' was not declared in this scope
arduino_mega_server:198: error: 'majordomoMegaLive' was not declared in this scope
arduino_mega_server:223: error: 'uploadInit' was not declared in this scope
arduino_mega_server:228: error: 'pirsInit' was not declared in this scope
arduino_mega_server:232: error: 'contactsInit' was not declared in this scope
arduino_mega_server:236: error: 'tempInit' was not declared in this scope
arduino_mega_server:240: error: 'electroInit' was not declared in this scope
arduino_mega_server:248: error: 'ledsInit' was not declared in this scope
arduino_mega_server.ino: In function 'void loop()':
arduino_mega_server:257: error: 'uploadWorks' was not declared in this scope
arduino_mega_server:262: error: 'rtcWorks' was not declared in this scope
arduino_mega_server:266: error: 'profStart' was not declared in this scope
arduino_mega_server:267: error: 'timersWorks' was not declared in this scope
arduino_mega_server:270: error: 'serverWorks' was not declared in this scope
arduino_mega_server:282: error: 'pirsWorks' was not declared in this scope
arduino_mega_server:286: error: 'contactsWorks' was not declared in this scope
arduino_mega_server:291: error: 'tempWorks' was not declared in this scope
arduino_mega_server:298: error: 'electroWorks' was not declared in this scope
arduino_mega_server:299: error: 'freqWorks' was not declared in this scope
arduino_mega_server:303: error: 'freqWorks' was not declared in this scope
arduino_mega_server:309: error: 'majordomoMegaLive' was not declared in this scope
arduino_mega_server:341: error: 'rtcSync' was not declared in this scope
arduino_mega_server:346: error: 'cyclosInSecWork' was not declared in this scope
arduino_mega_server:355: error: 'eraseCyclos' was not declared in this scope
arduino_mega_server:356: error: 'profCalc' was not declared in this scope
arduino_mega_server:358: error: 'cyclosDelayWork' was not declared in this scope
'timersInit' was not declared in this scope
Re: Arduino Mega Server
У вас неправильно указана плата — с Уно АМС не работаетArduino: 1.6.5 (Windows 7), Плата"Arduino/Genuino Uno"
Вот этого делать не надо. Архив это целый проект, нужно только разархивировать и указать правильный путь.Автор, но все таки что не правильно делаю.
2. раскрыл библиотеки в arduino/lib/ (получил dallastemperature,ds1307rtc,..) причем и в текущую где скетч и туда где скетч
Под Windows 8 не тестировалось — должно работать, но возможны варианты.Arduino: 1.6.5 (Windows 8.1), Плата"Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"