Skip navigation

Arduino

4 Posts authored by: matfur92    

(prev. post is Get a working webcam on Arduino Yun - The smart entrance - Internet of Holiday Lights RoadTest read this to have a working webcam on Arduino Yun)


In this post I will explain how to start a python script or possibly any other program / bash by our Arduino sketch Yun.
In particular, I am going to explain the procedure to have a motion detector (using a HC RS04 ultrasound sensor) that allows to send a photo by email in case it detects a change of distance of at least 2cm in two successive measurements in 'arc of about 60ms.

 

So let's see what are the steps necessary to accomplish this purpose.

 

Get a working python with support to HTTPS/SSL doing in SSH :

opkg update                      #updates the available packages list
opkg install distribute          #it contains the easy_install command line tool
opkg install python-openssl      #adds ssl support to python


 

I have positioned the sendemail.py (download it from attached file) in the /www/cgi-bin with FileZilla. [sendemail.py taken from http://dev.mikamai.com/post/76945627390/you-cant-touch-this-an-evil-arduino-based]

The sendmail.py was edited with my email ad login parameters of gmail.

IMPORTANT : go to https://www.google.com/settings/security/lesssecureapps and enable this option to have a working script!!

 

This is the script that I have loaded in my Arduino Yun that send an email when the distance have a delta > 2cm.

#include <Bridge.h>
#include <Wire.h>

//HC RS04 ultrasound sensor
int triggerPort = 4;
int echoPort = 2;

Process p;

void setup() {
    Wire.begin();
    Bridge.begin();
    Serial.begin(115200);

    //ultrasound sensor
    pinMode( triggerPort, OUTPUT );
    pinMode( echoPort, INPUT );

}

void commandGetImage(int n){
  p.runShellCommand("fswebcam --device /dev/video0 --resolution 640x480 --jpeg 95 --save /www/"+String(n)+".jpg --palette MJPEG --no-banner"); //takes the picture
  while(p.running()); //wait till the process ends
}

float getDistance(){
  digitalWrite( triggerPort, LOW );

  //send one impulse of 10microsec on trigger
  digitalWrite( triggerPort, HIGH );
  delayMicroseconds( 10 );
  digitalWrite( triggerPort, LOW );

  float duration = pulseIn( echoPort, HIGH );
  float centimeter = 0.034 * duration / 2;

  if( duration > 58000 ){
    duration=-1;
    centimeter=-1;
  }

  if (centimeter==0){
    Serial.println("ERROR - 0 cm - get again the distance");
    delay(10);
    centimeter=getDistance();
  }

  return centimeter;
}

void loop() {
    float d,prev=getDistance();
    float delta=0;

    while (true){
        delta=0;
        //get the first distance
        prev=getDistance();
        //get the image
        commandGetImage(0);//0.jpg is the image file taken
        //wait 50ms
        delay(50);
        //get the second distance
        d=getDistance();
        //calculate the delta
        delta=abs(d-prev);
        //if the delta is big send email - a movement is recognised!
        if(delta>2){
           Serial.print(" delta= "+String(delta) + "["+String(prev)+"cm,"+String(d)+"cm]");
           Serial.print("\nSENDING...");
          p.runShellCommand("python /www/cgi-bin/sendemail.py /www/" +String(0)+".jpg"); //sends the picture via email
          while(p.running()); //wait till the process ends
          Serial.println("E-MAIL SENDED");
        }else{
          Serial.print(".");
          delay(50);     
        }
    }
}


Today we will see how to run, on Arduino Yun, a webcam protocol compatible UVC (virtually every recent webcam supports this protocol).

 

First, install the sftp to read and write files into the Arduino Yun. From SSH do the following commands:

opkg update
opkg install openssh-sftp-server


Now we can access via SFTP with the same username and password that we used for the SSH to our Arduino Yun. For example I used FileZilla.

 

Then proceed with the installation of the driver to handle the webcam.

opkg update
opkg install kmod-video-uvc
opkg install fswebcam


 

Extract the files and place them with sftp in the annex for example in the /www/webcam/ . Position itself in this folder with cd /www/webcam/ and do the following command to install the mjpg-streamer :

opkg install mjpg-streamer_r148-4_ar71xx.ipk


 

Now you can connect the webcam with USB cable. If you have problems with the following commands reboot and try again with the following commands.

 

To view the current snapshot you must do:

mjpg_streamer -i "input_uvc.so -d /dev/video0 -y" -o "output_http.so"


It allow you to use the browser and, for example in my case, from http://192.168.1.10:8080/?action=snapshot you can view a snapshot in real time, if you refresh the page you can get a new snapshot. This method have the best image quality!

 

Another way to save an image is to use fswebcam. If you want to save on the /www/ you must do it:

fswebcam --device /dev/video0 --input 0 --resolution 640x480 --jpeg 95 --save /www/viewcam.jpg --palette MJPEG --no-banner


 

Another way to save images is to use a config file such as .fswebcam.conf with this content:

device /dev/video0
input 0
loop 15
skip 20
background
resolution 640x480
set brightness=60%
set contrast=13%
top-banner
font /usr/share/fonts/arial.ttf
title "ArduinoYunCAM"
timestamp "%d-%m-%Y %H:%M:%S (%Z)"
jpeg 95
save /www/viewcamC.jpg
palette MJPEG


And to use it go in the same directory and run:

fswebcam -c .fswebcam.conf


 

Other information are on:

- WebCam: Time-laps video

- WebCam: Using mjpeg streamer to stream video over HTTP

 

This is all for today...stay tuned to the next post, it will be about leds strips!

 

 

PS: If anyone have a problem with mjpg-straemer, my configuration file /etc/config/mjpg-streamer is:

config mjpg-streamer core
    option enabled        true
    option device        "/devices/platform/ehci-platform/usb1/1-1/1-1.1/1-1.1:1.0/input/input1"
    option resolution    "640x480"
    option fps        "5"
    option www        "/www/webcam"
    option port        "8080"

Another tips is to do:

/etc/init.d/mjpg-streamer enable
/etc/init.d/mjpg-straemer start

Hello everyone!


Here I am with the second step of my project. In previous point (http://www.element14.com/community/groups/arduino/blog/2014/12/23/the-smart-entrance--my-project-for-internet-of-holiday-lights-roadtest) I explained how to install mosquitto.

 

I go then to explain through a couple of pictures and code what I did to make it possible to write in the topic I chose updates of the data collected by the sensors.
Every 10 seconds my Arduino Yun reads data detected (humidity, temperature, air quality, fuel gases, flames and distance) from the sensors connected (see photo) and, through the MQTT protocol communicates them to the server.
To verify that everything happens correctly I installed in my smartphone "MyMQTT", a simple but powerful application to enroll in the topic, and also wanting to write messages on them. The configuration has only required the inclusion of IP of my server and the topic to which register.
Once started Arduino, as you can see from the screenshot, every 10 seconds, the topic is updated with the sensor data.


Below I leave you also also the code I used to be able to carry out the above and in the attached library for MQTT. Unfortunately this is not Paho as it is very greedy for space and occupied memory (about 92% against a 46% of this).


In the next post will address the issue in webcam and the one after that, hoping that the power pack, the pilot of the strip led according to the temperature received from the server using MQTT.

IMG_20150111_232113.jpgScreenshot_2015-01-11-23-32-23.png

 

#include <SPI.h>
#include <Bridge.h>
#include <YunClient.h>
#include <IPStack.h>
#include <Countdown.h>
#include <MQTTClient.h>
#include <Wire.h>
#include <dht11.h>
char printbuf[100];
// DHT11 sensor pins
dht11 DHT11;
#define DHT11_PIN 8 //pin number 8 of digital port
int pinSensoreFiamma = 7;
//HC RS04 ultrasound sensor
int triggerPort = 4;
int echoPort = 2;
YunClient yunClient;
IPStack ipstack(yunClient);
MQTT::Client<IPStack, Countdown> client = MQTT::Client<IPStack, Countdown>(ipstack);
byte mac[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; // replace with your device's MAC
const char* topic = "/smart_entrance/toYun"; // replace with your topic

void connect() {
    char hostname[] = "0.0.0.0"; // replace with your server IP or domain
    int port = 1883;
    sprintf(printbuf, "Connecting to %s:%d\n", hostname, port);
    Serial.print(printbuf);
    int rc = ipstack.connect(hostname, port);
    if (rc != 1) {
        sprintf(printbuf, "rc from TCP connect is %d\n", rc);
        Serial.print(printbuf);
    }
    Serial.println("MQTT connecting");
    MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
    data.MQTTVersion = 3;
    data.clientID.cstring = (char*) "arduino-yun"; //name of arduino on mosquitto
    rc = client.connect(data);
    if (rc != 0) {
        sprintf(printbuf, "rc from MQTT connect is %d\n", rc);
        Serial.print(printbuf);
    }
}

void setup() {
    Wire.begin();
    Bridge.begin();
    Serial.begin(115200);
    // sets the digital pin 7 as input
    pinMode(pinSensoreFiamma, INPUT);
    //ultrasound sensor
    pinMode( triggerPort, OUTPUT );
    pinMode( echoPort, INPUT );
    connect();
}

void loop() {
    if (!client.isConnected()){
        connect();
    }
    MQTT::Message message;
    while (true){
        int chk;
        Serial.print("DHT11, ");
        chk = DHT11.read(DHT11_PIN);    // READ DATA //pin number 8 of digital
        switch (chk){
          case DHTLIB_ERROR_CHECKSUM:
                      Serial.print("Checksum error, ");
                      break;
          case DHTLIB_ERROR_TIMEOUT:
                      Serial.print("Time out error, ");
                      break;
          default:
                      Serial.print("Unknown error, ");
                      break;
        }

        //MQ135 Air Quality Control
        float RoRs;
        int airqValue   = analogRead(0);    // read air quality sensor
        if(DHT11.temperature >=20.0&&DHT11.temperature<=50.0){//adjust for dependency on temperature
          RoRs = -0.0034 * DHT11.temperature + 1.067;
        }
        else if(DHT11.temperature>=-10.0&&DHT11.temperature<=5.0){//adjust for dependency on temperature
          RoRs = -0.0300 * DHT11.temperature + 1.4;
        }
        else if (DHT11.temperature >= 5.0 && DHT11.temperature <= 20.0){//adjust for dependency on temperature
          RoRs = -0.0167 * DHT11.temperature + 1.333;
        }
        else {
          RoRs = 1;
        }
        RoRs= RoRs * (-0.001923 * DHT11.humidity + 1.0634); //adjust for dependency on humidity
        int adjAirQValue = airqValue * RoRs;

        //MQ-2 General combustible gas
        int mq2   = analogRead(2);    // read MQ-2 General combustible gas

         char fuocoAcceso[8]="";
        if(digitalRead(pinSensoreFiamma)==1){
          sprintf(fuocoAcceso, "%s","spento");
        }else{
          sprintf(fuocoAcceso, "%s","acceso");
        }

         // trigger
        digitalWrite( triggerPort, LOW );
  
        //impulse of 10microsec on trigger
        digitalWrite( triggerPort, HIGH );
        delayMicroseconds( 10 );
        digitalWrite( triggerPort, LOW );
  
        long duration = pulseIn( echoPort, HIGH );
        long centimetri = 0.034 * duration / 2;

        if( duration > 58000 ){
          duration=-1;
          centimetri=-1;
        }

        MQTT::Message message;
        message.qos = MQTT::QOS0;
        message.retained = false;
        char str[50] = "";
        sprintf(str, "%d,%d,%d,%d,%s,%d", DHT11.humidity, DHT11.temperature,adjAirQValue,mq2,fuocoAcceso,centimetri);
        message.payload = str;
        message.payloadlen = strlen(str);
        int rc = client.publish("/smart_entrance", message);
        if (rc != 0) {
          Serial.print("Message publish failed with return code : ");
          Serial.println(rc);
        }
        client.yield(10000);
    }
    delay(100);
}


Element14.png

List of items:

1)  Arduino Uno or Yún

     + Ethernet Shield W5100 R3 for Arduino Uno

     + MQ2 and MQ135 Smoke Gas Sensor

     + DHT11 Temperature Sensor

     + Flame Firelight Sensor Module

2)  Arduino Yún

     + Infineon Lighting RGB LED Arduino Shield (to connect RGB strip LED)

     + 2-Channel 5V Relay Module for Arduino (to connect lamp)

     + HC-SR04 Ultrasonic Ranging Detector Sensor for Arduino

     + USB webcam

 

 

My idea:

 

My idea is to create a management system for a smart house, in particular as regards the entrance area of the house.

With this system I can go to manage:
a) [1) Arduino Yún + ..] Video surveillance with selective events: when a person approaches the front door, the ultrasonic sensor detects, then Infineon Light RGB LED shield illuminates with white strips inside the room, with relè the external light to illuminate the door, active surveillance taking pictures and / or video recording (streaming), all for a certain time interval.
b) [1) Arduino Yún + ..] if it isn't on a "presence at the door", the LED strips are programmed to create relaxing effects or manifest according shades of blue and red the temperature currently present in the room.
c) [2) Arduino Uno(or Yún) + ..] detect temperature, humidity, presence of harmful gases and flame lit the stove and transmit the data in real time via MQTT.

In this way, with a dedicated web interface I can to have full control of the focal point of my house, checking parameters and real-time operation, guaranteeing me so that everything is in total safety. In fact I can be alerted with push notifications when particular events occur as abnormal temperatures, harmful gases or unexpected visits!

 

For the management of communications between the various nodes of the system will use the protocol MQTT going to take advantage of the wonderful tools provided by the Eclipse IoT Platform as I will list below.




First job preview: I installed in my VPS (Virtual Private Server | running Ubuntu) mosquitto (http://mosquitto.org/) through the following commands:


sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa
sudo apt-get update
sudo apt-get install mosquitto-ppa


 

The next steps towards the realization of the project in the next post ... see you soon!

Filter Blog

By date: By tag: