Wemos d1 r2 обновление прошивки по wifi (ota) – arduino+

Обновляем скетч по воздуху

В процессе разработки кода для Arduino совместимых плат, очень часто возникает необходимость обновить прошивку в контроллере, очень часто сделать это проблематично, по той причине, что устройство уже собрано и дёргать туда-сюда шилдики и кучи проводов — утомляет и начинает раздражать.

Моей первой Arduino стал комплект деталей (собери сам) Freeduino Through-Hole, комплект по приезду был сразу же спаян и опробован, но в этом аналоге Arduino Diecimila не хватало одной приятной детали… а именно автоматического переключателя источника питания, в моем случае предлагалось перетыкивать перемычку на плате, что еще больше осложняло обновления скетча для моей мечты детства модели.

В этом посте я опишу как за 5 минут работы паяльником модифицировать XBee Shield для обновления скетча через беспроводной канал связи. Спроецировать данные изменения можно также и на другие аналоги XBee Shield без особых сложностей.

Начну с того, что у меня было два XBee Shield, различие было в том, что один из шилдиков имел разъем mini-usb и FTDI USB-Serial чип для прямого подключения XBee модуля к ПК, так что заморачиватся со сторонними USB-Serial шнурами мне не пришлось.

Как оказалось работать с модулями через этот шилдик очень удобно, RTS и DTR пины были разведены куда надо, прошивка обновлялась, конфиги заливались. Внимание! Если вы попытаетесь обновить прошивку, не подключив пины, RTS и DTR то модуль брикнется, но это поправимо.

Нужно лишь в настройках соединения X-CTU указать режим API работы с модулем и выполнить обновление firmware еще раз. И так приступим:

1. Модификация передающего модуля

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

Я использовал модули XBee не PRO версии и на моем шилдике остались не распаяны колодки под PRO модуль (он побольше процентов на 20), шаг между отверстиями этой колодки удачно совпадал с PLS разъёмом (это контакты типа «папа» втыкаймые в arduino), штырьки от которого уже давно пылились в коробке. Я откусил пару штырьков от основной «гребенки».

Согласно datasheet'у для XBee и XBee PRO выводы RTS и DIO3, располагаются на 16 и 17 пинах соответственно, что в нашей ситуации очень удобно. Впаиваем наши контакты в 16 и 17 отверстие на шилдике, а так же попутно выдёргиваем джампер (перемычку) из старого ненужно винта или материнской платы и замыкаем свежевпаянные контакты.

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

Переходим к настройкам самого модуля. Если вы хотя бы раз использовали XBee модули в своих поделках то скорее всего уже знакомы с программой X-CTU и её возможностями. О настройке с её помощью дальше и пойдет речь.

Первое, что нам нужно сделать, это подключить наш XBee модуль к компьютеру и проверить соединение. Если вы делаете это впервые то параметры будут следующими (COM порт разумеется следует выбрать свой):

После установки параметров нажимаем “Test / Query” и через секунду в ответ должны получить сообщение с серийным номером и моделью модуля.

Если этого не произошло — значит где то ошибка. Как вариант попробуйте поперебирать скорость порта (Baud).

Переходим во вкладку Modem Configuration и нажимаем Read для получения текущих настроек и версии прошивки модуля.

Первое значение, что мы изменим PAN ID. PAN ID состоит из 4 цифр в формате HEX и определят ID сети в которой будет работать данный модуль. PAN ID должен быть одинаковый как на приёмнике так и на передатчике. Так же рекомендуется не настраивать больше никаких модулей на этот ID во избежание конфликтов.

Следующим пунктом в настройках следует изменить скорость работы порта. Она должна соответствовать скорости необходимой для прошивки конкретной микросхемы ( так же есть альтернативные загрузчики повышающие скорость прошивки ). Для 168 чипа это 19200, а для 328p 57600.

Примите во внимание, что для работы с модулем в дальнейшем в скетч нужно внести поправки ( например если раньше вы использовали стандартную скорость 9600 ), изменить скорость работы с портом.Packetization Timeout — таймаут определяющий сколько ждать перед отправкой в эфир.

Может потребоваться значение больше чем 10 — подбирается индивидуально исходя из размеров скетча, 10=10кб скетч.Теперь устанавливаем пин D3 (Digital Input/Output) в положение 3-DI, что подразумевает что пин будет использоваться как цифровой вход.Устанавливаем параметр Digital IO change detect в FF. Так же можно указать вместо FF, 0x08.

Тогда мы конкретно укажем что изменения DI нужно слушать на D3 пине, но и так работает нормально.Теперь трансмиттер (передатчик) настроен на пересылку текущего статуса D3 пина на любые модемы в зоне досягаемости. Запишем изменения в наш модуль нажатием кнопки Write на верхней панели.

А так же стоит упомянуть о предсказуемых граблях пользователей Windows ( в MacOS и Linux это предусмотрено по умолчанию). Необходимо в настройках COM порта указать опцию Set RTS on close (в русской версии возможно другое название)Убедимся что галочка установлена и применяем настройки.

2. Модификация принимающего модуля

Модификацию по традиции начнём с железа, а именно спаяем в кучу ( пока что лучше на весу для дальнейшей отладки схемы) конденсатор, транзистор и резистор по следующей схеме:Reset signal from XBee — ведет напрямую к D3 пину. Reset to Arduino — напрямую к Reset пину на ардуине.

Должно получится нечто похожее на этоПовторю на всякий случай, не забудьте откорректировать скорость обмена в вашем проекте.

Теперь подключаем к компьютеру ресивер ( принимающий модуль ) и открываем уже знакомую X-CTU для установки следующих параметров PAN ID — Должен соответствовать передающему модулюInterface Data Rate — Аналогично должен совпадать с передатчикомPacketization Timeout — тоже как я понял аналогично передатчикуУстанавливаем пин D3 нашего приёмника 5-DO HIGH ( Digital Out Default High)I/O Output В Disabled. Для предотвращения попадания статусных сообщений в serial портИ в заключении устанавливаем I/O input address в FFFF — для приема I/O сообщений от всех вещающих. Можно так же указать адрес передатчика.Теперь запишем изменения в наш модуль нажатием кнопки Write. Рекомендую один раз настроить и сохранить профили для обоих модулей на своем компьютере во избежании путаницы в дальнейшем. Сверху Profile -> Save. Не забываем подключить все GND вместе и подключаем передающий модуль к компьютеру ( через переходник или шилдик ) и устанавливаем принимающий на целевую Arduino. Еще раз все проверяем, вдруг я ошибся или еще какая мелочь осталась где. Проверяем быстро все взглядом еще раз и можно пробовать! 🙂

Грабли которые были у меня: Скетч отказывался заливаться, хотя Arduino иногда перезагружалась, это ввело меня в ступор, но вскоре стало понятно что если быстро два раза нажать на Upload в IDE Arduino скетч успешно заливался хоть и не всегда ( виню Wifi и Blutooth коих вокруг очень много было ) По видимому копать стоит в сторону конденсатора (играться с объёмом ) Ну или на крайний случай править код IDE чтоб сама два раза RTS пин дёргала 🙂

Прошу прощение за сумбур, начинал писать сататью почти год назад, многое уже забыл, но все что хотел сказать сказал. Предложения и пожелания приветствуются. Неточности в статье или ошибки по традиции пишите в личку, надеюсь статья оказалась вам полезной.

Мою статью можно считать переводом этой

я лишь немного дополнил и приукрасил где мог.

Мой вопрос в Q&A тут и спасибо ответившему djmorgan

Источник: https://habr.com/post/126539/

ArduinoOTA: Wireless Update (OTA) from the Arduino IDE of ESP8266 Programs • DIY Projects

The ArduinoOTA library is a library that allows to update the Arduino program (and ESP3226, ESP32) wirelessly in Wi-Fi. It is an essential library when developing connected objects.

It allows to update the program without having to disassemble the microcontroller (Arduino, ESP8266, ESP32) to connect it to his computer. This library was originally developed to update the Arduino programs, it is perfectly supported by the ESP8266 and ESP32.

For this tutorial, we will only address the case of ESP8266.

The ArduinoOTA library is integrated into the ESP8266 library. There is nothing more to install. If you’re new to ESP, here’s how to install the ESP library and support. Open the preferences (from the Arduino menu) and add to the list of packages this one

http://arduino.esp8266.com/stable/package_esp8266com_index.json

Then go to the map manager and look for esp8266, then click install.

After installation, new examples have been added to the sample menu. Select your ESP8266 card to display the available samples. Open the BasicOTA example in the ArduinoOTA submenu

This program contains everything you need to manage wireless upgrade in your ESP projects.

Читайте также:  Parrot ar.drone 2.0: вторая версия "легенды" - arduino+

#include
#include
#include
#include const char* ssid = “……….”;
const char* password = “……….”; void setup() { Serial.begin(115200); Serial.println(“Booting”); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); while (WiFi.waitForConnectResult() != WL_CONNECTED) { Serial.println(“Connection Failed! Rebooting…”); delay(5000); ESP.restart(); } // Port defaults to 8266 // ArduinoOTA.setPort(8266); // Hostname defaults to esp8266-[ChipID] ArduinoOTA.setHostname(“Demo OTA ESP8266″); // No authentication by default ArduinoOTA.setPassword((const char *)”123”); ArduinoOTA.onStart([]() { Serial.println(“Start”); }); ArduinoOTA.onEnd([]() { Serial.println(”
End”); }); ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { Serial.printf(“Progress: %u%%
“, (progress / (total / 100))); }); ArduinoOTA.onError([](ota_error_t error) { Serial.printf(“Error[%u]: “, error); if (error == OTA_AUTH_ERROR) Serial.println(“Auth Failed”); else if (error == OTA_BEGIN_ERROR) Serial.println(“Begin Failed”); else if (error == OTA_CONNECT_ERROR) Serial.println(“Connect Failed”); else if (error == OTA_RECEIVE_ERROR) Serial.println(“Receive Failed”); else if (error == OTA_END_ERROR) Serial.println(“End Failed”); }); ArduinoOTA.begin(); Serial.println(“Ready”); Serial.print(“IP address: “); Serial.println(WiFi.localIP());
} void loop() { ArduinoOTA.handle();
}

Before reversing the program, change the ssid variables (Wi-Fi network to which to connect) and password (password).

Here, the program uses the ESP8266WiFi library to connect to the network. You can also use the WiFiManager library presented earlier.

Once the connection is established, it is possible to define additional (optional) parameters:

  • SetPort: by default the communication port is 8266. It is not very useful to change it unless it is already in use. For example, for a project integrating UDP communication.
  • SetHostname: This is probably the most important option. It allows you to assign a name to the ESP8266. If you have a lot of objects on your network, it will be much easier to identify it by name than by an identifier built automatically from the serial number.
  • SetPassword: used to request a password from the Arduino IDE before running an update. Practice if you work at several or in a school.

There are four other ways to connect treatments in the following cases:

  • OnStart: code to run when the update is started
  • OnEnd: idem at the end
  • OnProgress: during the progress
  • OnError: and on error

You will not need to add treatments in most cases. In particular, these functions allow us to remain informed of the smooth running of operations.

At the end of the setup, once all functions have been defined, start the wireless update support by calling the begin () method.

Finally, for everything to work, it is necessary to call the ArduinoOTA.handle () method in the loop () loop.

Upload the program and open the Terminal to verify that the ESP8266 is properly connected to the Wi-Fi network.

The Arduino IDE automatically detects devices that support remote update. They are added to the list of ports in a new section called Network ports.

To update the program, simply select the ESP as the port instead of the usual serial port. Then upload the program as usual. Here, as a password is required, an input window appears in the IDE. It is requested only once

The remote update (or failure) of the remote update can be tracked directly from the Arduino IDE.

It is not possible to open the serial monitor with wireless setup. A small Web interface is required. Read this tutorial to learn how to add a Web server and HTML interface to an ESP8266 project. To go further, here is a series of articles dealing with the subject

  • Homy, iOS / Android home automation application to control a server or DIY connected objects 20 December 2018
  • Xiaomi Mijia Honeywell Smoke Detector Test with Domoticz, Emergency Notification with PushOver 13 September 2018
  • Xiaomi Aqara now compatible with Apple Homekit, new Vibration Sensor and Honeywell Natural Gas Detector 11 September 2018
  • #Test Zigbee2MQTT gateway. Part 2, include Xiaomi Aqara or Mijia accessories to Domoticz with Node-RED [update] 10 September 2018
  • #Test Zigbee2MQTT project, hack of the Xiaomo Aqara Smart Home Gateway. Part 1: assembly, demo with Node-RED, 3D printed case [update] 7 September 2018
  • The diyprojects application also available on iOS and Android, first mobile project with Ionic 3 5 September 2018
  • ESP8266, Deep Sleep mode test, wake up with a PIR motion detector 27 June 2018
  • HC-SR04 (ultrasound) vs Sharp GP2Y0A02YK0F (IR) vs VL53L0X (Laser), which solution to choose for distance measurement with Arduino or Raspberry Pi 18 June 2018
  • Test and Calibrate Sharp GP2Y0A02YK0F Asian Clone proximity Sensor 15 June 2018
  • Install Grafana on macOS and Raspbian for Raspberry Pi. Example dashboard for connected object MySensors with Node-RED and InfluxDB [Update] 11 June 2018
  • Install InfluxDB on Raspberry Pi, Windows, macOS. Discovery of the Shell. Create a database, retention [Update] 11 June 2018
  • New Raspberry Pi 3 Model B+ 2018 @1.4GHz, Gigabit Ethernet, Ethernet POE Daughter Card, Flash Sale at $49.99 on Gearbest 1 June 2018
  • Retrogaming Retropie Mini Console on Raspberry Pi 3 with 3.5 ” HDMI LCD Touch Screen 1 June 2018
  • #Test LCD 3.5” HDMI touch screen (via GPIO) with acrylic case for Raspberry Pi 3 under Raspbian (480×320 to 1920×1080 pixels) 31 May 2018
  • Gateway RFLink with RobotDyn Arduino Mega 2560 Pro Mini and 3D printed case 6 April 2018

Источник: https://diyprojects.io/arduinoota-wireless-update-ota-arduino-ide-esp8266-programs/

Arduino Tutorial: ESP8266 OTA. Update the WeMOS D1 Over the Air (OTA)

This demonstration will be based on the blink example, which makes connecting the components required for this project very easy. Connect the components as shown in the schematics diagram below.

Preparations for OTA Update

To be able to use the OTA update, we need to first and foremost download and install Python 2.7 on our computer. Python 2.7 will install some of the files that will enable the serial port which we will use later on for the OTA update.

With python installed, we then open an instance of the Arduino IDE. It is important that the version of the IDE being used be up to date.

It is also important to setup the Wemos D1 board for programming with the Arduino IDE and this was covered in one of my previous tutorial which can be found at this link.

Over the Air Update uses the ArduinoOTA library which makes it easy to update the code on Arduino boards ( and the ESP8266 based boards) wirelessly over WiFi.

This library comes preloaded for the ESP8266 boards and as soon as the board is installed via the board manager, the library and its examples get installed on the Arduino IDE.

So next, we load the BasicOTA program which will now be available Under File -> Examples -> ArduinoOTA.

For the OTA to work, the system must be able to connect to a WiFi so we need to change the SSID and password in the BasicOTA code to match the credentials of our WiFi Access. with this done, we can select the board and upload the code to it.

After few minutes the board should connect to the specified WiFi access and we should see the esp8266-ota port show up on the Arduino IDE and we can then select it so as to upload another code(say blink for example) to the board.

If the esp8266-ota port doesn’t show up, restart the Arduino IDE and it should then come up.

The basicOTA program contains commands and functions which induces the Wemos D1 board to create an OTA port through which code can then be uploaded to the board wirelessly, but the downside to this basic program is that as soon as the code as we upload another code using the OTA means, we will not be able to upload code to the board using the OTA medium again as the commands needed to create the OTA port will no longer be available in the flash memory of the microcontroller.

To overcome this, we need to include some part of the Arduino OTA functions in all the codes will send to the wemos D1 via OTA and to demonstrate this, I created a sample sketch which can be edited to suit the needs of your project.

Code

In order to update the program over and over again wirelessly, we have to include some of the commands from the BasicOTA code in our code.

Читайте также:  Покупаем на алиэкспресс: подробная инструкция - arduino+

So as an example, I updated the ESP8266 blink example code to include the OTA commands.

This will give us the ability to update the code on the Wemos D1 wirelessly, as many times as we want, as the program will connect the WiFi network at startup and create the OTA port.

To do a brief explanation of the code, as usual, the first thing we do is include all the libraries which are needed to achieve our goal. Do not that all these libraries will be included in the basicOTA update.

#include #include #include #include

Next, we define the credentials of the WiFi through which we want to perform the OTA; the SSID and the password.

const char* ssid = “yourssid”; const char* password = “yourpassword”;

Next, we move to the void setup function. This is where the bulk of work is done. We start out by setting the pin mode of the pin to which the LED is connected as output. After this, we set the mode of the wifi and instruct it the board to join the WiFi network.

void setup() { pinMode(D10, OUTPUT); Serial.begin(115200); Serial.println(“Booting”); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); while (WiFi.waitForConnectResult() != WL_CONNECTED) { Serial.println(“Connection Failed! Rebooting…”); delay(5000); ESP.restart(); }

Next, we create the data to be displayed so we can be aware of the status of the OTA communication, so as to know when the system is running or when there is an error. Next, we start the OTA communication displaying the Ip address for it.

ArduinoOTA.onStart([]() { Serial.println(“Start”); }); ArduinoOTA.onEnd([]() { Serial.println(”
End”); }); ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { Serial.printf(“Progress: %u%%
“, (progress / (total / 100))); }); ArduinoOTA.onError([](ota_error_t error) { Serial.printf(“Error[%u]: “, error); if (error == OTA_AUTH_ERROR) Serial.println(“Auth Failed”); else if (error == OTA_BEGIN_ERROR) Serial.println(“Begin Failed”); else if (error == OTA_CONNECT_ERROR) Serial.println(“Connect Failed”); else if (error == OTA_RECEIVE_ERROR) Serial.println(“Receive Failed”); else if (error == OTA_END_ERROR) Serial.println(“End Failed”); }); ArduinoOTA.begin(); Serial.println(“Ready”); Serial.print(“IP address: “); Serial.println(WiFi.localIP());

To cap the code, we move to the void loop function. The code for this function is basic as all that needs to be done is read the status of the OTA and perform the normal action for which the code was created which is to blink the LED at a particular rate. This could be anything else in your own code, it could be an update that changes the behavior of the project totally.

void loop() { ArduinoOTA.handle(); digitalWrite(D10, HIGH); delay(500); digitalWrite(D10, LOW); delay(500); }

That’s it! If you need to update your programs wirelessly from now on, all you will need to do is to add a few lines of code to it and you are ready.

Источник: https://educ8s.tv/esp8266-ota-wemos-d1/

Wemos D1 R2 WiFi на базе ESP8266, плата Arduino

Добавить компанию на Zakupka.com

+380 (93) 679-10-14показать+380 (93) 679-10-14

На все товары магазина возможны персональные скидки, в зависимости от стоимости заказа и покупаемоего товара.

Wemos D1 R2 WiFi на базе ESP8266 – это микроконтроллер и WiFi модуль одновременно. Wemos D1 R2 используется для программирования, контроля, управления различных проектов, в которых нужно использование микроконтроллеров или может подключаться к программному обеспечению, выполняемому на компьютере.

Контроллер совместим со всеми платами расширения форм фактора Arduino UNO. Контроллер поставляется на плате типоразмера Arduino UNO. В комплекте с платой идет три колодки штыревых контактов, по 20 контактов каждый, с расстоянием между контактами 2,54 мм.

Каждый вывод контроллера продублирован на плате клеммой для возможности припаять штыревые контакты. Штыревые контакты перед пайкой нужно разделить на соответствующие по количеству клемм части. На плате используется всего 40 клемм, т.е. еще 20 штыревых контактов у Вас останутся, как запасные.

Для использования Wemos D1 R2 нужно подключить его к USB порту компьютера с помощью кабеля USB тип A – microUSB тип B (в комплект поставки не входит). Операционная система компьютера определит устройство как USB Serial CH340. Если автоматически драйвера не установились – это нужно сделать вручную.

После подачи питания на плате контроллера начнет гореть синий светодиод, обозначенный ON (индикация питания), также будет гореть синий светодиод, обозначенный SCK (индикация шины I2C). На плате контроллера находится кнопка сброса параметров или перезагрузки RESET.

После подключения контроллера к компьютеру нужно скачать и установить программное обеспечение для работы. Wemos D1 R2 поставляется с уже загруженной на ESP8266 прошивкой NodeMCU. Данная прошивка воспринимает код, написанный на языке программирования LUA. Но также есть возможность работать с более привычным Arduino IDE. Для этого нужно сделать ряд  манипуляций.

В конечном итоге Вы получите контроллер размера Arduino UNO с тактовой частотой 80 – 160 МГц и 4 Мбайт Flash памяти, что намного больше, чем в Arduino контроллерах. Предусмотрено три варианта использования в беспроводном режиме: Клиент (STA), Точка доступа (AP), Клиент+Точка доступа (STA+AP).

Wemos D1 mini оснащен PCB антенной, при этом расстояние приема/передачи в идеальных условиях 400 м.

Контроллер Wemos D1 R2 поддерживает функцию OTA, так называемое, обновление прошивки «по воздуху».

Контроллер Wemos D1 R2 имеет один аналоговый и одиннадцать цифровых входов/выходов общего назначения для ввода или вывода информации и управляющих сигналов:Аналоговый вход A0 имеет встроенный АЦП (аналого-цифровой преобразователь).

Максимальное входное напряжение аналогового входа A0 3,3В! Wemos D1 R2 может быть запитан от USB порта компьютера, от адаптера питания, от внешнего источника питания – тип источника выбирается автоматически.

Адаптер питания подключается посредством штекера диаметр – 2,1 мм с центральным положительным полюсом. Выходное напряжение блока питания может быть от 5 до 24В. Внешнее питание может подаваться от блока питания или батареи. Такое питание подключаются к выводам платы, обозначенным GND и VIN.

Разъемы питания:

  • VIN – вход используется для подачи питания от внешнего источника и как источник питания, если есть питание от блока питания;
  • 5V – выходное напряжение напрямую от стабилизатора напряжения; подавать на этот вывод входное напряжение нельзя;
  • 3.3V – напряжение на выводе 3,3В генерируемое встроенным регулятором на плате.

На плате есть дополнительная клеммная колодка для расширения возможностей платы. На колодку продублированы выводы: 3.3V, RX, TX, GND/3.3V, SCL, SDA, GND.

Особенность при работе с Wemos D1 R2 – вывод в терминал может осуществляться с мусором либо постоянно, либо при начале отображения.

Иногда все начинает работать само по себе, иногда требуется поиграть со скоростями последовательного порта (в окне терминала и в скетче), дабы подобрать скорость, которая будет работать именно у Вас.

Внимание: WeMos D1 R2 хоть и Arduino совместимая плата, но ожидать, что на ней будут нормально работать любые скетчи от Arduino не стоит.

Характеристики:

модель: WeMos D1 R2 V2.1.0; типоразмер: Arduino UNO; собран на чипе: ESP8266; Flash память: 4Мбайт; тактовая частота: 80 – 160 МГц; USB – UART: CH340G; расстояние приема/передачи, в идеальных условиях: 400 м; функция: OTA; встроенная прошивка: NodeMCU; размеры: 69 х 53 х 12 мм;

вес: 25 г.

Комплект поставки:

  • Wemos D1 R2 WiFi на базе ESP8266, плата Arduino;
  • штыревые контакты 2,54 мм – 3шт.

Материалы и файлы для работы с контроллером.
Статья.

Источник: http://freedelivery.zakupka.com/p/347785696-wemos-d1-r2-wifi-na-baze-esp8266-plata-arduino/

FirmwareUpdater

Firmware and certificates Updater

This tutorial will guide you in the process of updating the firmware or loading certificates on your MKR1000 board or WiFi Shield 101.

If the Check WiFi101 Firmware Version tells you that you may have issues because the firmware and library versions do not match, here is the solution to align them.

Hardware required

  • MKR1000 or WiFi Shield 101 connected to an Arduino or Genuino board

Circuit

The board should be connected to the USB port of the computer ready with Arduino Software (IDE) 1.6.10 or later.

Firmware update procedure

Important note:

The 19.5.2 firmware is only available for model B of the WINC1500, this is used in the MKR1000 board. Unfortunately, the WiFi101 shield uses model A, which Atmel has stopped supporting, so there is no 19.5.2 firmware release for it, 19.4.4 will be the latest firmware version that is compatible.

To simplify the process, we have prepared a specific sketch – this FirmwareUpdater – that you must load on the host board (either the one with the shield plugged in, or the MKR1000 itself) and an easy to use plug-in available in Arduino Software (IDE) 1.6.10 onwards.

The “FirmwareUpdater” sketch is available in Examples -> WiFi101

Читайте также:  Педагог дополнительного образования (робототехника, автомоделизм) - arduino+

Upload the sketch and keep the board (either the one with the shield plugged in, or the MKR1000 itself) connected to the computer. Once done, open the plug-in that is available in the tools menu.

Your board should be in the list of the available serial ports. If not, please check that it is properly configured in the Tools menu.

To update the firmware you should choose the right typer of board. You can find your model looking at the WiFi module: te first line in the sticker or the last line of the silk print on the right side of the PCB shows the microcontroller model. It can be either MR210PA or MR510PB and the last letter shows yor model accordingly.

Choose in the dropdown list the model corresponding to your unit and proceed clicking on the Update Firmware button. A bar at the bottom will show you the progress of the procedure that includes erasing, writing and verifying of the firmware. At the end you get a clear notice of the successfull operation.

Certificate uploading

With the same procedure, you may load root certificates on the WiFi module to access securely specific websites. Your board must be running the FirmwareUpdater sketch to work .

The root certificates are issued by a limited number of certification authorities, but it is difficult to know which site is using which authority. To ease your life, we allow you to specify directly the URL to which you need to connect securely, leaving to us the task to download the root certificate.

The list you are building is not saved from one session to the next one. It might happen that a few websites share the same root certificate. You don't have to worry about this as we take care of it.

The space available on your WiFi module to store the certificates is limited to around 10 certificates that, being issued by a limited number of authorities, should be more than enough for the average projects.

The procedure starts connecting your board (either the one with the shield plugged in, or the MKR1000 itself) to your computer and selecting it from the Tools menu of the Arduino Software (IDE). Load the FirmwareUpdater on the board and launch the WiFi 101 Firmware Updater from Tools and go to the third section of the interface.

There you find on the left an empty list and on the right the buttons to add or remove the URL from which you want to download the root certificates. The URL should be exactly the one to which you need to connect.

Add all the websites' URLs needed and then procceed with the uploading process. Please remember that you erase all the existing certificates when you load a new set.

Press the ''Upload Certificates to WiFi module” and wait for the confirmation message.

Code

When you load the sketch on the board, it prepares the communication betwen the plug-in and the WiFi chip. It opens up the communication through the serial port to the WiFi module hosted on the board. It is necessary to perform all the procedures managed by the Firmware Upgrader Plugin. Everything will be managed by the plug-in, but it is important to upload this sketch first.

The complete sketch is below :

/*   FirmwareUpdate.h – Firmware Updater for WiFi101 / WINC1500.   Copyright (c) 2015 Arduino LLC.  All right reserved.   This library is free software; you can redistribute it and/or   modify it under the terms of the GNU Lesser General Public   License as published by the Free Software Foundation; either   version 2.1 of the License, or (at your option) any later version.   This library is distributed in the hope that it will be useful,   but WITHOUT ANY WARRANTY; without even the implied warranty of   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU   Lesser General Public License for more details.   You should have received a copy of the GNU Lesser General Public   License along with this library; if not, write to the Free Software   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

*/

#include<\p>
#include

typedef struct __attribute__((__packed__)) {

  uint8_t command;
  uint32_t address;
  uint32_t arg1;
  uint16_t payloadLength;

  // payloadLenght bytes of data follows…

} UartPacket;

static const int MAX_PAYLOAD_SIZE = 1024;

#define CMD_READ_FLASH        0x01

#define CMD_WRITE_FLASH       0x02
#define CMD_ERASE_FLASH       0x03
#define CMD_MAX_PAYLOAD_SIZE  0x50
#define CMD_HELLO             0x99

void setup() {

  Serial.begin(115200);

  nm_bsp_init();

  if (m2m_wifi_download_mode() != M2M_SUCCESS) {
    Serial.println(F(“Failed to put the WiFi module in download mode”));
    while (true)
      ;
  }
}

void receivePacket(UartPacket *pkt, uint8_t *payload) {

  // Read command
  uint8_t *p = reinterpret_cast(pkt);
  uint16_t l = sizeof(UartPacket);
  while (l > 0) {
    int c = Serial.read();
    if (c == -1)
      continue;
    *p++ = c;
    l–;
  }

  // Convert parameters from network byte order to cpu byte order

  pkt->address = fromNetwork32(pkt->address);
  pkt->arg1 = fromNetwork32(pkt->arg1);
  pkt->payloadLength = fromNetwork16(pkt->payloadLength);

  // Read payload

  l = pkt->payloadLength;
  while (l > 0) {
    int c = Serial.read();
    if (c == -1)
      continue;
    *payload++ = c;
    l–;
  }
}

// Allocated statically so the compiler can tell us

// about the amount of used RAM
static UartPacket pkt;
static uint8_t payload[MAX_PAYLOAD_SIZE];

void loop() {

  receivePacket(&pkt, payload);

  if (pkt.command == CMD_HELLO) {

    if (pkt.address == 0x11223344 && pkt.arg1 == 0x55667788)
      Serial.print(“v10000”);
  }

  if (pkt.command == CMD_MAX_PAYLOAD_SIZE) {

    uint16_t res = toNetwork16(MAX_PAYLOAD_SIZE);
    Serial.write(reinterpret_cast(&res), sizeof(res));
  }

  if (pkt.command == CMD_READ_FLASH) {

    uint32_t address = pkt.address;
    uint32_t len = pkt.arg1;
    if (spi_flash_read(payload, address, len) != M2M_SUCCESS) {
      Serial.println(“ER”);
    } else {
      Serial.write(payload, len);
      Serial.print(“OK”);
    }
  }

  if (pkt.command == CMD_WRITE_FLASH) {

    uint32_t address = pkt.address;
    uint32_t len = pkt.payloadLength;
    if (spi_flash_write(payload, address, len) != M2M_SUCCESS) {
      Serial.print(“ER”);
    } else {
      Serial.print(“OK”);
    }
  }

  if (pkt.command == CMD_ERASE_FLASH) {

    uint32_t address = pkt.address;
    uint32_t len = pkt.arg1;
    if (spi_flash_erase(address, len) != M2M_SUCCESS) {
      Serial.print(“ER”);
    } else {
      Serial.print(“OK”);
    }
  }
}

If you are NOT opening the FirmwareUpdater from the examples available in the Arduino Software (IDE) as described in the paragraphs above and wish to copy and paste the code from this tutorial, you need to create another TAB in your sketch and add the Endianess.ino listed below.

/*   Endianess.ino – Network byte order conversion functions.   Copyright (c) 2015 Arduino LLC.  All right reserved.   This library is free software; you can redistribute it and/or   modify it under the terms of the GNU Lesser General Public   License as published by the Free Software Foundation; either   version 2.1 of the License, or (at your option) any later version.   This library is distributed in the hope that it will be useful,   but WITHOUT ANY WARRANTY; without even the implied warranty of   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU   Lesser General Public License for more details.   You should have received a copy of the GNU Lesser General Public   License along with this library; if not, write to the Free Software   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

*/

bool isBigEndian() {

  uint32_t test = 0x11223344;
  uint8_t *pTest = reinterpret_cast(&test);
  return pTest[0] == 0x11;
}

uint32_t fromNetwork32(uint32_t from) {

  static const bool be = isBigEndian();
  if (be) {
    return from;
  } else {
    uint8_t *pFrom = reinterpret_cast(&from);
    uint32_t to;
    to = pFrom[0]; to

Источник: https://www.arduino.cc/en/Tutorial/FirmwareUpdater

Ссылка на основную публикацию
Adblock
detector