Arduino это нечто — это выход в реальность из компьютерного мира — и главное за дешево(места знать надо)!!! Вообще Arduino это упрощенная платформа для программирования микроконтроллеров. Arduino Open Source — хошь бери чертежи и паяй один в один только Arduino не называй, это только фабрика в Италии может делать. Китайцы, естественно берут и неменя имен продают, если вы покупаете Arduino Uno R3 дешевле 1200 рублей(это если тупо умножить 20 евро на 60, а если тупо искать то у нас можно и за 1790 Арудуину купить) — знайте это не Италия. Ну а в моем случае :@) китайцы вообще взяли и сделали по своему — но работает также!!!
Называется это как Arduino Uno R3 но с чипом CH340G для USB, и Atmel mega328P здесь не огромный, а маленький как в Arduino MINI. Брал тут за 216 рублей, если USB кабель не нужен(пригодится для питания) то можно и за 171 рубль найти! Я кстати сразу взял набор, чтобы лампочками мигать вот такой.
У кого-то возникают проблемы с подключением этой Ардуины, в основном на Windows из-за отсутствия драйверов для CH340G, у меня Ubuntu завелся вообще без проблем, ставил из Центра Приложений Ubuntu
И того нам потребуются провода и бочки из набора, и следующее.
Ethernet Shield W5100 — тоже конечно клон-клона стоит 350 рублей брал тут. Штука с массой ограничений но на одном IP(получение по DHCP нет) на одном порту позволяет запускать веб сервер, карта SD для красоты — вместе они не работают только по очереди! Да и скорость у него всего 10 мега бит! Еще жалуются что он греется, ну да греется, но не горит же, вообще чип старый просто уже есть W5500 — но дорого!
Да и у меня же светодиот желтый на ней взорвался, когда подключил, но все таки думаю он коротнул об USB разъем на Arduino (надо его изолентой изолировать). Штуку надо плотно засаживать и смотреть чтобы ноги не прогнулись, до конца не встанет мешает USB порт как раз, а если не до конца то некоторый разъемы могут не работать!
С этим Ethernet Shield W5100 есть совершенно известная и идиотская проблема — может не включиться. Народ че-то паяет, и шаманит с кодом, мне кажется помог совет вот тут внизу http://forum.arduino.cc/index.php?topic=28175.30 так же ставил delay в setup… хотя нет, не помогло… говорят если перепоять кое что то будет грузитья само wiznetmuseum.com/portfolio-items/arduino-wiznet-ethernet-shield-proper-reset/
Датчик движения HC-SR501 хк SR501 брал тут за 60 рублей — делает то что должен и всего лишь за 60 рублей. На нем есть регуляторы расстояния срабатывания 3-7 метра и продолжительности сигнала срабатывания от 5 до 200 секунд — нужная штука.
И датчик температуры и влажности Dht22, Am2302 брал за 171 тут дорогой но у него большие рабочие температуры -40 ~ 80 Celsius
Датчик силы света — фоторезистор и сопротивления 2 по 10К брал из набора
Далее все просто, просто собираем, чтобы было как на фото…
…шутка! Собираем не как на фото а как на схеме!
Fritzing на Ubuntu прекрасно работает в части рисования, в построении электро-схем вообще никак не работает, наверное потому что все еще beta(в Windows тоже beta может он всегда beta)!
Прежде чем писать в Ардуино нужно скачать библиотеку для DHT22 вот тут скачивать надо ZIP архивом, кнопка справа по середине и добавить в проге через добавить библиотеку… так пишут но так не сработало у меня! Не помню точно, вроде я сразу разархивирование сюда /usr/share/arduino/libraries
Для Ethernet shield билиотека вроде как есть уже
Вот сам скетч (код надерган из массы примеров) — запускает веб сервер печатает в него с датчиков инфу, и в последовательный порт тоже пишет для диагностики:
#include <DHT.h> #include <SPI.h> #include <Ethernet.h> //move int pirPin = 3; // for DHT22 sensor //#include "DHT.h" #define DHTPIN 2 #define DHTTYPE DHT22 //light const int pinPhoto = A0; int raw = 0; // Enter a MAC address and IP address for your controller below. // The IP address will be dependent on your local network: // Enter a MAC address and IP address for your controller below. // The IP address will be dependent on your local network: byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; byte ip[] = { 192, 168, 1, 177 }; byte gateway[] = { 192, 168, 1, 1 }; byte subnet[] = { 255, 255, 255, 0 }; // Initialize the Ethernet server library // with the IP address and port you want to use // (port 80 is default for HTTP): EthernetServer server(80); // Initialize the Ethernet server library // with the IP address and port you want to use // (port 80 is default for HTTP): EthernetServer server(80); DHT dht(DHTPIN, DHTTYPE); void setup() { dht.begin(); // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } // start the Ethernet connection and the server: Ethernet.begin(mac, ip); server.begin(); Serial.print("server is at "); Serial.println(Ethernet.localIP()); } void loop() { // listen for incoming clients EthernetClient client = server.available(); if (client) { Serial.println("new client"); // an http request ends with a blank line boolean currentLineIsBlank = true; while (client.connected()) { if (client.available()) { char c = client.read(); Serial.write(c); // if you've gotten to the end of the line (received a newline // character) and the line is blank, the http request has ended, // so you can send a reply if (c == '\n' && currentLineIsBlank) { // send a standard http response header client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println("Connection: close"); // the connection will be closed after completion of the response client.println("Refresh: 30"); // refresh the page automatically every 30 sec client.println(); client.println("<!DOCTYPE HTML>"); client.println("<html>"); // get data from DHT22 sensor float h = dht.readHumidity(); float t = dht.readTemperature(); raw = analogRead( pinPhoto ); Serial.println(raw); Serial.println(t); Serial.println(h); //delay(500); // from here we can enter our own HTML code to create the web page client.print("<head><title> Home Weather</title></head><body><h1>Home Temperature</h1><p>Temperature - <font color=#880000><b>"); client.print(t); client.print("</b></font> degrees Celsius</p>"); client.print("<p>Humidity - <font color=#0066FF><b>"); client.print(h); client.print("</b></font> percent</p>"); client.print("<p>Light - <font color=#FFCC33><b>"); client.print(raw); client.print("</b></font> heze</p>"); long now = millis(); if (digitalRead(pirPin) == HIGH) { client.print("<p>Moving - "); client.print("<font color=#6600CC><b>YES o YES</b></font></p>"); } client.print("<p><em>Page refreshes every 30 seconds.</em></p></body></html>"); break; } if (c == '\n') { // you're starting a new line currentLineIsBlank = true; } else if (c != '\r') { // you've gotten a character on the current line currentLineIsBlank = false; } } } // give the web browser time to receive the data delay(1); // close the connection: client.stop(); Serial.println("client disonnected"); } }
Переходим на 192.168.1.177 и получаем вот такую страницу
Теперь собираем храним данные с Arduino и строим график!
Меняем скетч на этот, чтобы данные выводились одной строкой
#include <DHT.h> #include <SPI.h> #include <Ethernet.h> //move int pirPin = 3; // for DHT22 sensor //#include "DHT.h" #define DHTPIN 2 #define DHTTYPE DHT22 DHT dht(DHTPIN, DHTTYPE); //light const int pinPhoto = A0; int raw = 0; // Enter a MAC address and IP address for your controller below. // The IP address will be dependent on your local network: byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; byte ip[] = { 192, 168, 1, 177 }; byte gateway[] = { 192, 168, 1, 1 }; byte subnet[] = { 255, 255, 255, 0 }; // Initialize the Ethernet server library // with the IP address and port you want to use // (port 80 is default for HTTP): EthernetServer server(80); // Initialize the Ethernet server library // with the IP address and port you want to use // (port 80 is default for HTTP): EthernetServer server(80); void setup() { delay(500); // Open serial communications and wait for port to open: // Serial.begin(9600); // while (!Serial) { // ; // wait for serial port to connect. Needed for Leonardo only // } // start the Ethernet connection and the server: Ethernet.begin(mac, ip); dht.begin(); } void loop() { // listen for incoming clients EthernetClient client = server.available(); if (client) { Serial.println("new client"); // an http request ends with a blank line boolean currentLineIsBlank = true; while (client.connected()) { if (client.available()) { char c = client.read(); Serial.write(c); // if you've gotten to the end of the line (received a newline // character) and the line is blank, the http request has ended, // so you can send a reply if (c == '\n' && currentLineIsBlank) { // send a standard http response header client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println("Connection: close"); // the connection will be closed after completion of the response client.println("Refresh: 30"); // refresh the page automatically every 30 sec client.println(); // get data from DHT22 sensor float h = dht.readHumidity(); float t = dht.readTemperature(); raw = analogRead( pinPhoto ); //delay(500); // from here we can enter our own HTML code to create the web page client.print(t); client.print(" "); client.print(h); client.print(" "); client.print(raw); client.print(" "); long now = millis(); if (digitalRead(pirPin) == HIGH) { client.print("1"); } else { client.print("0"); } break; } if (c == '\n') { // you're starting a new line currentLineIsBlank = true; } else if (c != '\r') { // you've gotten a character on the current line currentLineIsBlank = false; } } } // give the web browser time to receive the data delay(1); // close the connection: client.stop(); Serial.println("client disonnected"); } }
Ардуино по IP теперь показывает одну строчку
Строим графики. Для этого надо как-то по сети снимать значения
попытаемся читать их консольным браузером, ставим Lynx
cd /usr/ports/www/lynx
make
make install
В консоли запускаем и получаем ту же строку
lynx -source 192.168.1.177
Делаем скрипт для записи это строки плюс время
cd /root
vi andmon.sh
вставляем
#!/usr/local/bin/bash d=`/usr/local/bin/lynx -source -connect_timeout=10 192.168.1.177` if [ -z "$d" ] then t=`/bin/date +%Y"."%m"."%d"-"%H":"%M" "` data=`/bin/cat /var/log/mon.log | /usr/bin/tail -n -1 | /usr/bin/awk '{print $2, $3,$4,$5,$6}'` /bin/echo "${t}${data}" >> /var/log/mon.log exit elif ! [ -z "$d" ] then t=`/bin/date +%Y"."%m"."%d"-"%H":"%M" "` /bin/echo ${t}${d} >> /var/log/mon.log fi
С крипт с защитой от пустой строки и ограничением по времени ответа
Даем права на исполнение
chmod +x andmon.sh
И засовываем в расписание, чтобы снимать значения 1 раз в минуту
crontab -e
строчку
*/1 * * * * /root/andmon.sh
Получаем файл с таким текстом
2015.11.04-19:46 25.50 43.10 743 0
2015.11.04-19:47 25.70 45.80 739 0
2015.11.04-19:48 25.70 45.60 742 0
2015.11.04-19:49 25.70 45.60 738 0
2015.11.04-19:50 25.70 43.70 741 0
Теперь ставим рисовалку графиков Gnuplot (Шикарная вещь, как жалко что раньше графики были не нужны)
cd /usr/ports/math/gnuplot
make
make install
Графики надо куда то класть чтобы смотреть. Вэб сервер Apache у меня уже стоит, ну естественно, делаем там любую папочку
mkdir /usr/local/www/apache22/data/arduino
chown www:www /usr/local/www/apache22/data/arduino
Делаем скрипт для отрисовки png с графиком
cd /root
vi plot_h.sh
вставляем
#!/bin/bash /bin/cat /var/log/mon.log |/usr/bin/tail -n -60 | /usr/bin/xargs -n 5 /bin/echo > /var/log/mon_last_h.log /usr/local/bin/gnuplot << EOF set terminal png size 800,500 set output '/usr/local/www/apache22/data/arduino/mon_lat_h_th.png' set key inside left set autoscale y set autoscale x set grid set ytics 1 set y2tics 1 set xtics 1 font "Verdana, 10" rotate 90 set xdata time set timefmt "%Y.%m.%d-%H:%M" set format x "%H:%M" set title 'Home Temperature and Humidity' #set yrange [-40:100] set xlabel 'time' set ylabel 'C/%' plot '/var/log/mon_last_h.log' u 1:2 with lines linetype 1 t 'temperature C', '/ var/log/mon_last_h.log' u 1:3 with lines linetype 5 t 'humidity %' EOF
Здесь /usr/bin/tail -n -60 значит берем последние 60 значений из файла /var/log/mon_last_h.log тоесть график будет за час
Даем права на исполнение
chmod +x plot_h.sh
Выполняем
sh plot_h.sh
Получаем вот такую картинку
Теперь добавим в этот скрипт еще и графики света и движения, вот все вместе
#!/bin/bash /bin/cat /var/log/mon.log |/usr/bin/tail -n -60 | /usr/bin/xargs -n 5 /bin/echo > /var/log/mon_last_h.log /usr/local/bin/gnuplot << EOF set terminal png size 800,500 set output '/usr/local/www/apache22/data/arduino/mon_lat_h_th.png' set key inside left set autoscale y set autoscale x set grid set ytics 1 set y2tics 1 set xtics 1 font "Verdana, 10" rotate 90 set xdata time set timefmt "%Y.%m.%d-%H:%M" set format x "%H:%M" set title 'Home Temperature and Humidity' #set yrange [-40:100] set xlabel 'time' set ylabel 'C/%' plot '/var/log/mon_last_h.log' u 1:2 with lines linetype 1 t 'temperature C', '/ var/log/mon_last_h.log' u 1:3 with lines linetype 5 t 'humidity %' EOF /usr/local/bin/gnuplot << EOF set terminal png size 800,200 set output '/usr/local/www/apache22/data/arduino/mon_lat_h_m.png' set key inside left set autoscale x set grid set ytics 1 set xtics 1 font "Verdana, 10" rotate 90 set xdata time set timefmt "%Y.%m.%d-%H:%M" set format x "%H:%M" set title 'Home moving' set yrange [0:1] set xlabel 'time' set ylabel '1=yes' set boxwidth 0.95 relative set style fill transparent solid 0.5 noborder plot '/var/log/mon_last_h.log' u 1:5 w boxes lc rgb"green" notitle EOF /usr/local/bin/gnuplot << EOF set terminal png size 800,400 set output '/usr/local/www/apache22/data/arduino/mon_lat_h_l.png' set key inside left set autoscale x set grid set ytics 75 set xtics 1 font "Verdana, 10" rotate 90 set xdata time set timefmt "%Y.%m.%d-%H:%M" set format x "%H:%M" set title 'Home Light' set yrange [500:1100] set xlabel 'time' set ylabel 'light' plot '/var/log/mon_last_h.log' u 1:4 w lines lc rgb"orange" notitle EOF
Скрипт будем запускать каждые 5 минут
crontab -e
добавляем строчку
*/5 * * * * /bin/sh /root/plot_h.sh
именно с /bin/sh
Сделаем простой HTML чтобы показывал сразу три картинки
vi /usr/local/www/apache22/data/arduino/index.html
Вставляем
<!DOCTYPE html> <html> <head> <title>Home Stat</title> </head> <body> <img src=./mon_lat_h_th.png border=0><br> <img src=./mon_lat_h_l.png border=0><br> <img src=./mon_lat_h_m.png border=0><br> </body> </html>
Заходим по адресу вашего сервера, у меня это http://192.168.2.200/arduino/ и получаем!!!
Наблюдения
Людское тело неимоверно сырое, в полуметре сразу же подымает влажность на 6-7% и температуру тоже на 1-2 градусу (может это только мое тело, у меня большая поверхность тепло рассеивания). Также по графику можно заметить просто открытие двери в комнате.
Фоторезистор, тоже справляет, он не дает значение в Люуксах(симла света?) но можно всегда оценить что в комнате происходить: примерно 500 это темнота, плюс 125 лампа, солнце 900-1000.
Движение работает да, намного страшно смотреть ночной график, а вдруг кто-то ходит…
UPD: Паяим все на лысую плату шильда для Ардуино. Профит — на фото До и После
Покупал вот эту плату Бесплатная доставка стандартный прото винт щит для Arduino совместимый улучшенная версия поддержка A6 A7 и вот эти 10 шт. 4PIN однорядные 1 x 4 т ряд иглы разъем мать строка. Паяльник, что удивительно покупал не в Китае, а за тежи деньги в OBI — 30W на нем прям электро схемы нарисованы.
Платы замечательные, 5V и GND в ней проведены к площадке слева, удобно припаивать. Для меня остался вопрос что использовать для соединения дальных дырок — провода очень неудобно. Легче всего оказалось паять ножки, они прям сами в каплю чпок!
На фото, плата с отпиленным кусочком чтобы встало в шилд W5100 — который все таки какойто кривой — он не встает глубоко в Ардуино, мешат в месте где RJ45 — пришлось даже подпилить чуть-чуть!
Вот так все выглядит в сборе — культурно даже кажется!
UPD: Удалось добавить еще датчиков, эркна и засунуть в корпус!
Были добавлены
— Mq-135 воздушный и опасных газ обнаружения датчик сигнализация
— DS3231 AT24C32 IIC модуль точность часов реального времени
— Жк-дисплей модуль синий экран IIC / I2C 1602 вот этот распаянный Special-promotions-LCD-module-Blue-screen-IIC-I2C-1602-LCD/32272410945.html
Чтобы часы работали
надо скачать и добавить вот эти библиотеки
https://github.com/PaulStoffregen/Time
https://github.com/PaulStoffregen/DS1307RTC
Добавить как обычно, я разархивировал убирал из названия «-» и добавлял через ПО Ардуино попку уж. А в папку с библиотекой DS1307RTC надо вставить из папки с основными библиотеками Ардунино два файла Wire.h и Wire.cpp и папку Utility все они лежать в папке Wire
Схемка распайки усложнилась, но так как я не умел паять и до сих пор не умею — то, что все в результате все таки получилось — считаю нереальным успехом!
Расстраивает что Ethernet Shield W5100 так и продолжает не включатся после включения Arduino (говорят что W5100 слишком долго грузится и не успевает) — только нажав кнопку Reset оно стратует — поэтому я нажимаю на кнопку Reset когда нужны сетевые возможно… вообще то до кнопки добраться тяжело, поэтому вывил её на корпус(на фото нет)
Скетч для Ардуино
#include <SPI.h> #include <Ethernet.h> #include <DHT.h> #include <DS1307RTC.h> #include <Wire.h> #include <LCD.h> #include <LiquidCrystal_I2C.h> #include <Time.h> #define DHTPIN 2 #define DHTTYPE DHT22 LiquidCrystal_I2C lcd(0x3f, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Addr, En, Rw, Rs, d4, d5, d6, d7, backlighpin, polarity DS1307RTC rtc; //move int pirPin = 3; // for DHT22 sensor //#include "DHT.h" DHT dht(DHTPIN, DHTTYPE); //light const int pinPhoto = A0; int raw = 0; int ap = 0; // Enter a MAC address and IP address for your controller below. // The IP address will be dependent on your local network: byte mac[] = { 0xDE, 0xAD, 0xAD, 0xEF, 0xFE, 0xDE }; byte ip[] = { 192, 168, 1, 177 }; // Initialize the Ethernet server library // with the IP address and port you want to use // (port 80 is default for HTTP): EthernetServer server(80); void setup() { lcd.begin(16,2); lcd.backlight(); lcd.setCursor(0, 0); lcd.print("[ "); lcd.setCursor(7, 0); lcd.print(" ]"); lcd.setCursor(4, 0); lcd.print(":"); lcd.setCursor(10, 0); lcd.print("AP:"); lcd.setCursor(0, 1); lcd.print("t:"); lcd.setCursor(9, 1); lcd.print("h:"); // Open serial communications and wait for port to open: //Serial.begin(9600); //while (!Serial) { //; // wait for serial port to connect. Needed for Leonardo only // } Ethernet.begin(mac, ip); server.begin(); dht.begin(); } void loop() { // listen for incoming clients EthernetClient client = server.available(); if (client) { Serial.println("new client"); // an http request ends with a blank line boolean currentLineIsBlank = true; while (client.connected()) { if (client.available()) { char c = client.read(); Serial.write(c); // if you've gotten to the end of the line (received a newline // character) and the line is blank, the http request has ended, // so you can send a reply if (c == '\n' && currentLineIsBlank) { // send a standard http response header client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println("Connection: close"); // the connection will be closed after completion of the response client.println("Refresh: 30"); // refresh the page automatically every 30 sec client.println(); // get data from DHT22 sensor float h = dht.readHumidity(); float t = dht.readTemperature(); raw = analogRead( pinPhoto ); ap = analogRead(2); //delay(500); // from here we can enter our own HTML code to create the web page client.print(t); client.print(" "); client.print(h); client.print(" "); client.print(raw); client.print(" "); client.print(ap); client.print(" "); long now = millis(); if (digitalRead(pirPin) == HIGH) { client.print("1"); } else { client.print("0"); } break; } if (c == '\n') { // you're starting a new line currentLineIsBlank = true; } else if (c != '\r') { // you've gotten a character on the current line currentLineIsBlank = false; } } } // give the web browser time to receive the data delay(1); // close the connection: client.stop(); Serial.println("client disonnected"); } tmElements_t tm; if (RTC.read(tm)) { print2digits(tm.Hour); print2digits(tm.Minute); print2digits(tm.Second); } else { } //lcd.setCursor(2, 0); // lcd.print(" "); // lcd.setCursor(2, 0); // lcd.print(tm.Hour); if (tm.Hour <= 9 ) { lcd.setCursor(2, 0); lcd.print(" "); lcd.setCursor(3, 0); lcd.print(tm.Hour);} else { lcd.setCursor(2, 0); lcd.print(tm.Hour); } // lcd.setCursor(5, 0); // lcd.print(" "); // lcd.setCursor(5, 0); // lcd.print(tm.Minute); if (tm.Minute <= 9 ) { lcd.setCursor(5, 0); lcd.print("0"); lcd.setCursor(6, 0); lcd.print(tm.Minute);} else { lcd.setCursor(5, 0); lcd.print(tm.Minute); } lcd.setCursor(13, 0); lcd.print(" "); lcd.setCursor(13, 0); lcd.print(analogRead(2)); lcd.setCursor(2, 1); lcd.print(dht.readTemperature()); lcd.setCursor(11, 1); lcd.print(dht.readHumidity()); delay(500); } void print2digits(int number) { if (number >= 0 && number < 10) { } }
Скрипты рисования картинок
/root/plot_h.sh
#!/bin/bash /bin/cat /var/log/mon.log |/usr/bin/tail -n -60 | /usr/bin/xargs -n 6 /bin/echo > /var/log/mon_last_h.log /usr/local/bin/gnuplot << EOF set terminal png size 800,500 set output '/usr/local/www/apache22/data/arduino/mon_lat_h_th.png' set key inside left set autoscale y set autoscale x set grid set ytics 1 set y2tics 1 set xtics 1 font "Verdana, 10" rotate 90 set xdata time set timefmt "%Y.%m.%d-%H:%M" set format x "%H:%M" set title 'Home Temperature and Humidity' #set yrange [-40:100] set xlabel 'time' set ylabel 'C/%' plot '/var/log/mon_last_h.log' u 1:2 with lines linetype 1 t 'temperature C', '/ var/log/mon_last_h.log' u 1:3 with lines linetype 5 t 'humidity %' EOF /usr/local/bin/gnuplot << EOF set terminal png size 800,200 set output '/usr/local/www/apache22/data/arduino/mon_lat_h_m.png' set key inside left set autoscale x set grid set ytics 1 set y2tics 1 set xtics 1 font "Verdana, 10" rotate 90 set xdata time set timefmt "%Y.%m.%d-%H:%M" set format x "%H:%M" set title 'Home moving' set yrange [0:1] set xlabel 'time' set ylabel '1=yes' set boxwidth 0.95 relative set style fill transparent solid 0.5 noborder plot '/var/log/mon_last_h.log' u 1:6 w boxes lc rgb"green" notitle EOF /usr/local/bin/gnuplot << EOF set terminal png size 800,400 set output '/usr/local/www/apache22/data/arduino/mon_lat_h_ap.png' set key inside left set autoscale x set grid set ytics 5 set y2tics 5 set xtics 1 font "Verdana, 10" rotate 90 set xdata time set timefmt "%Y.%m.%d-%H:%M" set format x "%H:%M" set title 'Air Polution' #set yrange [500:1100] set xlabel 'time' set ylabel 'AP' plot '/var/log/mon_last_h.log' u 1:5 w lines lc rgb"green" notitle EOF /usr/local/bin/gnuplot << EOF set terminal png size 800,400 set output '/usr/local/www/apache22/data/arduino/mon_lat_h_l.png' set key inside left set autoscale x set grid set ytics 75 set xtics 1 font "Verdana, 10" rotate 90 set xdata time set timefmt "%Y.%m.%d-%H:%M" set format x "%H:%M" set title 'Home Light' set yrange [500:1100] set xlabel 'time' set ylabel 'light' plot '/var/log/mon_last_h.log' u 1:4 w lines lc rgb"orange" notitle EOF
/root/plot_24h.sh
#!/bin/bash /bin/cat /var/log/mon.log |/usr/bin/tail -n -1440 | /usr/bin/xargs -n 6 /bin/ech o > /var/log/mon_last_24h.log /usr/local/bin/gnuplot << EOF set terminal png size 800,500 set output '/usr/local/www/apache22/data/arduino/mon_lat_24h_th.png' set key inside left set autoscale y #set autoscale x set grid set ytics 1 set y2tics 1 set xdata time set timefmt "%Y.%m.%d-%H:%M" set format x "%H" #set xtics 6 font "Verdana, 10" rotate 90 set title '24H Home Temperature and Humidity' #set yrange [-40:100] set xlabel 'time' set ylabel 'C/%' plot '/var/log/mon_last_24h.log' u 1:2 with lines linetype 1 t 'temperature C', '/var/log/mon_last_24h.log' u 1:3 with lines linetype 5 t 'humidity %' EOF /usr/local/bin/gnuplot << EOF set terminal png size 800,200 set output '/usr/local/www/apache22/data/arduino/mon_lat_24h_m.png' set key inside left set autoscale x set grid set ytics 1 #set xtics 1 font "Verdana, 10" rotate 90 set xdata time set timefmt "%Y.%m.%d-%H:%M" set format x "%H" set title '24H Home moving' set yrange [0:1] set xlabel 'time' set ylabel '1=yes' set boxwidth 0.95 relative set style fill transparent solid 0.5 noborder plot '/var/log/mon_last_24h.log' u 1:6 w boxes lc rgb"green" notitle EOF /usr/local/bin/gnuplot << EOF set terminal png size 800,500 set output '/usr/local/www/apache22/data/arduino/mon_lat_24h_ap.png' set key inside left set autoscale y set grid set ytics 10 set y2tics 10 #set xtics 1 font "Verdana, 10" rotate 90 set xdata time set timefmt "%Y.%m.%d-%H:%M" set format x "%H" set title '24H Air Polution' #set yrange [0:1] set xlabel 'time' set ylabel 'AP' #set boxwidth 0.95 relative #set style fill transparent solid 0.5 noborder plot '/var/log/mon_last_24h.log' u 1:5 w lines lc rgb"green" notitle EOF /usr/local/bin/gnuplot << EOF set terminal png size 800,400 set output '/usr/local/www/apache22/data/arduino/mon_lat_24h_l.png' set key inside left set autoscale x set grid set ytics 75 #set xtics 1 font "Verdana, 10" rotate 90 set xdata time set timefmt "%Y.%m.%d-%H:%M" set format x "%H" set title '24H Home Light' set yrange [500:1100] set xlabel 'time' set ylabel 'light' plot '/var/log/mon_last_24h.log' u 1:4 w lines lc rgb"orange" notitle EOF
/usr/local/www/apache22/data/arduino/index.html
<html> <head> <title>Home Stat</title> </head> <body> <img src=./mon_lat_h_th.png border=0><br> <img src=./mon_lat_h_ap.png border=0><br> <img src=./mon_lat_h_l.png border=0><br> <img src=./mon_lat_h_m.png border=0><br> <img src=./mon_lat_24h_th.png border=0><br> <img src=./mon_lat_24h_ap.png border=0><br> <img src=./mon_lat_24h_l.png border=0><br> <img src=./mon_lat_24h_m.png border=0><br> </body> </html>
Вот так выглядит страница с данными — сначала идут графики за час, потом за 24 часа — прямые линии это отсутсвие данных
UPD: Цена вопроса
Очень радует что в России микроэлектроника тоже развивается и появляются много новых качественных перепрадовцов. Например амперкару или чипдипру — ребята молодцы, кип гоинг, жиксу нули ба! Решился просто посчитать, что мне доставили бесплатно через 2 месяца из Китая и что я бы смог купить в России в общественно транспортной доступности сразу же!
…оказывается я не просто мега офигительную погодную станцию собрал(что следует просто из того что она все еще работает), но это еще и нереально дорогой — лакшари девайс!!!
Добавить комментарий