Quantcast
Channel: Short notes on everything
Viewing all 66 articles
Browse latest View live

Wireless sensor/actuator network with CC430 RF SoC.

$
0
0

The idea 

This piece of hardware originated as an entry for Texas Instruments Analog Design Contest'13 (come check it out, it's an annual event and YOU could score some great prizes).

The main idea of the project was to create a wireless network of sensors and actuators (grouped into arbitrary nodes) for data acquisition and control in the automated greenhouse. All data is collected from sensors and sent to the gateway node connected to web server, where processing of the obtained information takes place. Commands to actuators follow the same route in the opposite direction. This structure allows flexible and versatile solution for automation with modular approach that can be deployed quickly to any greenhouse.


Fig. 1 - 2. Potential victim of automation.

A place to deploy the system was fortunately found in my own university, where senior students built this (fig. 1, 2) hydroponic greenhouse to test various automation solutions (if memory serves me, the last thing that ran this greenhouse was PLC, hence the relays on the bottom).


Some theory and planning

A wireless sensor network (WSN) consists of spatially distributed autonomous sensors and is used to monitor physical or environmental conditions, such as temperature, sound, pressure, etc. and to cooperatively pass their data through the network to a main location. The more modern networks are bi-directional, also enabling control of sensor activity. The development of wireless sensor networks was motivated by military applications such as battlefield surveillance; today such networks are used in many industrial and consumer applications, such as industrial process monitoring and control, machine health monitoring, and so on. (From Wikipedia, the free encyclopedia)

The general diagram of the network that I've devised is shown in the figure below:
 
Fig. 3. Schematic diagram of the system.

Each sensor/actuator is equipped with a microcontroller that uniquely identifies this sensor in I2C network and allows the user to easily plug them to nodes in any order and any quantity (not exceeding the I2C address space size, obviously). The bidirectional link is established via radio with the gateway node, which sends the commands to nodes and receives data from sensors relaying it to the server. The server could be any single-board computer (like Rappberry Pi) or even an actual PC running the application which handles the link to gateway node.

Hardware

Each node is equipped with CC430F5137 RF SoC, which is responsible for RF link between the nodes and connection to I2C network of nodes. Frequency was chosen to be 433MHz, that is, an unlicensed frequency for ITU Region 1. The schematics of each node is shown below:
Fig. 4. Schematics of WSN node built around CC430 RF SoC.
The balun circuit was taken from TI app notes and is designed specifically for reception and transmission of 433MHz radio waves. Programming of the board is done via Spy Bi-Wire interface (J2) inherent to all microcontrollers of MSP430 series. J3 connects the node to its sensors and actuators (you'll see later how a bus connection allows to use only one connector to join virtually unlimited number of sensors/actuators).
Each sensor/actuator module is comprised of MSP430G2230 uC and the sensing element itself. Figures 5 to 8 are the schematics of sensor/actuator modules already implemented:
Fig. 5. Mains switching module (BT139 TRIAC + MOC3041 driver).

Fig. 6.Air temperature and humidity sensor (DHT22).

Fig. 7. Light intensity sensor (Merely a CdS photoresistor).

Fig. 8. Water temperature sensor (DS18B20 in waterproof enclosure).
System architecture provides an opportunity to integrate sensing and actuating modules alike into the node. This simplifies the management of the system as well as provides a way to organize units with similar purposes to the same node (e.g. temperature sensor with the heater relay, salinity sensor with water pump relay).

Results


Here are some pictures of assembled PCBs taken with my potato:

Physical manifestation of a WSN node.

Even more of them!

Node connected to mains swithing modules

Mains switch (BT139 TRIAC + MOC3041)

Left to right: water temp. module (with the sensor sticking from below), light int. sensor, air temp. and humidity sensor.

Air temperature and humidity sensor (DHT22).

Light intensity sensor (CdS photocell).

Water temperature sensor (DS18B20).

Final showdown - flourishing(ish) greenhouse.

What's yet to be done.

I'm planning to develop this project and further improve it.
For now, the project requires firmware for microcontrollers that will realize mesh network and software for the server. The list of improvement include:
1)    Adding a miniature energy harvesting system to each node, making it completely wireless and autonomous. The energy will be collected from solar cells and stored in supercapacitors. The most suitable integral solution for this is, probably, BQ25504.
2)    Development of PCBs with AC switches (relays or TRIACs). Those will make it an actual control system, enabling us not only to get data from sensors but also to control pumps etc. Done shortly after the project was submitted.

Беспроводная сеть сенсоров/исполнительных устройств на основе систем-на-чипе CC430 с радиомодулем.

$
0
0

Задумка

Этот проект возник из другого проекта, с которым я участвовал в конкурсе Texas Instruments Analog Design Contest'13 (советую посмотреть на информацию по ссылке, ведь именно ТЫ, мой дорогой гость, можешь выиграть классные призы в этом конкурсе). 

Основная идея проекта заключалась в создании беспроводной сети датчиков и исполнительных устройств (ИУ), сгруппированных в узлы произвольной комплектации для сбора данных и управления в автоматизированной теплице. Все данные собираются с датчиков и отправляются в узел-шлюз, который подключен к веб-серверу, в котором происходит обработка полученной информации. Команды на исполнительные устройства следуют по тому же маршруту, только в обратном направлении. Эта структура представляет собой гибкое и универсальное решение для автоматизации с модульным подходом , которое может быть быстро развернуто в любой теплице (да и вообще в любом объекте автоматизации).

Рис. 1 - 2. Потенциальная жертва автоматизации.

Место дляразвертывания системы, к счастью, нашлосьвмоем университете, где студенты старших курсов давнособрали вотэту(рис.1, 2)гидропонную теплицу для тестирования разных управляющих систем(еслимне не изменяет память, последнее, на чем крутилась этаоранжерея,былПЛК, оттуда в нижней части и остались реле).

Немного теории и планирование

Беспроводная сенсорная сеть — распределённая, самоорганизующаяся сеть множества датчиков (сенсоров) и исполнительных устройств, объединенных между собой посредством радиоканала. Область покрытия подобной сети может составлять от нескольких метров до нескольких километров за счёт способности ретрансляции сообщений от одного элемента к другому.

Беспроводные сенсорные сети состоят из миниатюрных вычислительных устройств — узлов, снабжённых сенсорами (датчиками температуры, давления, освещенности, уровня вибрации, местоположения и т. п.) и трансиверами, работающими в заданном радиодиапазоне. Гибкая архитектура, снижение затрат при монтаже выделяют беспроводные сети интеллектуальных датчиков среди других беспроводных и проводных интерфейсов передачи данных, особенно когда речь идет о большом количестве соединенных между собой устройств. Постоянное снижение стоимости беспроводных решений, повышение их эксплуатационных параметров позволяют постепенно переориентироваться с проводных решений в системах сбора телеметрических данных, средств дистанционной диагностики, обмена информации. «Сенсорная сеть» является сегодня устоявшимся термином (англ. Sensor Networks), обозначающим распределенную, самоорганизующуюся, устойчивую к отказу отдельных элементов сеть из необслуживаемых и не требующих специальной установки устройств. Каждый узел сенсорной сети может содержать различные датчики для контроля внешней среды, микрокомпьютер и радиоприемопередатчик. Это позволяет устройству проводить измерения, самостоятельно проводить начальную обработку данных и поддерживать связь с внешней информационной системой. (Материал из Википедии, свободной энциклопедии)

Общая схемасетиразработанноймной, показанана рисунке ниже:
 
Рис. 3. Схема системы.

Каждый датчик/ИУоснащенмикроконтроллером, который уникально идентифицируетэтот датчиквI2Cсети ипозволяет пользователюлегкоподключить ихк узламв любом порядкеилюбом количестве(не болееразмераадресного пространстваI2C, очевидно). Двунаправленнаясвязь устанавливаетсячерезрадиомодульсшлюзовым узлом, который посылает команды дляузлови принимает данные отдатчиковдля ретрансляцииихна сервер. Серверможет быть любымодноплатнымкомпьютер(например,RaspberryPi) или дажеобыкновенный стационарныйкомпьютер , на котором работаетприложение, отвечающее за общение с шлюзовым узлом.

Аппаратная структура

Каждый узелснабженчипом CC430F5137с радиомодулем, который отвечает забеспроводнуюсвязьмеждуузлами и заподключение ксети I2C.Частотабыла выбрана433 МГц, т.к. это нелицензируемаячастота длярегиона 1 ITU. Схема каждого узлапоказана ниже.:
Рис. 4. Схема узла беспроводной сети на CC430.
Схема балунабыла взята из напрямую из аппноута TIи предназначена специальнодля оптимального приема и передачирадиоволн на частоте433 МГц. Программированиеосуществляется черезинтерфейсSpyBi-Wire (J2), имеющийся у всехмикроконтроллеровсерииMSP430. J3соединяетузелс егодатчиками и исполнительными устройствами(далее вы увидите, как соединениешиной позволяетиспользовать только одинразъем дляприсоединения практически неограниченного количествадатчиков/исполнительных устройств).

Каждый модульдатчиков/исполнительных устройствсостоит измикроконтроллера MSP430G2230 
и обвязки. Иллюстрацииот 5 до 8являютсясхемамимодулейдатчиков/исполнительныхустройств:

Рис. 5. Модуль коммутации сети переменного тока (симистор BT139 + драйвер MOC3041).

Рис. 6. Датчик температуры и влажности воды (DHT22).

Рис. 7. Датчик интенсивности света (обычный фоторезистор).

Рис. 8. Датчик температуры воды (DS18B20 в водонепроницаемом корпусе).
Архитектура системыобеспечиваетвозможность интеграцииизмерения данных сенсорами иуправления исполнительнымиустройствами в 1узел. Это упрощаетуправление системой, а также предоставляет возможностьсобратьмодулиспохожим назначениемна один узел(например,датчик температурыскоммутатором нагревателя, датчик соленостискоммутаторомводяного насоса).

Результаты


Несколько фотографий готовых печатных плат снятых на мобилу:

Физическое воплощение узла беспроводной сети.

И он даже не один!

Узел соединенный с коммутационными модулями.

Модуль коммутации сети переменного тока (симистор BT139 + драйвер MOC3041).

Слева направо: датчик темп. воды (сенсор торчит снизу), датчик освещенности, датчик температуры и влажности воздуха.

Датчик температуры и влажности воды (DHT22).

Датчик интенсивности света (фоторезистор).

Датчик температуры воды (DS18B20).

Финальное фото - как бы цветущая теплица.

Что стоит доделать.

Я планируюразвивать этот проекти улучшить его.

В настоящее время требуется написатьпрошивкудля микроконтроллеров, которые будутреализоватьячеистую сетьи программное обеспечение длясервера. Списокулучшенийвключает в себя:

1)Добавлениеминиатюрнойсистемысбора энергиина каждый узел, что сделает его полностьюбеспроводным иавтономным.Энергиябудет собиратьсяизсолнечных батарейи хранится вионисторах. Наиболее подходящиминтегрированным решением для этого, пожалуй, будет BQ25504.

2) Разработкапечатных плат с коммутаторамипеременного тока(реле илисимисторы). Это,сделает сделаетпроектеще и системой управления, что позволит не толькополучить данныеот датчиков, но иуправлять насосамии т.д.Сделановскоре после того какпроект был представлен на конкурс.

Kogawa's simplest FM transmitter

$
0
0

 

Kogawa's simplest FM transmitter

 After the last unsuccessful attempt at building this thing, I've finally got it working.
Some helpful tips:
Normal output (note the awful frequency drift-off)
Output with base overdriven
Signal's doppelganger to the left
  • Things like size of the pads (exactly 5x5 mm.), lead length (minimal) and component placement really DO matter. If you assembled a transmitter like this one and it doesn't seem to work (or it does, but the signal is noisy with lots of out-of-band emissions) you probably should check the layout.
  • Signal frequency drifts off with decrease of battery voltage, and really fast. Therefore, it's not practical to use transmitter as it is now. One should add a voltage regulator to power the circuit in order to stabilize output frequency.
  • Too large of an amplitude of the signal will saturate the transistor's base and "bloat" the output frequency band, rendering the sound almost unrecognizable.
  •  Almost any sort of transistor will do, such as renowned 2N3904. Look in the datasheet for fT (Current Gain - Bandwidth Product). It shouldn't be less than 170MHz (Kogawa himself uses 2SC2001 with this figure, 2N3904 is even better with 300MHz).
  • The transmitter, other than the intended RF signal, will produce it's weakened undesired copies outside the band. Search for the strongest signal.
To-do:
  1. Stabilize the power supply to prevent frequency drif-off (add a simple 7809 voltage regulator and increase the power supply voltage).
  2. Add band-pass filter at the output to supress out-of-band noise.
  3. Add antenna to invade the neigborhood 8-)

Простейший FM передатчик Когавы

$
0
0

 

После последней неудачной попытки собрать эту штуку, я, наконец, добился чтобы она заработала.Некоторые полезные советы по сборке:
Нормальная работа (обратите внимание на ужасный дрейф частоты)
Сигнал с насыщенной базой транзистора
Двойник сигнала слева от оригинала
  • Такие вещи, как размер площадок (ровно 5 на 5 мм.), длина выводов компонентов (минимальная) и размещение ДЕЙСТВИТЕЛЬНО имеют значение. Если вы собрали такой же передатчик как этот и он не работает (или работает, но сигнал шумный с большим количеством помех вне частоты передачи), вероятно, следует проверить печатную плату.
  • Частота сигнала дрейфует с уменьшением напряжения батареи, и очень быстро. Таким образом, передатчик не практичен без модификаций. Следует добавить стабилизатор напряжения для питания схемы для того, чтобы стабилизировать выходную частоту.
  • Слишком большая амплитуда сигнала насыщает базу транзистора и "раздувать"выходной сигнал, что делает звук почти неузнаваемым.
  • Почти любой вид транзистора пойдет, например, известный 2N3904. В даташите следует искать параметр fT (Current Gain - Bandwidth Product). Он не должен быть меньше, чем 170MHz (сам Когава использует 2SC2001с этим значением параметра, 2N3904 еще лучше - 300 МГц).
  • Передатчик, кроме желаемого радиочастотного сигнала, будет производить его ослабленные копии. Ищите самый сильный сигнал.
Что сделать:
  1. Стабилизировать питание, чтобы предотвратить уплывание частоты (добавить простой регулятор напряжения 7809 и увеличить напряжение питания).
  2. Добавить полосовой фильтр на выходе для подавления шума вне диапазона.
  3. Добавить антенну чтобы устроить локальную радиостанцию 8-)

Переделка часов Электроника 7

$
0
0

I'm not going to make an English version of this post because the possibility of someone who doesn't speak Russian coming into possession of an old Soviet clock is basically 0.


Итак, примерно полгода назад добрые люди на кафедре отдали мне старые и нерабочие часы "Электроника 7". Так они выглядели:


Что не работает в часах видно по картинке - половина сегментов в вакуумных трубках выгорели. Мне пришла в голову идея реставрировать такое чудо советской инженерии с шиком - заменить вакуумно-люминисцентные индикаторы современными яркими светодиодами "Пиранья"и заменить саму электронику внутри.

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

Я заменил раму из ДВП на другую.


Шаг 1. Работа над корпусом.

Начнем с выдирания старой электроники - нужно вытащить из часов все печатные платы и ВЛИ. Теперь приступим к созиданию - надо для начала сделать новый дисплей из светодиодов. Для этого понадобится:
  • куча светодиодов Пиранья любого цвета;
  • 2 макетные платы 9х15 см;
  • кусок черного картона или чего-то похожего.
Каждая макетная плата разместит на себе 2 цифры по 10 сегментов каждая. Из-за того что сегменты состоят из точек, не получится обойтись обычными 7 сегментами. Вначале я попытался, и вот какая чепуха получилась:
Часы с 7 сегментами на цифру. Тихий ужас.

 Организация сегментов - общий катод:
В каждом сегменте будет от 1 до 3 светодиодов, и соединяться они будут последовательно. Где расположен какой сегмент будет видно на фото ниже.
Процесс изготовления 1 макетной платы с 2 цифрами выглядит так:
  1. На макетной плате со стороны металлизации разметить отверстия для 2 цифр;
  2. Наложить картон с лицевой стороны, пробить в нем отверстия под ножки светодиодов;
  3. Поставить светодиоды на место, спаять их соотвественно схеме "общий катод".
Так выглядят готовые макетки спереди и сзади:

Важно пометить верх, а также за что отвечает данная плата - часы или минуты, особенно если крепление цифр к корпусу будет несимметричным. Маленькая черная платка содердит всего 1 светодиод для разделительной точки.

Часовая и минутная платы в сборе.
После того, как цифры готовы, можно собирать их в корпус и смотреть на результат:

Крепление цифр на раме, вид сзади. Уже прикреплены блоки питания на 5 и 12 Вольт.

Если вас устраивает такой вид, то можно приступить к следующему шагу. Меня не устроили скошенные рамки из черной краски на стекле, я снял краску со стекла и заменил ее тонировочной пленкой:

На фото видны дополнительные циферки в верхнем левом углу. Это потому, что вначале я хотел добавить в часы термометр, но потом передумал и убрал их.
Законченный вид уже с пленкой.

Шаг 2. Разработка электронной начинки.

В основу я взял то что было под рукой - микроконтроллер PIC16F887. Схема пережила несколько версий и переделок. Изначально все транзисторы на схеме были полевыми, но, как выяснилось, напряжение питания 5В открывает их не полностью, и они были заменены на старые добрые NPN транзисторы.
Версия 1 схемы использует часовой кварц для тактирования микроконтроллера и имеет подключение к дисплею температуры:


Во второй версии я изменил источник тактирования МК на внутренний с частотой 4МГц, так как частоты часового кристалла было недостаточно для мультиплексированиядисплея часов. Кварц от часов был поставлен источником таймера 1.
Финальная версия схемы часов.
Схема простая и не имеет ничего лишнего, так что объяснять тут нечего. Можно приступать к сборке  схемы на макетной плате:

 
Ужасно запутанная первая версия платы. Я психанул и спаял заново.

Финальная версия платы. Намного меньше спагетти.
 Что не забыть во время пайки:
  • Фильтрующие конденсаторы на линиях питания 12 и 5 В. Большой емкости для низкочастотных помех и маленьких емкостей поближе к МК для высокочастотных помех.
  • Подобрать нагрузочную емкость для кристалла 32.768 КГц. От этого будет зависить точность часов. Про свой кристалл я не знал ничего, поэтому по очереди проверял точность с конденсаторами от 6.8 до 20 пФ. Лучшие результаты получились с 6.8 пФ (за 16 часов не отстали ни на секунду).

Шаг 3. Собрать, наслаждаться.

К этому моменту все по отдельности должно быть готово. Остается только залить прошивку, собрать все вместе и запускать.

Исходные коды прошивки на C и схема в формате Eagle CAD

В моем случае трагичные события привели к гибели оригинальной рамы из ДСП и виновнику пришлось собирать новый корпус. Если у вас руки растут правильно, то собирать новый корпус не обязательно.
Фото окончательного результата:

Infrared remote controlled light switch with ATTiny2313

$
0
0
На русском

Back when I was only starting to dabble in electronics, I needed a project that would meet the following requirements:
  • simple to make;
  • original (i.e. done entirely by myself from scratch);
  • containing a microcontroller;
  • and maybe the most important of all, useful. I've had enough devices I assembled just to dismantle the whole thing a month later.
The thing I came up with at the time was a light swich for my room controlled over an IR remote from TV. Remote that I had used RC-5 protocol, hence the firmware is suited for any RC-5 compatible remote.
Everyone is familiar to the everliving problem with switching the lights off in your room before going to bed and stumbling back across the room. The IR switch I describe here solves that problem, and I can definitely tell that this project was a success - I am still using it with no regret.

That's what it looks like. The blue cover is a lid from some beauty product.



As usual, I am putting up the link for source code, schematic and PCB at the end of the article.

Schematics


The schematic is pretty straightforward. Although it may be simple for me, this device is intended for absolute beginners in electronics so I'll try to explain every bit of it.

Power is supplied from an external 5V power supply (not sure about current, should be a tiny figure). There's C1 for filtering ripples in power supply, it's an electrolytic capacitor and the value doesn't matter really much, can be anywhere from 10 to 1000uF. There's also C2 and C3 for the same purpose, and those are placed as close as possible to the point of consumption, that is, to microcontroller's power supply pins.

 The heart of the circuit is ATTiny2313 clocked at 8MHz. C4 and C5 are load capacitors for crystal. There's input - the switch S1 with debouncing circuit and IR receiver designed specifically for reception of 36KHz pulses (TSOP1736); and then there's output - the relay which is switched on and off by means of a simple bipolar transistor. Diode D1 supresses the voltage spikes that appear at the time of switching across the relay coil.

The only thing leaft is an ICSP header  that I use to program my microcontrollers soldered on the board. And that's it, really.

Hardware

Now that the theory is behind you can start etching the PCB and assembling the device. My looks awful after lots of modifications of the original design, but here it goes:

Your switch is not supposed to look like crap, unlike mine.

Next step would be modifying (the code my remote sends when I press the OFF button may be different from what your remote sends, just edit the code) , compiling and uploading the firmware and installing the new smart switch in place of the old dumb one:

Hardware in Eagle and C code for AVR 

That's it, no more cold feetsies for ya!

This is an open-source hardware, you are free to modify whatever you want. 

Выключатель света с управлением с пульта от ТВ на ATTiny2313

$
0
0
In English

Когда ятолько начиналбаловатьсяэлектроникой, мне нужен былпроект, который отвечал бы следующим требованиям:
  • простой;
  • оригинальный (т.е. сделанный мною с нуля);
  • использующий микроконтроллер;
  • и, возможно,самое важное, полезный. У меня былодостаточноустройств которыея собралтолько для того чтобыразломать через месяц.
Вот что япридумал - выключатель света управляемый пультом от телевизора. Пульткоторыйу меня был использовал протоколRC-5, следовательно,прошивкаподходитдля любогопультас RC-5.

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


Вот так он выглядит. Крышка снята с какой-то банки с косметикой.

Как обычно,вконце статьия поставлю ссылку наисходный код, схемуипечатную плату.

Принципиальная схема


Схема устройствадовольно проста. Хоть это может бытьи простодля меня, но это устройство предназначенодля абсолютных новичковв электронике, так что я постараюсь объяснитькаждую его часть.
Питание осуществляется отвнешнего источникапитания 5 В. (неуверен какойток, но должен бытькрошечным). C1предназначен для фильтрациипомех по питанию, это электролитический конденсатори емкость его не имеет особого значения,может быть от10 до1000 мкФ. Также  на схеме расположены С2 и С3 для той же цели, иразмещеныони как можно ближекместу потреблениятока, то есть, к выводупитаниямикроконтроллера. Сердцемсхемы являетсяATtiny2313с тактовой частотой8 МГц. С4 и С5 - нагрузочные конденсаторы длярезонатора Q1. Есть устройстваввода- выключательS1собвязкой для устранения дребезга контактови ИК-приемник, разработанный специально дляприемаимпульсов частотой36 кГц(TSOP1736); и есть  устройства вывода - реле, котороевключается и выключаетсяс помощьюпростогобиполярного транзистора. ДиодD1подавляетскачки напряжения, которые появляются во времяпереключениятока черезкатушку реле.
Единственное, что осталосьэторазъем для внутрисхемного программирования (ICSP). Яиспользуюего для программирования микроконтроллеровуже напаянныхнаплату. Вот и все.


Железо и сборка

Хватит теории, можно начатьтравлениепечатной платыисборку устройства. Моя плата выглядитужасно после многочисленныхмодификацийоригинального устройства, вот она:

Ваша плата не должна выглядеть как кал, в отличие от моей.

Следующим шагомбудетмодификация(код который посылает мой пульт при нажатиина кнопкуВЫКЛможет отличатьсяот того, чтопосылает вашпульт, просто отредактируйте код), компиляция изагрузкапрошивки, после чего следуетустановка новогоумного переключателя на местестарогои тупого:

Код прошивки на C, схема и печатная плата Eagle CAD 

Скажите холодным ступням прощай!

Этот проект является открытым, вы можете свободно вносить любые модификации. 

Improvements to Arduino

$
0
0

Preface

Everyone knows Arduino. It's a versatile board that is great for when you need to make some piece of hadware work really quick without building a custom board and writing low-level code. Ever since I discovered that board I've been using it where flexibility and speed matter - robotics contests, mostly.
Now, considering Arduino is an open hardware, a lot of Arduino variations exist - actually too much to even try to list - and all of those clones try to either overcome some limitations that exist in original platform or add some useful functions to it.
This article is an aggregation of tricks for those who have an original Arduino board - some of those tricks are just improvisations I had to make up while I was working with Arduino, some of those I just found on the Internet and considered interesting.
Anyway, here's a collection of improvements:


Add a jumper to Vin pin

Original Arduino has a diode (D1) that protects the board from reverse polarity applied to DC jack connector.
Unfortunately, the creators didn't seem to want to protect Vin pin which serves the same function - supplying external voltage. For instance, accidentally shorting pins Vin and GND (they are located nex to each other) with power supplied from DC jack results in destroyed diode and burnt traces.

What you need to do is:

  • sever the trace from Vin to diode (which probably already blew during the short circuit),
  • replace a diode (definitely) and capacitors (maybe) - if an accident had already happened. Look for bulging tops on capacitors,
  • solder a preferably solid core wire between Vin pin and power jack.

Result:


Speed up and optimize


Convert to 3.3V

Here's a great writeup.

Make another

Bonus for those apt with soldering iron - a guide to making your perfect Arduino to suit all your needs.
1) Pick a microcontroller and make a basic Arduino board with whatever voltage and frequiency you want.
2) Add whatever you want to make it truly universal. For instance, I always found pin headers too flimsy for repeated use in prototyping. You could either make your board fit on a breadboard like this:
or replace pin headers altogether with screwless terminal blocks, possibly adding multiple headers for GND, 5V and 3.3V (three 5Vs, two 3.3Vs and 5 GNDs is what I consider perfect for most prototyping tasks):

To be continued

If you have some nifty hacks to add to this list, please write me back: headcra6 at gmail com.

A guide to more finished PCBs

$
0
0
If you ever had your PCB manufactured at factory, odds are you're familiar with the following situation. You design a schematic, lay out the board, check it multiple times, then send Gerbers to manufacturer and some time later the box of shiny PCBs has arrived. You assemble it (or don't, some manufacturers offer a full assembly at moderate cost) only to find that something SO obvious is amiss.
There's so much to keep in mind when designing a schematic and PCB, and it's even harder when you don't do it regularly. That's why I decided to compile a list of

things to check before you submit your PCB to fab

Schematic

PCBs start with schematic diagram, that's why it's important to tidy it up first.

1)Draw dots at junctions. How's your schematic capture sofware supposed to know these crossing lines connect and those crossing lines do not? That's right, with the help of dots.
Well-arranged multivibrator. Notice the dots at the crossing junctions.

2)Add filtering capacitors: big electrolytics for low frequencies, small ceramics for high frequencies.
Two ceramic capacitors by the part for bypassing.

Small caps (100 nF generally) should be placed as close as possible to IC pins (on schematic, too!).
In serious analog circuitry also add inductor/mutual inductor/inductor-capacitor filters for better noice reduction.
Good links to learn about power supply filtering:
Designers guide manual on power supply filtering

TI SCAA048
Analog MT-101
Maxim AN4713
Intersil AN1325

Filter calculator

3) Add protection - fuses, flyback diodes etc. (a thin trace can happen to be a fuse - see item 1 under "PCB")
NPN transistor protected by flyback diode
Ditto for PNP transistor

4) Add some means to program and test your rig!
Any fresh board needs testing and programming first. That's why you need a way to make temporary connections for measuring equipment. For these purposes you have a choice between the following:
Test pads for pogo pins
PogoISP Project
TagConnect ICSP Cable
Great choice for cases when you need maximal portability and high-density PCBs.
Test points for hook clips
Сonvenient in most through-hole designs.
Regular pin headers
(I assume everyone knows how those look)
Well, if you haven't stocked up on real test accesories, it's your choice.

PCB

1) Check the thickness of every trace. Insufficient thickness of any trace will result in that trace burning after you connect power to your PCB. Look at my example of PCB that modulates flyback transformer's arc so it would play music (nevermind the horrible arrangement of PCB):
I've outlined the path where high currents are switched through the primary of flyback xformer.
Aaand it corresponds to 2 traces that are only good for carrying signal!
Now this looks better:
Power traces should be thick even if they don't carry much current, it makes them more recognizable on the board.
2) 45 degree rule
It doesn't matter how you route your schematic if the signals don't go higher than 1MHz. Still, routing your board with 45 degrees everywhere makes its appearance more aesthetic:

Arbitrary angles
45 deg. everywhere

3) Arrange names on silkscreen, add meaningful designations wherever possible. Imagine you see your board for the first time and you have to figure out what to do to make it work - what to connect here and which jumper to close etc. Example of PCB for a wireless network node can be seen below:
I didn't take heed at proper silkscreen when I ordered the first batch which resulted in ugly boards
This looks better. Names, dates, pin names - everything is there.

4) Add ground and power planes for shortest possible current return path length. Also add planes under surface-mount components that tend to heat when used (voltage regulators, FETs etc.) for better thermal performance.

That's obviously not everything you have to keep in mind. All I described in this article is based on personal experience I have aquired over years of doing PCBs as a hobby.

Vocore tutorial: blinking an LED, using software SPI and unbricking

$
0
0

 Introduction


Hello everyone, I've recently laid my hands on this interesting piece of hardware and this article will describe my experience with it. It is an attempt to gather together all those scattered pieces of information I found on Internet to get this thing running.
Predictably, I managed to brick Vocore while messing around with its operating system (the only working thing left in memory was the bootloader), so I'll describe how to easily get it running again.

Requirements

  • PC running Linux (I used Arch Linux)
  • LED, any value resistor, any button or switch.
  • Any USB to Serial board- Only for unbricking!


    Some helpful links we'll frequently use

    One page you're going to look at a lot is its layout.
    Hardware: descriptions, schematics, etc.

    Let's start!

    So, you have this board in front of you. You probably already connected 5v to it, switched on your power supply and login'd via ssh. If you didn't, go to this link and do it!
    What's next? First, to be able to configure the kernel of Vocore and, more importantly, to get a cross-compilation toolchain, we will have to compile OpenWrt, which is the OS that runs Vocore.

     Building OpenWrt

    1) Download OpenWrt
    2) Configure feeds
    Optional: install some (or all) feeds. I just installed nano because that's my favorite text editor in Linux
    3) Apply Vocore patch
    It makes OpenWrt use 16Mb flash instead 8Mb, sets the access point SSID to VoCore, turns the radio on by default, sets the root password to "vocore" and ip to 192.168.61.1
    Optional: you can change whatever you want - e.g. change the SSID to something you like more, change the root password, add security to Wifi etc..
    4) Configure the kernel.
    The first 3 selections have to be:
    Now go to
    and tick the following:
    Optional: add or delete utilities, modules, features. Unset menu items only if you are sure what they mean. When I did it first time I went on a rampage and wiped all unnecessary (or so I thought) features which resulted in perfectly working kernel that didn't have WiFi drivers in it.
    I would definitely include dmesg which is a handy program that displays system log so you know exactly why doesn't something work. To make use of software SPI you will need to check

    and to test if it works okay you should also check

    Using GPIOs that have alternative function (like JTAG, PCM, UART etc)? You're in for a surprise. Lunux kernel probably won't let you export (or use) those GPIOs. If you're sure you'll never need this pin's function, you can modify

    and remove the section that corresponds to the pin you need, for me it was
    and use it freely!
    5) Run make and wait patiently...
    -jN is the number of your CPU cores + 1.
    6) Flash the new firmware
    We are going to use the easiest method. I even made a script update_openwrt_on_vocore.sh to assist that (requires packages zenity and sshpass):
    Just connect to Vocore AP and run
    Text that pops up in a windows is what you have to type in telnet window (Couldn't make ssh run a command even though it should be as easy as ssh user@host 'COMMAND'. Know how to do it? Please write a comment).
    That's it! Wait for the AP to reappear and you can telnet to your brand new custom OpenWrt.

    Adding some hardware

    My aim was to make Vocore work with REYAX CC110LM boards (containing TI's CC110L):


    However, as an old microcontroller enthusiast I decided to add a blinky light and a button to see if I can make Linux blink an LED and read the state of a button. So I got to soldering this all on, I hope you can make your soldering look less messy:


    Schematic:
    led -        gpio7
    button - gpio19

    cc110l:
    SI -        gpio12
    SO -      gpio13
    SCLK - gpio14
    CSN -   gpio21
    GDO -  gpio0

    As you can see, I also hotglued miniUSB jack as a power connector. Quite handy.

    First program - Blink

    To switch GPIO 7 (with LED connected to it) on and off from shell you can telnet into Vocore and type the following:
    If you can't export GPIO, that most likely means it's allocated for some other purpose. Either put the LED on the pin you can export or you can free the pin of it's function  when you compile OpenWrt (go to item 4 of section "Building OpenWrt")
    Controlling GPIO from command line is nice, but that's not how it should work, so let's compile and launch our first program that blinks an LED. I'm using makefiles to automate compiling and uploading.
    Program structure is simple, and so is makefile. To compile and upload to target you only have to change  this line:

    to where your toolchain is located (it was built when you compiled OpenWrt) and run make in Blink directory.
    Make system will compile your program, copy it to vocore's /root and login you to telnet.
    You only have to launch it ./blink and look at the LED.

    Next up - buttons

    Now that we've dealt with GPIOs in output mode, we have input mode ahead of us - that's what the button is for.
    To assess the button's state (gpio19) from command line enter the following:
    Writing the program that will utilise the button is up to you ;-)

    SPI

    I'll be using software SPI via spi-gpio-custom kernel module. Adding an SPI device is as simple as launching
    where 1 is device id,
    14 is pin for SCK
    12 is pin for MOSI
    13 is pin for MISO
    0 is SPI mode,
    1000000 is max clock freq. (in Hz, so 1Mhz in this case)
    21 is pin for SS
    and using the resulting /dev/spidev1.0 like this:

    To check if SPI really works without having any slave device connected to your board simply short MISO to MOSI on Vocore (gpio12 to gpio13 in my case) and run
    and that's what it's supposed to yield:
     If what you see is a page of '0's, 'F's or some rubbish that is inconsistent between spidev_test launches, check if your wiring (and insmod command) is correct and try again.

    So you spoiled it

    In fact, I bricked Vocore so many times I made a script that automatically restore the default firmware. You can get it HERE
    Let's begin by connecting USB-Serial adaptor to Vocore's UART at pins 15 and 16. Then install putty , open it and create a profile "ttyUSB0@57600" that is just a serial port on ttyUSB0 at 57600 baud. Launch ./unbrick_ckermit_uart.sh and wait for it to do the job.

    The end.

    I'll write about using CC110L with Vocore if I'll have enough time.

    Neoway M590 GPRS Tutorial: sending and receiving files from/to SD card

    $
    0
    0



    Here's a bit of useful info from what I've been doing lately. I got a job to design a device that connects to a web-server via GPRS and downloads a bunch of tiny WAV files, that it later plays on a specific schedule. Now, there's a jellybean part for this kind of task, and that is SIM900 (or SIM800), but I have a knock for "optimising" my electronics. Optimising  in this context means making everything I can as cheap as possible, provided it doesn't impact overall quality in a negative way.
    That's how I came upon this el cheapo GPRS module - Neoway M590. It's sold as an assemble-it-yourself kit at Aliexpress, and at the moment of writing this article it retails for as low as 2USD.

    Advertisement not intended so I blurred the store id :-)

    Preparations:

    • One can easily find pictures of this thing assembled to know which way to solder diodes, sim card holders etc. 
    • I strongly suggest using an external 5V power supply rated at least 1A, Arduino cannot source enough current for transmit/receive operations.
    • Actually for proper operation you are supposed to power it from 3.3V supply and use level conversion on RX/TX lines with 5V Arduino, but personally I conntected this module straight to Arduino pins and nothing happened.
    After receiving it I wanted to do a quick check of its fuctions. Hooked it up with Arduino and started looking up pieces of code and docs... Hmmm, weird enough, the only useful piece of info I found was this, and it only covers SMS.
    So, after sifting through tons of garbage in the internet and failing to send proper HTTP GET requests I proudly present you my test sketches that just work (c). Those sketches are enought to get anyone started in sending SMS and sending/receiving info through TCP/IP.
     

    Some notes about TCP/IP stack on M590:

    •  TCP connection can only be established to IP address, so you can use AT+DNS="hostname.com" to request IP from known address.
    • Println function in Arduino terminates the string with CR LF sequence (ASCII codes 13 10 or special characters \r \n), and I don't use it for TCPSEND command to avoid confusion. You have to tell M590 how many characters to send. All characters between AT+TCPSEND=1,47\r and final character 0x0D count (including \r and \n).
    • You will need this document, it  contains AT command set of this module.

    Sending SMS and detecting incoming calls:


    Download text file using GPRS


    Download WAV file to SD card

    This code requires the following physical setup:
    SD card MOSI - Arduino pin 11
    SD card MISO - Arduino pin 12
    SD card CLK - Arduino pin 13
    SD card CS - Arduino pin 4
    M590 TX - Arduino pin 2
    M590 RX - Arduino pin 3
    To avoid using level converters with peripherals (they're all 3.3V) I used my Arduino Uno modified for 3.3V operation.
    So, this one sketch I used to try and see what happens if you download something bigger than plaint text. I quickly whipped up a free web-site and downloaded a tiny 90kB wave file to it. Then I used the same old sketch to print this file in Serial monitor.
    This turned out a complete failure. First of all, M590 would reboot mid-download, what is worse, is that some bytes came corrupted. I'm attaching original WAV file and received bogus copy for future reference, with the conclusion that, as usual, you can get things either cheap or in good quiality, not both...

    Application of Neoway M590: remote control for garage heater.

    $
    0
    0

    As those who read my previous article about M590 GSM/GPRS module know, it's not very reliable for GPRS operation. Recognizing this downside of M590s, I still wanted to use them (heaps of garbage wares from China have to go somewhere, right?). Thus a new idea of useful application was born: a remotely activated air heating unit for my garage.

    Heating part:

      The heating unit is built around a part I happened to  have at the time - a huge heating element (about 1 meter long!).
      Beside that I only had to source a 1 m. piece of  round ventilation duct and a fan. The heater has to be positioned roughly at the center of duct. I also sawed out rectangular pieces from the duct so that the plastic fan wouldn't melt, to further protect it from overheating I installed an NC thermal switch that opens when the temperature is around 90°C.
      You should be able to easily replicate my setup just by looking at the pictures below:
       
      The whole heater + fan setup is suspended from the ceiling by some copper braid. Note that:
      1. You can use anything that won't melt for suspension - steel or copper wire is what you'll probably find lying around  in no time.
      2. Hanging the heater was the dumbest thing done in this project. When you heat air it goes UP whereas the cold air stays down below. The fastest and the most efficient way to heat air is to install this on the floor.

      Electronics part:

        Yeah I used Arduino for this pls don't shame me.
        I also went full ghetto with the enclosure, which is a plastic box from some power tool painted black. It gives off the air of something quickly put together from scraps and that's what I like about it - I'm all about improvisation :-)
        Schematics:

          The schematics is pretty simple. I use a contactor to switch heater on and off, which is probably overkill. The relays on the schematics are actually 12V relay modules, which is why I can drive them from an AVR pin. Here are some pictures of the insides of the enclosure:

          Ready to be connected!






          Arduino sketch:



          I'm using an official Arduino Bounce library for debouncing (I'm that lazy). The heater has 3 modes: ON, OFF and AUTO, which are switched by the switch on the main panel. When switched off, the controller turns off the heater but lets fan blow off the heat for a preset time (120 seconds in my case). In AUTO mode you can send SMS to switch the heating on or off, but there's a timeout of 3 hrs. for safety reasons. So, if I were to switch on the heater and forget about it completely it would not waste tons of energy waiting for me to come to the garage.

          Seeing how impressed my friends were when they saw this thing controlled by an SMS I immediately felt it was worth making. And with cold season coming it's going to become my greatest friend :-).




          Пивоварня из стиральной машины

          $
          0
          0
          Сегодня я покажу как начать варить пиво при наличии большого желания и кучи хлама и отсутствия денег. Именно в такой ситуации я решил переделать старую активаторную стиральную машинку в емкость для варения пива.
          После прочтения кучи текстов про пивоварение я нашел интересный и простой метод варки в 1 емкости : BIAB (brew in a bag или варка в мешке). Хорошее руководство с картинками можно найти ТУТ (английский).
          Будучи любителем автоматизации, я сразу заметил то, что неплохо бы температурные паузы при пивоварении поддерживать при помощи микроконтроллера. Таким и появился монстр под названием стиральная машинка - автоматизированная пивоварня.

          Стиральная машина

          Имеем стиралку Вятка активаторную (это значит что она устроена не как современные машинки с барабаном который крутится, а с баком внизу которого крутится что-то вроде плоской мешалки). Объем бака 28 литров, слив воды - снизу. Бак формы цилиндра срезанного снизу, что очень удобно для слива сусла по максимуму.

          Так выглядела моя Вятка до модификаций.

          Для контроля температуры надо установить в бак нагревательный элемент и датчик температуры. Понадобится следующее:

          Нагревательный элемент от чайника.
          Датчик температуры DS18B20, желательно
          сразу с гильзой для вворачивания в
          стенку емкости. Покупается в Китае.

          Также понадобится что-то чем скрепить нагреватель и емкость. Я купил для этого тюбик холодной сварки. Не делайте этого! Холодная "сварка" - это всего лишь двухкомпонентная эпоксидная смола и совершенно не пригодна для контакта с пищей. Стоит поискать какой-то клей для пищевой промышленности либо вообще не использовать резиновые/металлические прокладки для соединения.
          Вырезаем активатор и на его место вставляем нагревательный элемент. Также где-нибудь в емкость врезаем датчик температуры.
          (ОПЦИОНАЛЬНО) Я добавил ситечко над нагревательным элементом для того чтобы к нему ничего не пригорало. Для варки в мешке это не требуется, т.к. весь солод и хмель при варке находятся в мешке, но если я захочу попробовать варить пиво обычным методом, оно пригодится. Для крепления ситечка я использовал защелку как на чемоданах, купленную в магазине крепежа.


          Теперь надо установить фильтрующую систему и кран для слива сусла. Для этого в любом хозяйственном магазине покупаем следующуий набор (все размеры 1/2"):
          • Гибкая подводка 1м
          • Сгон
          • 2 гайки
          • 2 металлические шайбы
          • 2 резиновые прокладки
          • Гибкая подводка 30см
          • Резиновая прокладка
          • Кран
          Длинная подводка и будет фильтром. Отрезаем гайку на одном конце подводки, а на другом конце очень острым и тонким ножом прорезаем резиновый шланг сквозь металлическую оплетку. Остается только вырвать шланг и у нас в руках остается фильтр - металлическая оплетка с гайкой на конце. Другой конец надо закрыть, я просто закрутил его болтиком и шайбами.

          Почти готовый фильтр из оплетки. После того как я это сфотографировал, я еще вытащил красную и синюю леску.
          Бак с фильтром - вид снаружи. К гибкой подводке привинчивается кран.
          Бак с фильтром - вид изнутри. Также хорошо видно сито над нагревателем.

          Электроника

          Сразу прикреплю схему управляющей коробки - она простая и не требует множества пояснений. Для вывода информации используется знакосинтезирующий дисплей (ищется по ключевому слову hd44780 на алиэкспрессе и проч.), для ввода - 3 кнопки и энкодер. Питание коммутирую при помощи твердотельного реле аж на 25 китайских ампер, что примерно равно 10 настоящим амперам нагревателя.


          Собрал все в корпусе от ATX блока питания, от другого БП взял 12 и 5 В (перебор, конечно, но у меня валялось полно этих блоков). Прилагаю фото сборки и готового устройства:

          Врезаем органы управления в переднюю панель...
          Крепим Ардуино вертикально чтобы сэкономить место.
          Почти готово. Огромный радиатор - перебор, но это лучше чем перегрев :)
          Коробка собрана и залита пробная программа.
          Вся система. Снизу БП, сверху система управления с торчащим из нее датчиком. Питание на нагреватель подается белым кабелем папа-мама.
          Белый шнур дает 220В на нагреватель, питание электроники осуществляется отдельно через черный шнур (в нем 12В+5В+GND). Провод в белом вводе - датчик температуры.
          USB порт для удобства выведен наружу.
          Черный кабельный ввод - для подключения нагревателя.
          Блок управления врезанный в корпус от стиральной машинки.

          Код:


          В начале кода есть кое-какие полезные подстройки, такие как:

          #define DEBUG - любимый режим отладки. В нем будет вывод всякой полезной инфы в терминал, в том числе значения температуры для построения графика (незаменимо для настройки PID алгоритма). Обычно когда код готов, я эту строку комментирую.

          #define USE_EEPROM - советую раскомментировать после настройки PID алгоритма, тогда все параметры будут сохраняться/загружаться в постоянную память.

          const int WindowSize = 5000; - размер "окна"в течение которого происходит 1 цикл включение-выключение реле (здесь 5с). Что-то вроде периода медленного ШИМ сигнала.

          const double maxKp = 1000;
          const double maxKi = 500;
          const double maxKd = 100; - пределы подстройки коэффициентов пользователем. Взял их от балды, но вдруг кому-то понадобится больше.

          После того как все собрано и запрограммировано, самое время настроить PID алгоритм.

          Настройка


          Для лучшей работы алгоритма надо подстроить коэффициенты Kp, Ki и Kd под конкретный объект (именно ваш нагреватель, котел и т.д.). Я делал это следующим образом:
          1.  

          Про саму варку в мешке читайте в следующем посте:

            Tutorial: IntelliJ IDEA Community Edition with Tomcat deployment

            $
            0
            0
            This tutorial will help the beginner developers of Java EE applications.
            IntelliJ IDEA is a great IDE for a Java developer, however its Community Edition is somewhat limited in regard to enterprise and web development toolbox. You can easily develop desktop applications in Community, but confronted with the need to develop an enterprise web application with Java EE you suddenly find out that Community Edition can't provide you with an application server or automatic deployment or anything, really.
            In this tutorial I'm going to show you how to sidestep this issue by integrating IntelliJ IDEA Community Edition with Tomcat (via Maven) to develop a sample website with servlets.
            As most projects within IDEs do, this one starts with New -> Project item from menu bar.
            Pick Maven on the left side and create a project from maven-archetype-webapp archetype (pic. 1):

            Pic. 1. Create a Maven project.

            The following screenshots demonstrate setting group id, artifact id, project name and location. Group id is the unique identifier of your project, usually the name of the package as per Java package naming conventions. Artifact id is the name of the JAR file that gets deployed into Maven repository, in this case mywebapp. See how to pick group id and artifact id here.


            After creating a project, you end up with the basic directory structure required for web application: WEB-INF folder, web.xml file and even an index page(pic. 2).

            Pic. 2. Basic web app structure.
             
             Maven can build that, but there's still no directory for Java sources! That's what you have to do next (pic. 3). Create a folder java under My web app/src/main/ and mark it as source root. That's where all servlets go.

            Pic. 3. Create a source root.

            Let's proceed to make a sample servlet HelloServlet.java (pic. 4) and paste the following code there:



            Pic. 4. Create a sample servlet.

            The code is correct, but it's highlighted in red! Why? We forgot to add Java EE library as a dependence. Open your pom.xml and make it look like that:



            Modify pom.xml.

            Even though you don't need it to compile the project, your pom.xml now contains lines that pull tomcat7-maven plugin. Now let's make use of it: create a new Maven Run/Debug Configuration, name it whatever you want, put tomcat7:runin Command line field, and, finally, add a Maven goal clean to the list of things to do before launch (pic. 5):

            Pic. 5. Create a run configuration.

            Congratulations! You now have a working Java EE webapp project with run config that builds the entire thing and deploys it to Tomcat:


            Now you should be able to simply press Shift+F10 (or Run button, I'm not going to judge) and see index.jsp in your web browser of choice after clicking the link http://localhost:8888 in build output window:


            What about servlets? To see the servlet in your web browser you have to let Tomcat know where to look for it first. For that, change src/main/webapp/WEB_INF/web.xml and src/main/webapp/index.jsp to look like that:



            IntelliJ IDEA Community Edition деплой веб-приложения на Tomcat

            $
            0
            0
            Это краткое руководствопоможет начинающим разработчикам Java EE.

            IntelliJ IDEA - отличная IDE для Java, однако ее бесплатная версия Community Edition несколько ограничена в разработке веб-приложений и Java EE в целом. В Community версии очень легко разрабатывать desktop приложения, но как только становится необходимо разработать веб-приложение с Java EE, ты вдруг обнаруживаешь, что в Community нет никакой поддержки ни апп серверов (JBoss, GlassFish), ни даже сервлет контейнеров (Tomcat).

            В этом руководстве я покажу, как обойти эту проблему (без установки довольно дорогой или крякнутой Ultimate Edition) путем интеграции IntelliJ IDEA Community Edition с Tomcat (через Maven) для разработки веб-приложений с сервлетами.

            Начнем с того, что создадим наш проект, щелкнув на пункте New -> Projectв верхнем меню.
            В левой части выбираем Maven, а в правой архетип maven-archetype-webapp (рис. 1):

            Рис. 1. Создайте проект Maven.

            На следующих скриншотах видно, как задавать group id, artifact id, имя проекта и папку для него. Group id - уникальный идентификатор твоего проекта, обычно это имя java пакета в соответствии с Java code conventions. Artifact id  - имя JAR файла который заносится в репозиторий Maven, в данном случае mywebapp. Здесьможно подробнее почитать как выбрать group id и artifact id.


            После того как проект создан, появится стандартная структура папокнеобходимая для веб-приложения: папка WEB-INF, файл web.xmlи даже главная страница(рис. 2).

            Рис. 2. Стандартная структура папок.
             
             Maven уже сможет собрать такой проект, но до сих пор некуда класть исходный код Java! Это нам и надо исправить (рис. 3). Создаем папку javaпо адресу My web app/src/main/и метим ее как "source root". В этой папке хранится код сервлетов.

            Рис. 3. Создаем папку для исходников.

            Создадим для примера сервлет HelloServlet.java (рис. 4) и вставляем туда следующий код:



            Рис. 4. Создаем сервлет.

            Код правильный, но почему он подчеркивается красным как ошибка? Надо добавить библиотеки Java EE при помощи Maven. Открываем pom.xml и приводим его к такому виду:



            Изменения в pom.xml.

            Хотя это и не требуется для того чтобы собрать проект, мы также добавили в pom.xml директивы которые вытягивают с серверов Maven плагин tomcat7-maven. Теперь воспользуемся этим плагином: создаем новую Run/Debug Configurationтипа Maven, называем ее как угодно, в поле Command line пишем tomcat7:run, и наконец добавляем cleanв список целей Maven перед запуском (рис. 5):

            Рис. 5. Создаем конфигурацию запуска.

            Поздравляю! Теперь у тебя есть рабочее веб-приложение Java EE с конфигурацией запуска которая его собирает, делает WAR архив и деплоит его в Tomcat:


            Теперь можно просто нажать Shift+F10 (или кнопку Runна панели вверху) и увидеть в браузере страницу index.jsp по адресу http://localhost:8888 (ссылка будет в окне вывода информации о сборке):


            JSP есть, а что насчет сервлетов? Чтобы обратиться к сервлету, надо дать Tomcat понять, где его искать и на какой адрес замапить. Для этого поменяем 2 файла: src/main/webapp/WEB_INF/web.xmlи src/main/webapp/index.jsp :




            Tiva and Stellaris Launchpad RTC usage in Energia

            $
            0
            0


            For those of you who still have one of those old Stellaris Launchpads, I'm going to show how to utilize one of its most useful features - real time clock - in a simple way. Actually, the Hibernation module is the same in the new Tiva Launchpad, so it's supposed to work there as well.

            Some time ago I ordered one of those Stellaris boards, which were great for their price (about 12USD) - 80MHz ARM core with lots of I/O, UARTs, SPIs and I2Cs, USB device, Hibernation module and Arduino-like IDE (called Energia) support for simplicity of programming. Later, the line got rebranded to Tiva and Texas Instruments made another launchpad, almost identical to this one.
            Basically, Tiva Launchad is the same Stellaris Launchpad with a slightly different processor - LM4F120 on Stellaris was replaced with TM4C123G on Tiva.
            Meanwhile, the Stellaris Launchpad was collecting dust on my shelf, when I realized - it can be used as simply as any Arduino-compatible dev board, but it has something more to offer - RTC in Hibernation module!
            I started digging the internet and eventually I had this proof-of-concept code that makes use of Hibernation module as a simple RTC. It's limited to only telling you time (without date), but that was what I needed anyway.


            Upload it to your Stellaris or Tiva Launchpad and open Serial monitor:


            Send g to get current time, send s to set time. That's all, you are welcome to use this anywhere you want. This code snipped could be a base for a digital clock with some cool features, or an automated watering system, it's up to you!

            Сheap but ugly variable bench power supply

            $
            0
            0

             Every full-fledged tinkerer in electronics needs a variable power supply, and, as a tinkerer prefers to do, usually builds it instead of just buying. Personally, I did it because I didn't want to spend money on it, eventually discovering that now my PSU has a unique combination of features that no money can by. In this write-up I'll attempt to provide the reader with a comprehensive step-by-step guide on how to build something similar (and probably looking less like crap 😀 )


            I based my design on this splendid homemade PSU:

             Made by ThomasVDD
            You can learn how to make it at:

            http://www.instructables.com/id/Variable-ATX-bench-powersupply-FabLab-edition

            Since I didn't have access to a laser cutter and couldn't be bothered cutting the box manually with a jigsaw, I just found a plasic box of sufficient size and cut some holes in it.
            My PSU was supposed to be a carbon copy of the one on the link above (and I certainly wouldn't write this if it stayed this way). This model has some added features like:
            • Separate ground terminal with ammeter (0-1A and 0-5A range - selectable)
            • 2 additional terminals to measure and display zener diode's voltage
            • A display that shows voltage at variable voltage terminal
            • Additional -5V terminal 
            • A switch that lets you measure current through USB port
            • Awful exterior
            If this looks good to you, then please proceed:

            What you'll need

            • Working ATX Power supply
            • Some enclosure
            • A matching number of banana plugs and terminals (not exactly matching, based on my experience you never need more than 4 connection leads at once, so probably just 4 plugs and at least 9 terminals)
            Banana terminals that I used.
            Not the only kind at the market, you're free to choose something fancier.
            Banana plugs.

            • 7 fuse holders and fuses

             

            • 2 voltmeters with 3 wires (Power, Ground and Signal aka measured voltage) - most voltmeters sold on Aliexpress are 2-wired meaning they measure the voltage of the power source. You don't need them - as soon as voltage drops below 4.5V they will switch off.
            • USB port - I found that the easiest in procurement panel-mounted USB connector is "USB Female to Female cable" (BTW most suppliers incorrectly list it as type B):
            For a price of 1 item you get 2 connectors after snapping it in the middle! Yay!
            •  2 Ammeters - 0..1A and 0..5A
            NEVER buy digital ammeters, they just burn for no reason at all after a month of usage. I personally replaced 2 digitals before switching to analog.
            Analog is the way to go!
            •  For variable voltage circuit you will need: LM317, some filtering capacitors, 1.2k Ohm resistor, 10k Ohm potentiometer, 1N4007 (or similar) diode, heatsink for LM317, screw terminals (x3).
            • Miscellaneous: 2 SPDT switches (changeover), 1 SPST switch (on/off), 1k resistor, a couple of screws and standoffs to attach voltmeters to the enclosure.
            This "item list" picture was relevant when I started working
            on the original PSU, since then I replaced ugly usb ports
            and added lots of features. Still, this picture is inspiring so I'll just leave it here.

            Building

            Here's the schematic for the whole project.

            A picture is worth a thousand words, so here's some pictures of build in progress:


            1) Attach the box-less PSU to the lid.
            2) Fan is essential for keeping the power supply nice and cool.
            Don't forget to make some holes for air outflow as well.

            3) Build and attach the variable voltage circuit.


            4) Plan ahead, make a grid according to which you'll place
            your posts and fuse holders. Note a huge analog ammeter
            on top center - got fried in less than a month.




            Aaaand there goes the cheap chinese ammeter...

            At least it works without it just fine.

            Finished product:



            Hack SC2262/PT2262 transmitter to send commands for each button

            $
            0
            0


            Applications of RF transmitters based on 2262-type chips (datasheet) are innumerable. You can find it in most remote controlled things on the market - toy cars, light switches. This one in particular came from a fog machine and was used to trigger it remotely.

             Recently I needed a way to remotely tell a robot to start and stop doing a simple task, and this thing seemed a perfect solution for this - use Lock button to stop and Unlock to start.
            RF transmitters and receivers come in several flavors, most commonly 315, 433, 868 and 915MHz. To determine which one I had, I had to crack it open:


            Now we got to read it somehow... Luckily for me, you can buy receivers for any frequency in China by boatloads and dirt cheap. That's what I did!

            315MHz variety as marked in silkscreen table
            Now hook it up to Arduino and quickly check that everything is ok... (that's the library I use BTW)
            Except that when I tried to read the code for those buttons there was something unexpected in my terminal window...

            2 buttons yield the same code
              Looks like optimisation in production of fog machines really came a long way - even though transmitter's enclosure implies you can send 2 commands, it actually transmits one and the same command when you press any one of those 2 buttons.

            Checking the layout, my suspicions that 2 buttons are just connected to the same input were confirmed:


            That's how this works: any button pressed will connect 12V to the whole circuit: VCC pin and some address pins of 2262 IC and red LED thus sending one of 3^12 address codes possible.
            What you need to make 2 buttons work is separate them and make each of them send 12V to different address pins and VCC.
            Time to whip out your trusty scalpel 8-)
            Aand that's the result:

            You can see that in order to separately provide VCC to chip, I used 2 diodes.
            Now I have a fully functional remote control:


            Was it worth the hassle? Hell yeah, knowledge about internal works of stuff never hurt anyone. Hope someone will find this article at least educational, and maybe even practical!

            Interface board between industrial controllers and FischerTechnic construction set - for education and fun!

            $
            0
            0
            Have you ever seen an industrial programmer? Those half-gods who write programs for PLCs (industrial controllers, in short) and turn lifeless heaps of relays, controllers, motors and sensors into working factories, pump stations and other industrial objects?

            Those fortunate enough to see them doing their job probably wondered how they acquire their most vital trade skill - avoiding bugs in code. While a bug in code written by a conventional software developer could lead to system freeze-up or, worst case, loss of data, only one incorrect bit set by an industrial programmer in his code could send a gantry crane hook crashing into some really costly equipment (that's not a real-world example, I swear) or even harm people directly. Yeah, we all know that most mistakes in any equipment that interacts with outside world through something other than mouse and a keyboard do notcome cheap.

            The truth is, in most cases a newly hatched industrial programmer can't simply start working with real equipment. You have to let them either watch their experienced colleagues work for a while or train on something that's much cheaper and simpler than a factory, but at the same time emulates a manufacturing process.


            Real-world automation

            To understand how to make something that emulates the whole factory, let's start by looking at how it works in real world.

            Each industrial object that employs automation aims to replace human labor, which is expensive and prone to errors, with control systems (cheap to use, quite pricey to buy and install) to operate equipment. To understand what's going on out there and react to it, we connect various sensors and actuators to our control system. In the heart of any industrial control system is one or more steel cabinets that hold all the power and control electronics. That's what a typical Siemens-based cabinet looks like:

            Top part of the cabinet
            ... and the bottom part.

            Out of this assorted bunch of hardware, what really matters in terms of programmer's education is presence of PLC. Some IDEs for industrial controllers offer simulators, but that's only good for simple POC code, not complex systems where number of used I/O ports can exceed 100.

            That's what coding looks like in IDE for Siemens controllers called TIA Portal.
            Oh, and quite obviously any PLC only works when it's powered up. Most frequently PLCs are powered from either AC mains or 24VDC (latter is an industry standart - that's why it's not 12 or 5V)

            Sensors and actuators, from a programmer's standpoint, are divided into digital (0 and 1) and analog (0...MAX_VAL). There's lots and lots of different sensors and actuators out there, but what makes them useful to programmer is their involvement into manufacturing process.

            Thus, this arrangement is more educational than just any optical sensor dangling from a wire and pointing anywhere:



            Let's summarize what kind of equipment we need to hone industry involved programmer's skills:
            • Not prohibitively expensive - not any university can buy PLCs for each student in class, fewer still can provide them with expensive industry-grade sensors and actuators. As an alternative, there are some factory simulation software suites like Plant Simulation - they cost money too, besides, no program can be more visual and educational than a real piece of hardware in front of you.
            • Easy to fix if broken.
            • Involves a real PLC.
            • Sensors and actuators are embedded in some sort of manufacturing process.

            Solution

            Here's the solution they came up with in my university: real PLCs  in conjunction with toy control objects. FischerTechnic was the toy of choice: they offer this - ready-made control objects, and those we use as industrial robotic manipulators.
            Controllers they bought for educational purposes

            Some of our mock control objects - assembly line and robotic manipulator

            FischerTechnics really make excellent sets for every conceivable purpose -  sets include motors for vehicles, air compressors, valves and pistons for pneumatic contraptions, all kinds of sensors:


            All electric connections are made with a peculiar type of barrel connector. While it is easy to crimp (strip a wire, plug a wire into a barrel, tighten a screw) it's way too uncommon.
            It should also be noted that of all this assortment, only switches are indifferent to voltage applied to them,  for the rest of them you need some kind of level shifting between 24V and 9V.

            So, in order to solve these 2 problems, I set out to make an interface board that could bridge the gap between an industrial controller and child's toy. I'll be sharing with you some build pictures of the 2 versions of this board, as well as Kicad files and BOMs for both of them.

            Build (version) 1


            Requirements for this board were determined by PLCs we bought - it was Siemens S7-1200 with 10 digital outputs, 14 digital inputs and 2 analog inputs (0-10V), enhanced by 1 analog output module (0-10V as well). People with microcontroller background will be surprised to learn that even though there are microcontrollers inside any PLC, PLCs themselves can only have ports that are either input or output, not both.

            Since motors usually need to be operated in both directions, I arranged digital outputs in pairs in H-bridge set-up. Thus, any given pair of digital outputs can act as a driver for either 2 separate loads (valves, unidirectional motors etc.) or 1 bidirectional load such as a motor.

            What did I use for Fischer barrel connectors? After hours of lurking through local shops and markets, I found something that easily accepted a Fischer barrel - 9mm hollow rivets for clothes:


            Having bought a few of them, I tried to solder them and it turns out they are solderable (some metals like aluminum are a pain in the ass to solder with a conventional soldering iron+rosin+Pb solder) and conductive - a perfect match for my barrels!

            Features of this version:
            • Can drive either 10 loads in ON-OFF mode or 5 loads in polarity-switch mode (or any combination of thereof e.g. 2 bidirectional motors + 6 valves). Voltage level on each output is 0-9V.
            • 14 digital inputs where you can connect a switch or a phototransistor.
            • 2 analog inputs with 10V power supply terminals.
            • 1 analog output configured as a 9V PWM signal.
            • All inputs and outputs have LED indication.
            Here's some 3D renders of the first attempt:

            Top side
            Bottom side

            It seemed good enough for a first try and I ordered 5 boards at PCBWay.com - i found it via PCB Shopper service. This service allows you to enter your board's specs and shows you how much it will cost in each fab house from quite an extensive list. I went for the cheapest this time and here's what the cheapest PCB 5-pack looks like:

            They even add some tiny breadboards to your order for free!

            Top side
            Bottom side
            Soldering everyting to your board costs extra money, besides, what kind of electronics enthusiast would voluntary relinquish the joys of hand-soldering each individual part? 😀

            There's a couple of shots of soldered board (not finished yet though):

            Top side
            Bottom side
            As usual, there were lots of bugs in this first revision of board. Some were due to my lack of attention while committing Gerbers to fab house (that's how I ended up without mounting holes in boards's corners - just forgot to save changes in layout), some due to blatant lack of knowledge in electronics. Anyway, someone had to fix that, that's why I had to reroute some stuff here and there, getting a Frankenstein PCB as a result:

            That's a completely fixed PCB. Doesn't look as virgin as it did, innit?
            Some morbid closeup shots:



            I didn't even think about the fact that analog sensors needed 10 volts to have an output range 0..10V, that's why there's a 7805 on the bottom of all first revision boards now!


            Eventually all 5 boards were ready to go into testing phase:

            Yeah, for some reason I took a picture of 4 out of 5.
            Board already hooked up to some assembly line

            Quality control line to the left (sorts the mock wares into 2 chutes - good and reject)


            Clothing rivets turned out to be a perfectly acceptable replacement for real connectors
            I'm attaching Kicad files, PDF schematic and gerbers for this build. Some ugly stuff has been fixed in this revision, but the analog input part is still whack...

            Preliminary second revision fixed most bugs in schematic, but then I had to convert the board to smaller relays and different connectors, therefore it's completely different layout, parts etc...

            Preliminary second version of board before drastic changes, nothing from it survived but this 3D render.

            Only grab this if you'd rather build a board with Fischer connectors - second revision of my board completely eliminates them. In this case you should look at rev.2 schematic (it's much better) and fix this revision.

            Build 2 


            Tester guys from university, apart from finding a couple of bugs in rev. 1, didn't like using barrel connectors at all. Wires kept falling out of them when people didn't tighten screws enough and snapping when they tried too hard. Oh, and they look way too bulky and outdated, so I've been asked to find a way to eliminate them altogether.

            Here's what I managed to devise second time:

            Rev. 2 rendered in Kicad
             Notice some vital features I added/changed:
            •  Barrel receptables dropped in favor of spring cage terminals - you can just plug the bare wire directly to the board now.
            • Separate fused connection for lamps (optocouplers need them to detect a broken beam of light when something passes a particular point on a conveyor for instance).
            • PTC fuses on each digital output - now careless freshmen can short-circuit anything they like without burning my board!
            • Silkscreen is more informative now - it's possible to assemble the board without its schematic as all the values are printed directly in silk. Now I can hand over the assembly part to undergrad students and rest assured they won't mess it up (or at least be more sure than usual...)
            • Smaller relays.
            • You can pick PWM voltage between 9 and 24V.
            • 10V output to power analog sensors.
            • Smoothing capacitors on 24V, 10V and 9V power rails.
            • Power indication on 9V input.
            • LEDs are surface mount now except 9V power indication.
            • Stand-offs were added around 40-pin and 10-pin IDC connectors to prevent board bending and snapping while plugging male connectors.
            Now, some pictures of the build as usual...

            Top side
            Bottom side

            Board were ordered from PCBWay again (I'm not affiliated with them, it's just they offered the cheapest quote for this revision of the board, too).

            Top side
            Bottom side with plastic standoffs

            Even a couple of vanity shots. She looks beautiful, doesn't she?
             

            Board being used - now connecting a peripheral device is as simple as pressing a terminal's fin with a screwdriver and plugging in your wire.
            All 5 boards assembled and ready to go.
            Here's the link to all the sources of this board.

            A little extra


            As a bonus, I designed this little contraption to mount my rev. 2 board on a DIN rail, which is an industry standart too BTW.


            Now this can go in a real control cabinet together with PLCs and relays.
            I'm feeling generous today with models any idiot can design, so I'm sharing this too. It was made with Autodesk Inventor.

            The result


            I wouldn't start and proceed through this great undertaking if it wasn't for my overwhelming desire to see the fruits of my work.

            Alma-mater used those boards not only to teach some bright minds to become undustry-affiliated programmers one day, but also to organize a region-wide contest in PLC programming.

            I'll now indulge myself in uploading innumerous pictures of my boards being used in this contest and in process of teaching. One picture is worth a thousand words, so what comes next could probably populate a skinny paperback book. 😀







            photoplaceholder photoplaceholder


            photoplaceholder photoplaceholder


            Here's even a video:


            Пивоварня из стиральной машины

            $
            0
            0


            Сегодня я покажу как начать варить пиво при наличии большого желания, кучи хлама и отсутствия денег. Именно будучи в такой ситуации я решил переделать активаторную стиральную машинку советских времен "Вятка"в емкость для варения пива.

            После прочтения кучи текста про пивоварение в интернете я понял, что для варения пива обычно надо много емкостей большого объема, и чем их больше - тем проще (меньше переливаний из 1 во второй а потом обратно). Но потом я нашел интересный и простой метод варки в 1 емкости : BIAB (brew in a bag или варка в мешке). Хорошее руководство с картинками можно найти ТУТ (английский).

            Будучи любителем автоматизации, я сразу заметил то, что неплохо бы температурные паузы при пивоварении поддерживать при помощи микроконтроллера. Таким и появился монстр под названием "Стиральная-Машинка-Автоматизированная-Пивоварня".

            Чтобы варить зерновое пиво обычным методом(не в мешке),  потребуется немного дополнить получившуюся машину, что я также опишу в отдельной главе.

            Стиральная машина

            Имеем стиралку Вятка активаторную (это значит что она устроена не как современные машинки с барабаном который крутится, а с баком внизу которого крутится что-то вроде плоской мешалки). Объем бака 28 литров, слив воды - снизу. Бак формы цилиндра срезанного снизу, что очень удобно для слива сусла по максимуму.

            Так выглядела моя Вятка до модификаций. (только более ржавая)

            Для контроля температуры надо установить в бак нагревательный элемент и датчик температуры. Понадобится следующее:

            Нагревательный элемент - плоский или
            трубочный. Добывается из чайника
            Датчик температуры - у меня DS18B20,
            желательно сразу с гильзой для вворачивания в
            стенку емкости. Покупается в Китае.

            Также понадобится что-то чем прикрепить нагреватель к емкости. Сначала я купил для этого тюбик холодной сварки. Не делайте этого!"Холодная сварка" - это всего лишь двухкомпонентная эпоксидная смола и не пригодна для контакта с пищей. Стоит поискать какой-то клей для пищевой промышленности (я не нашел) либо вообще использовать силиконовые/металлические прокладки для соединения (что я и сделал, описано ниже).

            Итак, вырезаем активатор и на его место вставляем нагревательный элемент. Также где-нибудь в емкость врезаем датчик температуры.

            После этого добавляем кран для слива сусла:

            Отверстие для слива и кран в стенке соединяет обычная короткая гибкая подводка. Разумеется, не стоит забывать про силиконовую шайбу на отверстии для слива (на картинке резиновая, с такой пиво будет на вкус как резина 😄)

            UPDATE: 

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

            На фото показаны элементы фильтра (змеюка и крепление для ситечка из 2 шурупов и защелки),
            которые не нужны для варки в мешке, потому что мешок сам фильтрует сусло.

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

            Алюминиевая шайба прикрепляется на емкость болтами, соединение прокладывается силиконом. Где достать силикон? Покупаем круглую силиконовую форму для выпечки в магазине. Вот фото в процессе и результат:


            Электроника

            Те, у кого не чешутся руки изобретать велосипед, могут взять в Китае PID-регулятор и пропустить сборку электроники и написание кода.  А я такой 😊

            Сразу прикреплю схему управляющей коробки - она простая и не требует множества пояснений. Для вывода информации используется знакосинтезирующий дисплей (ищется по ключевому слову hd44780 на алиэкспрессе и проч.), для ввода - 3 кнопки и энкодер. Питание коммутирую при помощи твердотельного реле аж на 25 китайских ампер, что примерно равно 10 настоящим амперам нагревателя.


            Собрал все в корпусе от ATX блока питания, от другого БП взял 12 и 5 В (перебор, конечно, но у меня валялось полно этих блоков). Прилагаю фото сборки и готового устройства:

            Врезаем органы управления в переднюю панель...
            Крепим Ардуино вертикально чтобы сэкономить место.
            Почти готово. Огромный радиатор - перебор, но это лучше чем перегрев :)
            Коробка собрана и залита пробная программа.
            Вся система. Снизу БП, сверху система управления с торчащим из нее датчиком. Питание на нагреватель подается белым кабелем папа-мама.
            Белый шнур дает 220В на нагреватель, питание электроники осуществляется отдельно через черный шнур (в нем 12В+5В+GND). Провод в белом вводе - датчик температуры.
            USB порт для удобства выведен наружу.
            Черный кабельный ввод - для подключения нагревателя.
            Блок управления врезанный в корпус от стиральной машинки.
            IT'S ALIVE!!!

            Код:

            В начале кода есть кое-какие полезные подстройки, такие как:

            • #define DEBUG - режим отладки. Я включал его во время разработки программы, потом выключал. При нем включается вывод многих  событий в Serial, например нажатия кнопок, переключения режимов. Обычно когда код готов и все оборудование работает, я эту строку комментирую. 
            • #define PLOT - режим построения графика температуры. Значения температуры выводятся в Serial real-time для построения графика. Незаменимо для настройки PID алгоритма, потом можно и отключить.
            • Режимы DEBUG и PLOT несовместимы друг с другом, потому что выводят в один и тот же порт разную инфу. Построение графика при DEBUG работать не будет.
            • #define USE_EEPROM - советую раскомментировать после настройки PID алгоритма, тогда все параметры будут сохраняться/загружаться в постоянную память.

            const int WindowSize = 5000; - размер "окна"в течение которого происходит 1 цикл включение-выключение реле (здесь 5с). Что-то вроде периода медленного ШИМ сигнала.

            const double maxKp = 10000;
            const double maxKi = 5000;
            const double maxKd = 1000; - пределы подстройки коэффициентов пользователем. Взял их от балды, но вдруг кому-то понадобится больше.

            Библиотеки, нужные для компиляции кода, можно установить прямо из Arduino IDE.

            Теперь сам КОД:



            Когда код залит и работает, получим самодельный PID регулятор:


            Настройка

            После того как все собрано и запрограммировано, самое время настроить PID алгоритм.

            Надо подстроить коэффициенты Kp, Ki и Kd под конкретный объект (именно ваш нагреватель, котел, объем воды и т.д.). Я делал это следующим образом:

            1. Объекты с медленно меняющимся контролируемым параметром (температурой в моем случае) обычно работают с большим Kp, малым Ki и нулевым Kd. В итоге должен получиться именно такой результат.
            2.  Начинаем с малого Kp, нулевого Ki и Kd. Насколько малый? В данный момент не скажешь точно, но можно взять минимальное значение при котором нагреватель будет всегда включен при разнице между заданной и текущей температурой в 10 градусов.
            3. Заливаем код с режимом PLOT, подключаем Arduino к ПК и запускаем Serial plotter в Arduino IDE. Включаем нагрев и видим медленно ползущий вверх график:
              А также медленно нагревающуюся воду...
            4. Рано или поздно текущая температура начнет колебаться вокруг заданной:
              Setpoint = 40C
            5. Удваиваем Kp до тех пор, пока колебания не станут периодичными. Затем берем Kp в 2 раза меньше, чтобы колебания были либо стабильные, либо вообще отсутствовали.
            6. Устанавливаем небольшой Ki. Удваиваем его пока не начнутся колебания, затем берем его в 2 раза меньше, чтобы колебаний не было.
            Если что-то не получается - бежим читать интернеты (я читал здесь) либо делаем все путем проб и ошибок (зная что будет большое значение Kp, малое Ki и нулевое Kd).

            Опционально

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

            Здесь защелка сварена с ситечком - плохое решение, будет ржаветь. Надо сделать несварное соединение на болтах.

            Также для фильтрации сусла надо установить фильтрующую систему и кран для слива сусла. Для этого в любом хозяйственном магазине покупаем следующуий набор (все размеры 1/2"):
            • Гибкая подводка 1м
            • Сгон
            • 2 гайки
            • 2 металлические шайбы
            • 2 резиновые прокладки
            • Гибкая подводка 30см
            • Резиновая прокладка
            • Кран



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

            Готовый фильтр из оплетки.
            Бак с фильтром - вид снаружи. К гибкой подводке привинчивается кран.
            Бак с фильтром - вид изнутри. Также хорошо видно сито над нагревателем.

            Варим

            Про саму варку в мешке читайте в следующем посте:

            TBD
              Viewing all 66 articles
              Browse latest View live