Alexis Santiago Allende
Published © GPL3+

Eco-Thing #1 "Eco-Smart-Container V1.0"

An IoT device that could help keep the Sandy River Delta clean, as garbage is a very common problem.

IntermediateFull instructions provided10 hours11,352

Things used in this project

Hardware components

Arduino 101
Arduino 101
×1
SparkFun Inventor's Kit for Arduino 101
SparkFun Inventor's Kit for Arduino 101
×1
Raspberry Pi Zero Wireless
Raspberry Pi Zero Wireless
×1
DHT22 Temperature Sensor
DHT22 Temperature Sensor
×1
Grove starter kit plus for Intel Edison
Seeed Studio Grove starter kit plus for Intel Edison
×1
Jumper wires (generic)
Jumper wires (generic)
×1
Ultrasonic Sensor - HC-SR04 (Generic)
Ultrasonic Sensor - HC-SR04 (Generic)
×1
SparkFun Soil Moisture Sensor (with Screw Terminals)
SparkFun Soil Moisture Sensor (with Screw Terminals)
×1
Breadboard (generic)
Breadboard (generic)
×1
Li-Ion Battery 1000mAh
Li-Ion Battery 1000mAh
×1
USB-A to B Cable
USB-A to B Cable
×1
USB-A to Micro-USB Cable
USB-A to Micro-USB Cable
×1

Software apps and online services

Blynk
Blynk
Arduino IDE
Arduino IDE

Hand tools and fabrication machines

Hot glue gun (generic)
Hot glue gun (generic)

Story

Read more

Schematics

Example

Code

Main code arduino

Arduino
/*Made by Alexis Santiago Allende Last Update 17/07/17*/
#include <CurieBLE.h>
#include "CurieIMU.h"
#include <Wire.h>
#include "rgb_lcd.h"
#include <CurieTime.h>

BLEPeripheral blePeripheral;//BLE Peripheral Device (Arduino Device)
BLEService demo111("19b10000-e8f2-537e4f6c-d104768a1214"); // BLE demo111 Service
// BLE sensor rate Characteristic"
BLEUnsignedIntCharacteristic sensor1("19b10001-e8f2-537e4f6c-d104768a1214", BLERead | BLENotify);
// BLE sensor rate Characteristic"
BLEUnsignedIntCharacteristic sensor2("19b10002-e8f2-537e4f6c-d104768a1214", BLERead | BLENotify);
// BLE sensor rate Characteristic"
BLEUnsignedIntCharacteristic sensor3("19b10003-e8f2-537e4f6c-d104768a1214", BLERead | BLENotify);
// BLE sensor rate Characteristic"
BLEUnsignedIntCharacteristic sensor4("19b10004-e8f2-537e4f6c-d104768a1214", BLERead | BLENotify);
//Ble palabra sensor Characteristic
BLECharacteristic palabra("19b10005-e8f2-537e4f6c-d104768a1214", BLERead | BLENotify,10); 
// BLE demo111 buttons Characteristic - custom 128-bit UUID, read and writable by central
BLEUnsignedCharCharacteristic buttons("19b10006-e8f2-537e4f6c-d104768a1214", BLERead | BLEWrite);
rgb_lcd lcd;
const int colorR = 198;
const int colorG = 78;
const int colorB = 25;
int lastOrientation = - 1; // previous orientation (for comparison)
long previousMillis = 0;  // last time the sensor was checked, in ms
const int green = 13; // pin to use for the green light
const int red = 11;// pin to use for the red light
boolean a = LOW, b = LOW; //Control variables
int temp=0;
long distancia;
long tiempo;
int orientation;
int valor=0,nivel=0,ndistancia;

void setup() {
  Serial.begin(9600);
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  lcd.setRGB(colorR, colorG, colorB);
  // Print a message to the LCD.
  setTime(16, 56, 24, 3, 07, 2017);
  lcd.print("Have a nice day!");
  lcd.setCursor(12, 1);
  lcd.print("Off");
  pinMode(green, OUTPUT); // use the LED on pin 13 as an output
  pinMode(red, OUTPUT); 
  pinMode(9, OUTPUT); /*activación del pin 9 como salida: para el pulso ultrasónico*/
  pinMode(8, INPUT);
  CurieIMU.begin();
  CurieIMU.setAccelerometerRange(2);
  // set the local name peripheral advertises
  blePeripheral.setLocalName("Demo111");
  // set the UUID for the service this peripheral advertises
  blePeripheral.setAdvertisedServiceUuid(demo111.uuid());

  // add service and characteristic
  blePeripheral.addAttribute(demo111);
  blePeripheral.addAttribute(buttons);
  blePeripheral.addAttribute(sensor1);
  blePeripheral.addAttribute(sensor2);
  blePeripheral.addAttribute(sensor3);
  blePeripheral.addAttribute(sensor4);
  blePeripheral.addAttribute(palabra);

  // assign event handlers for connected, disconnected to peripheral
  blePeripheral.setEventHandler(BLEConnected, blePeripheralConnectHandler);
  blePeripheral.setEventHandler(BLEDisconnected, blePeripheralDisconnectHandler);

  // assign event handlers for characteristic
  buttons.setEventHandler(BLEWritten, switchCharacteristicWritten);
  
 // sensors.setEventHandler(BLEWritten, switchCharacteristicWritten);
// set an initial value for the characteristic
  buttons.setValue(0); 
  sensor1.setValue(0);
  sensor2.setValue(0);
  sensor3.setValue(0);
  sensor4.setValue(0);
  // advertise the service
  blePeripheral.begin();
  Serial.println(("Bluetooth device active, waiting for connections..."));
}

void loop() {
  // poll peripheral
  blePeripheral.poll();
  digitalWrite(9,LOW); /* Por cuestión de estabilización del sensor*/
  delayMicroseconds(5);
  digitalWrite(9, HIGH); /* envío del pulso ultrasónico*/
  delayMicroseconds(10);
  tiempo=pulseIn(8, HIGH); /* Función para medir la longitud del pulso entrante. Mide el tiempo que transcurrido entre el envío
  del pulso ultrasónico y cuando el sensor recibe el rebote, es decir: desde que el pin 12 empieza a recibir el rebote, HIGH, hasta que
  deja de hacerlo, LOW, la longitud del pulso entrante*/
  distancia= int(0.017*tiempo); /*fórmula para calcular la distancia obteniendo un valor entero*/
  
    char clockTime[8];
  //use sprintf to create a time string of the hour, minte and seconds
  sprintf(clockTime, "%02d:%02d:%02d", hour(), minute(), second());
  //set cursor to column 0, row 0
 lcd.setCursor(2, 1);
 //print the date string over lcd
 lcd.print(clockTime);
 
  long currentMillis = millis();
      // if 1s have passed, check the sensor:
      if (currentMillis - previousMillis >= 1000) {
        previousMillis = currentMillis;
        updateSensor();
      }

  orientation = - 1;   // the board's orientation
  String orientationString; // string for printing description of orientation

  // read accelerometer:
  int x = CurieIMU.readAccelerometer(X_AXIS);
  int y = CurieIMU.readAccelerometer(Y_AXIS);
  int z = CurieIMU.readAccelerometer(Z_AXIS);

  // calculate the absolute values, to determine the largest
  int absX = abs(x);
  int absY = abs(y);
  int absZ = abs(z);

  if ( (absZ > absX) && (absZ > absY)) {
    // base orientation on Z
    if (z > 0) {
      orientationString = "up";
      orientation = 0;  
    } else {
      orientationString = "down";
      orientation = 1;
    }
  } else if ( (absY > absX) && (absY > absZ)) {
    // base orientation on Y
    if (y > 0) {
      orientationString = "digital pins up";
      orientation = 2;
    } else {
      orientationString = "analog pins up";
      orientation = 3;
    }
  } else {
    // base orientation on X
    if (x < 0) {
      orientationString = "connector up";
      orientation = 4;
    } else {
      orientationString = "connector down";
      orientation = 5;
    }
  }

  // if the orientation has changed, print out a description:
  if (orientation != lastOrientation) {
    Serial.println(orientationString);
    lastOrientation = orientation;
  }


}

void blePeripheralConnectHandler(BLECentral& central) {
  // central connected event handler
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Have a nice day!");
  Serial.print("Connected event, central: ");
  Serial.println(central.address());
  lcd.setCursor(12, 1);
  lcd.print("On");
}

void blePeripheralDisconnectHandler(BLECentral& central) {
  // central disconnected event handler
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Have a nice day!");
  Serial.print("Disconnected event, central: ");
  Serial.println(central.address());
  lcd.setCursor(12, 1);
  lcd.print("Off");
}

void switchCharacteristicWritten(BLECentral& central, BLECharacteristic& characteristic) {
  // central wrote new value to characteristic, update LED
  Serial.print("Characteristic event, written: ");
  Serial.print(buttons.value());
  if (buttons.value() == 1 && a == LOW) { // 1 in ASCII
          
          Serial.print("LED on");
          digitalWrite(green, HIGH);         // will turn the LED on
          a = HIGH;
        } else if (buttons.value() == 1 && a == HIGH)  {  //when 1 was read again (second time)          

          Serial.println("LED off");
          digitalWrite(green, LOW);          // will turn the LED off
          a = LOW;
        }
        else if (buttons.value() == 2 && b == LOW) { // 1 in ASCII
          
          Serial.print("LED on");
          digitalWrite(red, HIGH);         // will turn the LED on
          b = HIGH;
        } else if (buttons.value() == 2 && b == HIGH)  {  //when 1 was read again (second time)          

          Serial.println("LED off");
          digitalWrite(red, LOW);          // will turn the LED off
          b = LOW;
        }
        
}




void updateSensor() {
  temp=analogRead(A0);//dht.readTemperature();//read temperature 
  valor=analogRead(A1);
  nivel = map(valor, 0, 1023, 100, 0);
  ndistancia = map(distancia, 38, 2, 0, 100);
  float sensorLevel = temp*(3.3/1023);
  int temp1=(sensorLevel-0.5)*100;
  sensor1.setValue(temp1);//send temperature value
  sensor2.setValue(distancia);//send distance value
  sensor3.setValue(orientation);//send orientation value
  sensor4.setValue(nivel);//send percentage of hummidity value
  Serial.println(temp1);
  Serial.println(distancia);
  Serial.println(orientation);
  Serial.println(nivel);
 
}

Main code Node JS

JavaScript
//Blynk
var Blynk = require('blynk-library');

var AUTH = 'adea86da8f774157b6a4997a6ed18a08';

var blynk = new Blynk.Blynk(AUTH);

var v1 = new blynk.VirtualPin(1);
var v9 = new blynk.VirtualPin(9);
var v8 = new blynk.VirtualPin(8);
var v7 = new blynk.VirtualPin(7);
var v6 = new blynk.VirtualPin(6);
var v5 = new blynk.VirtualPin(5);
var v4 = new blynk.VirtualPin(4);
var v3 = new blynk.VirtualPin(3);

//Bluetooth low energy
var noble = require('noble');

// Search only for the Service UUID of the device (remove dashes)
var serviceUuids = ['19b10000e8f2537e4f6cd104768a1214'];

// Search only for the led charateristic
var characteristicUuids = ['19b10001e8f2537e4f6cd104768a1214','19b10002e8f2537e4f6cd104768a1214','19b10003e8f2537e4f6cd104768a1214','19b10004e8f2537e4f6cd104768a1214','19b10005e8f2537e4f6cd104768a1214','19b10006e8f2537e4f6cd104768a1214'];

var sensor1=0;
var sensor2=0;
var sensor3=0;
var sensor4=0;
var temperatura=0;
var humedad=0;
var boton=0;
var contador1=0,contador2=0,contador3=0,contador4=0;

//Twilio
const twilio = require('twilio')
var accountSid = 'AC4c3a664e0475a08a4e0fdbd016555a70'; 
var authToken = '22ee6e5fe596967997a2d1a57d6d73eb'; 
 
const phone = new twilio(accountSid, authToken);
 
const sendMessage = () => {
  phone.messages.create({
    to: "+526462378678",
    from: "+12818266123 ",
    body: 'WARNING!!!!!! take care, please review your Blynk app now!!!!!', 
  }) 
}
//Reading DHT22
var sensor = require('node-dht-sensor');


//Final
v1.on('write', function(param) {
  boton=param[0];
  
});

v9.on('read', function() {
  v9.write(new Date().getSeconds());
});

v8.on('read', function() {
  v8.write(sensor1);
});

v7.on('read', function() {
  v7.write(humedad);
});

v6.on('read', function() {
  v6.write(temperatura);
});

v5.on('read', function() {
  v5.write(sensor2);
});

v4.on('read', function() {
  v4.write(sensor3);
});

v4.on('read', function() {
  v4.write(sensor4);
});

// start scanning when bluetooth is powered on
noble.on('stateChange', function(state) {
  if (state === 'poweredOn') {
    noble.startScanning(serviceUuids);
  } else {
    noble.stopScanning();
  }
});

//Reading sensor
setInterval(function() {
sensor.read(22, 21, function(err, temperature, humidity) {
    if (!err) {
         temperatura=temperature.toFixed(1);
         humedad= humidity.toFixed(1);
        
    }
    });
        }, 1000);


// Search for BLE peripherals
noble.on('discover', function(peripheral) {
  peripheral.connect(function(error) {
    console.log('connected to peripheral: ' + peripheral.uuid);
    // Only discover the service we specified above
    peripheral.discoverServices(serviceUuids, function(error, services) {
      var service = services[0];
      console.log('discovered service');

      service.discoverCharacteristics(characteristicUuids, function(error, characteristics) {
        console.log('discovered characteristics');
        // Assign Characteristic
        var sensor1Characteristic = characteristics[1];
        var sensor2Characteristic = characteristics[2];
        var sensor3Characteristic = characteristics[3];
        var sensor4Characteristic = characteristics[4];
       //var botonCharacteristic = characteristics[4];
        
        setInterval(function() {
           
            sensor1Characteristic.read(function(error, data) {
            // data is a buffer
            console.log('Temperature is: ' + data.readUInt8(0));
            sensor1=data.readUInt8(0);
            if (data.readUInt8(0)>=32 && contador1===0) {
                    sendMessage();
                    contador1=1;
                  }
            else if(data.readUInt8(0)<=30 && contador1==1){
                      contador1=0;
                  
                   }
            
            });

             sensor2Characteristic.read(function(error, data) {
            // data is a buffer
            console.log('Trash percent is: ' + data.readUInt8(0));
            sensor2=data.readUInt8(0);
            if (data.readUInt8(0)<=4 && contador2===0) {
                    sendMessage();
                    contador2=1;
                  }
            else if(data.readUInt8(0)>=30 && contador2==1){
                      contador2=0;
                  
                   }
            });


             sensor3Characteristic.read(function(error, data) {
            // data is a buffer
            console.log('Orientation: ' + data.readUInt8(0));
            sensor3=data.readUInt8(0);
            if (data.readUInt8(0)!=2 && contador3===0) {
                    sendMessage();
                    contador3=1;
                  }
            else if(data.readUInt8(0)==2 && contador3==1){
                      contador3=0;
                  
                   }
            });

            sensor4Characteristic.read(function(error, data) {
            // data is a buffer
            console.log('Humidity: ' + data.readUInt8(0));
            sensor4=data.readUInt8(0);
            if (data.readUInt8(0)>=90 && contador4===0) {
                    sendMessage();
                    contador4=1;
                  }
            else if(data.readUInt8(0)<=30 && contador4==1){
                      contador4=0;
                  
                   }
            });
            
        }, 1000);

             //  var bufferToSend = new Buffer(1);
               // bufferToSend.writeUInt8(boton);
               // console.log(bufferToSend);
               // botonCharacteristic.write(bufferToSend, false);
           // setInterval(function() {
           //bufferToSend.writeUInt8(1); // you can pass this any integer, we just do this to alternate 0/1
         //  botonCharacteristic.write(bufferToSend, false);
       // }, 1000);
      }); 
    });
  });
});

Credits

Alexis Santiago Allende

Alexis Santiago Allende

0 projects • 75 followers
Im a person who since young feel a passion for electronics, I also like to cook pizza and travel. Now Im working on the internet of things

Comments