Enc28j60 mqtt arduino

A Simple MQTT Pub/Sub Node With Arduino UNO and ENC28J60 Ethernetshield

Introduction: A Simple MQTT Pub/Sub Node With Arduino UNO and ENC28J60 Ethernetshield

While playing with MQTT on various ESP8266’s, I started to wonder if maybe I could do something with an old ENC28j60 shield and module I still had laying around and actually hardly ever used.

For the youngsters: The ENC28J60 Ethernetshield was the first shield to connect the Arduino with the internet. The major drawback of the chip was that it was lacking a stack, that subsequently had to be constructed in software. As a result it was kinda memory hungry. The initial version was without an SD card slot, the later version had an SD card slot. There were two libraries available: The Ethercard and the Ethershield library. The UIPEthernet library came later. As far as I could figure out, the PubSubClient library that is needed for MQTT doesnt work with the original Ethershield/EtherCard libraries. It does work with the UIPEthernet library though (extended fork here). The UIPEthernet library is a smart piece of coding that made programs written for the W5100 Ethernetshield suitable to be used with the ENC28J60 Shield, simply by changing the included library. Ofcourse there is a price to pay for this, namely more memory consumption. There is also an MQTT client for the ENC28J60/Atmega328 based Nanode.

Anyway, there still is enough memory to read a DHT11 sensor an analog port and some switches. In my case those were 3 door contacts. The PubSubClient is the original from Knolleary, though normally I am more a fan of the fork by Imroy. For this example I have used the Mosquitto public broker but ofcourse any broker can be used. I have installed the Mosquitto broker on a local raspberry and I found that a call to («raspberrypi.local»,1883) does not work, using the local 192.168.1.xxx ip number does work though

The program is rather ‘spartan’, to save space. Print statements have been removed or commented out after initial testing.

Just for completeness sake, this sketch takes about 77% of memory. This same sketch for the WIZ5100 based Ethernet shield, with the Ethernet.h library takes about 52% of memory. If you decide to adapt the sketch, be careful with altering the character strings. For instance, using the string «OPEN» 3 times is likely less memory consuming than having 3 different strings of the same or even shorter length. Obviously the ‘topic’ strings take a lot of space as well and if you were to shorten them to less meaningful names, you could add more sensors such as for instance a PIR sensor.

Should you copy the program from this blog page, you may copy ‘stray characters’ that you have to delete. You can also download it here.

A final warning. after I updated my libraries, including the Adafruit DHT library, I received an error on compiling this sketch. That disappeared when I returned it to version 1.2.1. I thought I was not using the Adafruit library but the Tillaert library, but DHT libraries come a dime a dozen so maybe my compiler linked in another than I thought. (The sketch is my adaptation of work i found on internet, but I think the original source is from Luca Dentella)

Note: In the UIPEternet librari it is possible to disable UDP and thus gain 5kb flash, remember though that if you use DHCP, you cannot disable UDP as the DHCP negotiation goes through UDP.

You could adapt the above program for a fixed address as follows:

Источник

consolacion/ENC28J60-MQTT

Use Git or checkout with SVN using the web URL.

Work fast with our official CLI. Learn more.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Use of an ENC28J60 shield (or module) with MQTT PubSub

The program uses the old ENC28J60 shield on a UNO or an ENC28J60 Module on say an Arduino proMini to send MQTT messages. The ENC28J60 uses a lot of memory so little is left for programming. Therefore this program uses short strings and only publishes MQTT, it does not subscribe to any MQTT. The UIPEthernet library can be found here: https://github.com/UIPEthernet/UIPEthernet

Some memory can be gained by setting the UIP_UDP_CONNS value in the UIPEthernet.h library to less than the default ‘4’ Go to your /../sketchfolder/libraries/UIPEthernet-master/utility/uipethernet-conf.h and open the uipethernet-conf.h file.

If you set UIP_CONF_UDP to ‘0’ you will save 5kB flash, by disabling UDP. However, if you use DHCP to connect to your router, you cannot disable UDP as the DHCP connection requires UDP.

There is a DHT11 attached to pin D3. The state of D4-D12 is published via MQTT The value of A0-A3 is also published via MQTT the value of A2 is made a float and shows how to send data from a battery that is attached

The deblanking function is there to strip spaces of the numbers being sent, so a receiving program can use them as numbers again.

The IP number as well as the MAC are also published, as is the uptime.

the publish delay is 20 seconds but can easily be adapted by the value of «PUBLISH_DELAY» The MAC address is made to be 00:01:02:03:04:05 but can easily be changed

Источник

MQTT with the ENC28J60 Ethershield

While playing with MQTT on various ESP8266’s, I started to wonder if maybe I could do something with an old ENC28j60 shield and module I still had laying around and actually hardly ever used.

For the youngsters: The ENC28J60 Ethernetshield was the first shield to connect the Arduino with the internet. The major drawback of the chip was that it was lacking a stack, that subsequently had to be constructed in software. As a result it was kinda memory hungry. The initial version was without an SD card slot, the later version had an SD card slot. There were two libraries available: The Ethercard and the Ethershield library. The UIPEthernet library came later.
As far as I could figure out, the PubSubClient library that is needed for MQTT doesnt work with the original Ethershield/EtherCard libraries. It does work with the UIPEthernet library though (extended fork here). The UIPEthernet library is a smart piece of coding that made programs written for the W5100 Ethernetshield suitable to be used with the ENC28J60 Shield, simply by changing the included library. Ofcourse there is a price to pay for this, namely more memory consumption. There is also an MQTT client for the ENC28J60/Atmega328 based Nanode. The Ethercard seems to work with the EthercardMQTT library.

Anyway, there still is enough memory to read a DHT11 sensor an analog port and some switches. In my case those were 3 door contacts. The PubSubClient is the original from Knolleary, though normally I am more a fan of the fork by Imroy. For this example I have used the Mosquitto public broker but ofcourse any broker can be used. I have installed the Mosquitto broker on a local raspberry and I found that a call to (“raspberrypi.local”,1883) does not work, using the local 192.168.1.xxx ip number does work though

Output in MQTT-spy

The program is rather ‘spartan’, to save space. Print statements have been removed or commented out after initial testing.

Just for completeness sake, this sketch takes about 77% of memory. This same sketch for the WIZ5100 based Ethernet shield, with the Ethernet.h library takes about 52% of memory. If you decide to adapt the sketch, be careful with altering the character strings. For instance, using the string “OPEN” 3 times is likely less memory consuming than having 3 different strings of the same or even shorter length. Obviously the ‘topic’ strings take a lot of space as well and if you were to shorten them to less meaningful names, you could add more sensors such as for instance a PIR sensor.

Should you copy the program from this blog page, you may copy ‘stray characters’ that you have to delete. You can also download it here.
An updated version is found here.

Freeing up memory

Should you really be pressed for memory, there is a way to free up about 5K of Flash: Go to your /../sketchfolder/libraries/UIPEthernet-master/utility/uipethernet-conf.h and open the uipethernet-conf.h file.
in that file you will see the following section:

If you set UIP_CONF_UDP to ‘0’ you will save 5kB flash, by disabling UDP. However, if you use DHCP to connect to your router, you cannot disable UDP as the DHCP connection requires UDP. In that case you still can gain a bit of memory by reducing the UIP_UDP_CONNS.
An example of using a fixed address is this:

A final warning… after I updated my libraries, including the Adafruit DHT library, I received an error on compiling this sketch. That disappeared when I returned it to version 1.2.1. I thought I was not using the Adafruit library but the Tillaert library, but DHT libraries come a dime a dozen so maybe my compiler linked in another than I thought.
(The main sketch is my adaptation of work I found on internet, but I think the original source is from Luca Dentella)

Источник

zuhryfayesz/Zuhry-MQTT-IoT

Use Git or checkout with SVN using the web URL.

Work fast with our official CLI. Learn more.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Control Arduino Nano MCU via MQTT protocol

Arduino Nano MCU status display in LCD

MCU connected LED on status

MCU connected LED off status

About

Arduino Home Automation Arduino. Interface Arduino Nano with ENC28J60 ethernet module to communicate over internet via MQTT protocol.

Источник

Arduino.ru

Шилд w5500 и enc28j60 и MQTT.

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Стоит задача отправить данные брокеру cloudmqtt.com (MQTT). В наличии w5500 и enc28j60.

Нужен рабочий пример скетча или совет куда копать. Может эти шилды не могут с такой задачей справиться?

Спасибо за ответы.

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Спасибо. Объмный код, 400 строк. Читаю 20% понимаю. э-Э-э-x :))

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Юзаю ардуину 5-6 недель. Кое как написал, что-то свое, но оно не работает. Смотрел чужой код здесь http://arduinolab.pw/index.php/2017/08/22/protokol-mqtt-kod-iz-video/ и здесь http://arduino.ru/forum/proekty/ethernet-vyklyuchatel-nagruzki-v-lokalnoi-seti. Не могу приконектится и передать данные брокеру. У брокера статистика показавает, что какие байты туда сюда идут, но в топик ничего не приходит. Код зациклился, без конекта, в строках 41 — 54.

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Какие байты идут, если коннект не проходит? Адрес DNS / маршрута по умолчанию 192.168.1.1 ?

Если есть в сети DHCP, то пробуйте запускать драйвер Wiznet как: Ethernet.begin(mac) , это поможет локализовать проблему. Так же может просто не совпадать версия MQTT протокола.

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Какие байты идут, если коннект не проходит? Адрес DNS / маршрута по умолчанию 192.168.1.1 ?

Если есть в сети DHCP, то пробуйте запускать драйвер Wiznet как: Ethernet.begin(mac) , это поможет локализовать проблему. Так же может просто не совпадать версия MQTT протокола.

В статистике пишет, что что-то пришло. Скрин сделал как выложить не знаю.

Пробовал по всякому проблема таже. Код:

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Самая первая ошибка — сразу из ардуины херачить космолёт.

Доступ к логам MQTT есть? Нет. С ардуины целевой хост запинговать можете, открытые порты проверить? Тоже нет. Как собираетесь сеть проверять? Или хотите, чтобы мы тут все руками поверх исходника поводили и написали, в которой строке 8 заменить на 56?

В локальной сети отладьте свой скетч, потом будете на внешние сервера лазить. Или траффик перехватывайте и анализируйте.

  • Войдите или зарегистрируйтесь, чтобы получить возможность отправлять комментарии

Самая первая ошибка — сразу из ардуины херачить космолёт.

Доступ к логам MQTT есть? Нет. С ардуины целевой хост запинговать можете, открытые порты проверить? Тоже нет. Как собираетесь сеть проверять? Или хотите, чтобы мы тут все руками поверх исходника поводили и написали, в которой строке 8 заменить на 56?

В локальной сети отладьте свой скетч, потом будете на внешние сервера лазить. Или траффик перехватывайте и анализируйте.

Спасибо за ответ. Недавно закончил проэкт в локалке: 2-ве Ардуино НАНО и одно УНО + W5500. 16*2 (6 в тестах) датчиков АМ2320 на НАНО(СЛЭЙВЫ) подключены к МАСТЕРУ УНО по I2C. В W5500 реализовал локальный сервер с таблицей данных. А связаться с Cloudmqtt никак не могу.

Это фрагмент статистики на Cloudmqtt: https://drive.google.com/open?id=1hoFXTcxiop7-0q9gd0tQOy-Hj0-DQrwx Судя по тому что ардуино отключена, а подклчение есть в статистике, в статистику попадает тот же вход в аккаунт.

Это логи. В них тоже сохраняется вход аккаунт. Ошибку подключения ардуино видно(подчеркнул) : https://drive.google.com/open?id=1w1m2jL_m2T1p7Z8GILeN8LZVlLQjUL_8

Думаю не правильно логинюсь. Может проблема с ID устройства, сочинил от потолка. Еще эта строка, как я понимаю, определяет адрес IP в локальной сети byte ip[] = < 192, 168, 31, 161 >; // IP адрес

Источник

Adblock
detector