Дабы не флудить в чужих темах .. Есть задача передавать (принимать) данные между UNO+W5100 и OpenHab Пока что первая проблема это передать не статичные данные а переменную. Спойлер: Скетч Код (C++): #include <SPI.h> #include <Ethernet.h> #include <PubSubClient.h> char t = 0; // Update these with values suitable for your network. byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED }; IPAddress ip(192, 168, 0, 15); IPAddress server(192, 168, 0, 100); void callback(char* topic, byte* payload, unsigned int length) { Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); for (int i=0;i<length;i++) { Serial.print((char)payload[i]); } Serial.println(); } EthernetClient ethClient; PubSubClient client(ethClient); void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.println("Attempting MQTT connection..."); // Attempt to connect if (client.connect("arduinoClient")) { Serial.println("connected"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); delay(5000); } } } void setup() { Serial.begin(9600); client.setServer(server, 1883); client.setCallback(callback); Ethernet.begin(mac, ip); // Allow the hardware to sort itself out delay(1500); } void loop() { if (!client.connected()) { reconnect(); } for ( t = 150; t >= 0; t--){ // Once connected, publish an announcement... String toSend = (String) t; client.publish("test",toSend); } } Выскакивает следующая Спойлер: Ошибка Код (C++): no matching function for call to 'PubSubClient::publish(const char [5], String&)' Прошу помощи зала.
1. Нашел рабочий код с переменными! Спойлер: Код Код (C++): #include <SPI.h> #include <Ethernet.h> #include <PubSubClient.h> char t = 0; // Update these with values suitable for your network. byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED }; IPAddress ip(192, 168, 0, 15); IPAddress server(192, 168, 0, 100); int sensorPin=5; int lastTemperature; unsigned long lastTime; char buffer[10]; void callback(char* topic, byte* payload, unsigned int length) { // handle message arrived (no messages expected though) } EthernetClient ethClient; PubSubClient client(server, 1883, callback, ethClient); void setup() { Ethernet.begin(mac, ip); if (client.connect("arduinoClient")) { client.publish("test/status/arduino01","online"); lastTemperature=0; lastTime=0; } } void loop() { int reading=analogRead(sensorPin); int temperature = ((reading * 0.004882)-0.50)*100; if(temperature!=lastTemperature) { if(millis()>(lastTime+1000)) { sprintf(buffer,"%d",temperature); client.publish("test/device/arduino01",buffer); lastTemperature=temperature; lastTime=millis(); } } client.loop(); } Добавил функцию переподключения при потере связи. Спойлер: Код Код (C++): #include <SPI.h> #include <Ethernet.h> #include <PubSubClient.h> char t = 0; // Update these with values suitable for your network. byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED }; IPAddress ip(192, 168, 0, 15); IPAddress server(192, 168, 0, 100); int sensorPin=5; int lastTemperature; unsigned long lastTime; char buffer[5]; void callback(char* topic, byte* payload, unsigned int length) { // handle message arrived (no messages expected though) } EthernetClient ethClient; PubSubClient client(server, 1883, callback, ethClient); void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.println("Attempting MQTT connection..."); // Attempt to connect if (client.connect("arduinoClient")) { Serial.println("connected"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); delay(5000); } } } void setup() { Serial.begin(9600); Ethernet.begin(mac, ip); if (client.connect("arduinoClient")) { Serial.print("online"); lastTemperature=0; lastTime=0; } } void loop() { if (!client.connected()) { reconnect(); } int reading=analogRead(sensorPin); int temperature = ((reading * 0.004882)-0.50)*100; if(temperature!=lastTemperature) { if(millis()>(lastTime+1000)) { sprintf(buffer,"%d",temperature); client.publish("test/device/arduino01",buffer); lastTemperature=temperature; lastTime=millis(); } } client.loop(); }
2. Подключены 2шт DS18b20 Спойлер: код Код (C++): #include <SPI.h> #include <Ethernet.h> #include <PubSubClient.h> #include <OneWire.h> #include <DallasTemperature.h> #define ONE_WIRE_BUS 5 OneWire oneWire(ONE_WIRE_BUS); DallasTemperature sensors(&oneWire); DeviceAddress Thermometer1 = { 0x28, 0xFF, 0x62, 0x42, 0x62, 0x15, 0x01, 0x9A }; // адрес датчика DS18B20 280054B604000092 DeviceAddress Thermometer2 = { 0x28, 0xFF, 0xE7, 0x2C, 0xA6, 0x15, 0x01, 0xCB }; IPAddress ip(192, 168, 0, 15); IPAddress server(XXX, XXX, XXX, XXX); byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED }; char tmp1[10]; char tmp2[10]; unsigned long loopTime; unsigned long currentTime; EthernetClient ethClient; PubSubClient client(server, 1883, callback, ethClient); void callback(char* topic, byte* payload, unsigned int length) { // handle message arrived (no messages expected though) } void reconnect() { while (!client.connected()) { Serial.println("Attempting MQTT connection..."); // Attempt to connect if (client.connect("arduinoClient")) { Serial.println("connected"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); delay(3000); } } } void setup() { Serial.begin(9600); sensors.begin(); sensors.setResolution(Thermometer1, 10); sensors.setResolution(Thermometer2, 10); currentTime = millis(); loopTime = currentTime; Ethernet.begin(mac, ip); if (client.connect("arduinoClient")) { Serial.println("online"); } } void loop() { client.loop(); currentTime = millis(); sensors.requestTemperatures(); if(currentTime >= (loopTime + 10000)){ if (!client.connected()) { reconnect(); } float temperature1 = sensors.getTempC(Thermometer1); float temperature2 = sensors.getTempC(Thermometer2); dtostrf(temperature1, -2, 1, tmp1); client.publish("test/device/arduino01/temp1",tmp1); dtostrf(temperature2, -2, 1, tmp2); client.publish("test/device/arduino01/temp2",tmp2); loopTime = currentTime; } } Итемы для OpenHab Код (Java): Number ds1 "t° Обратки [%.1f °C]" <temperature> { mqtt="<[mosquitto:test/device/arduino01/temp1:state:default]" } Number ds2 "t° Подачи [%.1f °C]" <temperature> { mqtt="<[mosquitto:test/device/arduino01/temp2:state:default]" } Далее в планах прикрутить управление внешними устройствами.
3. Добавлено 2 реле !! Спойлер: код Код (C++): #include <SPI.h> #include <Ethernet.h> #include <PubSubClient.h> #include <OneWire.h> #include <DallasTemperature.h> int REL1; // not sensing light, LED off int REL2; // not sensing light, LED off #define ONE_WIRE_BUS 5 #define rel1_pin 6 #define rel2_pin 7 OneWire oneWire(ONE_WIRE_BUS); DallasTemperature sensors(&oneWire); DeviceAddress Thermometer1 = { 0x28, 0xFF, 0x62, 0x42, 0x62, 0x15, 0x01, 0x9A }; // адрес датчика DS18B20 280054B604000092 DeviceAddress Thermometer2 = { 0x28, 0xFF, 0xE7, 0x2C, 0xA6, 0x15, 0x01, 0xCB }; IPAddress ip(192, 168, 0, 15); IPAddress server(XXX, XXX, XXX, XXX); byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED }; char tmp1[10]; char tmp2[10]; unsigned long loopTime; unsigned long currentTime; char message_buff[100]; EthernetClient ethClient; PubSubClient client(server, 1883, callback, ethClient); void callback(char* topic, byte* payload, unsigned int length) { payload[length] = '\0'; Serial.print(topic); Serial.print(" "); String strTopic = String(topic); String strPayload = String((char*)payload); Serial.println(strPayload); if (strTopic == "test/device/arduino01/rel1") { if (strPayload == "ON"){REL1 = 1;} else if (strPayload == "OFF"){REL1 = 0;} Serial.print("REL1 = "); Serial.println(REL1); } else if (strTopic == "test/device/arduino01/rel2") { if (strPayload == "ON") {REL2 = 1;} else if (strPayload == "OFF") {REL2 = 0;} Serial.print("REL2 = "); Serial.println(REL2); } } void reconnect() { while (!client.connected()) { Serial.println("Attempting MQTT connection..."); // Attempt to connect if (client.connect("arduinoClient")) { Serial.println("connected"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); delay(3000); } } } void setup() { Serial.begin(9600); pinMode(rel1_pin, OUTPUT); digitalWrite(rel1_pin, LOW); pinMode(rel2_pin, OUTPUT); digitalWrite(rel2_pin, LOW); sensors.begin(); sensors.setResolution(Thermometer1, 10); sensors.setResolution(Thermometer2, 10); currentTime = millis(); loopTime = currentTime; Ethernet.begin(mac, ip); if (client.connect("arduinoClient")) { Serial.println("online"); client.publish("test/device/arduino01/rel1", "OFF"); client.publish("test/device/arduino01/rel2", "OFF"); client.subscribe("test/device/arduino01/#"); } } void loop() { if (REL1 == 0) digitalWrite(rel1_pin, LOW); else if (REL1 == 1) digitalWrite(rel1_pin, HIGH); if (REL2 == 0) digitalWrite(rel2_pin, LOW); else if (REL2 == 1) digitalWrite(rel2_pin, HIGH); client.loop(); currentTime = millis(); sensors.requestTemperatures(); if(currentTime >= (loopTime + 10000)){ if (!client.connected()) { reconnect(); } float temperature1 = sensors.getTempC(Thermometer1); float temperature2 = sensors.getTempC(Thermometer2); dtostrf(temperature1, -2, 1, tmp1); client.publish("test/device/arduino01/temp1",tmp1); dtostrf(temperature2, -2, 1, tmp2); client.publish("test/device/arduino01/temp2",tmp2); loopTime = currentTime; } } и итемы Код (Java): Switch Reley1 "Реле1" { mqtt=">[mosquitto:test/device/arduino01/rel1:command:on:ON],>[mosquitto:test/device/arduino01/rel1:command:off:OFF],<[mosquitto:test/device/arduino01/rel1:state:MAP(switchMQTT.map)]" } Switch Reley2 "Реле2" { mqtt=">[mosquitto:test/device/arduino01/rel2:command:on:ON],>[mosquitto:test/device/arduino01/rel2:command:off:OFF],<[mosquitto:test/device/arduino01/rel2:state:MAP(switchMQTT.map)]" }
4. Добавлена функция управления реле по заданной температуре. Спойлер: Код Arduino Код (C++): #include <SPI.h> #include <Ethernet.h> #include <PubSubClient.h> #include <OneWire.h> #include <DallasTemperature.h> #define ONE_WIRE_BUS 5 #define rel1_pin 6 #define rel2_pin 7 char REL1; // not sensing light, LED off char REL2; // not sensing light, LED off char tmp1[10]; char tmp2[10]; char tUstav1; char StrtUstav11[3]; unsigned long loopTime; unsigned long currentTime; OneWire oneWire(ONE_WIRE_BUS); DallasTemperature sensors(&oneWire); DeviceAddress Thermometer1 = { 0x28, 0xFF, 0x62, 0x42, 0x62, 0x15, 0x01, 0x9A }; DeviceAddress Thermometer2 = { 0x28, 0xFF, 0xE7, 0x2C, 0xA6, 0x15, 0x01, 0xCB }; IPAddress ip(192, 168, 0, 15); IPAddress server(XXX, XXX, XXX, XXX); byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED }; EthernetClient ethClient; PubSubClient client(server, 1883, callback, ethClient); void callback(char* topic, byte* payload, unsigned int length) { payload[length] = '\0'; Serial.print(topic); Serial.print(" "); String strTopic = String(topic); String strPayload = String((char*)payload); Serial.println(strPayload); if (strTopic == "test/device/arduino01/rel1") { if (strPayload == "ON"){REL1 = 1;} else if (strPayload == "OFF"){REL1 = 0;} } else if (strTopic == "test/device/arduino01/rel2") { if (strPayload == "ON") {REL2 = 1;} else if (strPayload == "OFF") {REL2 = 0;} } else if (strTopic == "test/device/arduino01/kotel1/get") { char tUstav11; tUstav11 = atoi((char*)payload); if (tUstav11 != tUstav1 ) { tUstav1 = tUstav11; } } } void reconnect() { while (!client.connected()) { Serial.println("Attempting MQTT connection..."); // Attempt to connect if (client.connect("arduinoClient")) { Serial.println("connected"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); delay(3000); } } } void setup() { Serial.begin(9600); pinMode(rel1_pin, OUTPUT); digitalWrite(rel1_pin, LOW); pinMode(rel2_pin, OUTPUT); digitalWrite(rel2_pin, LOW); sensors.begin(); sensors.setResolution(Thermometer1, 10); sensors.setResolution(Thermometer2, 10); currentTime = millis(); loopTime = currentTime; Ethernet.begin(mac, ip); if (client.connect("arduinoClient")) { Serial.println("online"); client.publish("test/device/arduino01/rel1", "OFF"); client.publish("test/device/arduino01/rel2", "OFF"); client.publish("test/device/arduino01/kotel1/get", "37"); client.subscribe("test/device/arduino01/#"); } } void loop() { if (REL1 == 0) digitalWrite(rel1_pin, LOW); else if (REL1 == 1) digitalWrite(rel1_pin, HIGH); if (REL2 == 0) digitalWrite(rel2_pin, LOW); else if (REL2 == 1) digitalWrite(rel2_pin, HIGH); if ((sensors.getTempC(Thermometer2)) < tUstav1 && REL2==0) { REL2 = 1; client.publish("test/device/arduino01/rel2", "ON"); Serial.println("REL2 - ON"); } else if ((sensors.getTempC(Thermometer2)) >= tUstav1 && REL2==1) { REL2=0; client.publish("test/device/arduino01/rel2", "OFF"); Serial.println("REL2 - OFF"); } client.loop(); currentTime = millis(); sensors.requestTemperatures(); if(currentTime >= (loopTime + 15000)){ if (!client.connected()) { reconnect(); } float temperature1 = sensors.getTempC(Thermometer1); float temperature2 = sensors.getTempC(Thermometer2); dtostrf(temperature1, -2, 1, tmp1); client.publish("test/device/arduino01/temp1",tmp1); dtostrf(temperature2, -2, 1, tmp2); client.publish("test/device/arduino01/temp2",tmp2); dtostrf(tUstav1, -2, 0, StrtUstav11); client.publish("test/device/arduino01/kotel1/get", StrtUstav11); loopTime = currentTime; } } Буду признателен если кто то даст совет по оптимизации кода. сейчас он занимает 70% памяти контроллера. Items: Код (Java): Number ds1 "t° Обратки [%.1f °C]" <temperature> { mqtt="<[mosquitto:test/device/arduino01/temp1:state:default]" } Number ds2 "t° Подачи [%.1f °C]" <temperature> { mqtt="<[mosquitto:test/device/arduino01/temp2:state:default]" } Switch Reley1 "Реле1" { mqtt=">[mosquitto:test/device/arduino01/rel1:command:on:ON],>[mosquitto:test/device/arduino01/rel1:command:off:OFF],<[mosquitto:test/device/arduino01/rel1:state:default]" } Switch Reley2 "Реле2" { mqtt=">[mosquitto:test/device/arduino01/rel2:command:on:ON],>[mosquitto:test/device/arduino01/rel2:command:off:OFF],<[mosquitto:test/device/arduino01/rel2:state:default]" } Number Kotel_Show_Get "Уставка подачи [%.2f °C]" <temperature> { mqtt="<[mosquitto:test/device/arduino01/kotel1/get:state:default]" } Number Kotel_Getting "Отопление Скрытая Цель [%.2f °C]" <temperature> { mqtt="<[mosquitto:test/device/arduino01/kotel1/get:state:default]" } Number Kotel_Proxy "Отопление для команд [%.2f C]" <temperature> { mqtt=">[mosquitto:test/device/arduino01/kotel1/get:command:*:default]" } String Relay2_Getting "Реле2 состояние" { mqtt="<[mosquitto:test/device/arduino01/rel2:state:default]" } sitemap: Код (Java): Frame label="Arduino+W5100" { Text item=ds2 Text item=ds1 Text item=Kotel_Show_Get Setpoint item=Kotel_Getting label="Реулировка Уставки 37-80°C [%.1f °C]" icon="temperature" minValue=37 maxValue=80 step=1 } Frame { Switch item=Reley1 Switch item=Reley2 } rules: Код (Java): import org.openhab.core.library.types.* import org.openhab.core.persistence.* import org.openhab.model.script.actions.* var Timer timer11 = null rule "change heating" when Item Kotel_Getting changed then if (timer11 != null) timer11.cancel() timer11 = createTimer(now.plusSeconds(5)) [| { sendCommand(Kotel_Proxy, Kotel_Getting.state.toString) } ] end P/S: Отдельное спасибо выражаю ИгорюК! Без его примеров времени и сил было бы потрачено в разы больше. И другим участникам форума за умные мысли и полезные советы.
Не знаю писалось тут или нет, но на всякий случай, может кому то пригодится. 5. Ставим пароль на доступ к OpenHab 1. Редактируем файл users.cfg из директории /opt/openhab/configurations в файле пишем: user1=pass1 Думаю тут все понятно. Пользователей может быть несколько. Сохраняем файл. 2. В файле openhab.cfg из той же директории ищем ####################################################################################### ##### General configurations ##### ####################################################################################### удаляем одну # и пишем длинное слово ON , Должно получиться вот так: Код (Java): # configures the security options. The following values are valid: # ON = security is switched on generally # OFF = security is switched off generally # EXTERNAL = security is switched on for external requests # (e.g. originating from the Internet) only # (optional, defaults to 'OFF') security:option=ON 3. Перезагружаем сервис OpenHab. 4. Радуемся результату.
делаю подобный небольшой проект управления отоплением на даче 1. Интернет там есть 2. железо Arduino Mega, w5100 3. Сенсоры и реле.... Прочитал ваш пост. Ничего не понял про всякие Items:, mqtt=">[mosquitto: и прочее На самой Arduine проекты пишу Буду признателен.