Manufactura industrial
Internet industrial de las cosas | Materiales industriales | Mantenimiento y reparación de equipos | Programación industrial |
home  MfgRobots >> Manufactura industrial >  >> Manufacturing Technology >> Proceso de manufactura

Monitoreo SMART de temperatura para escuelas

Componentes y suministros

Pycom SiPy
× 1
Raspberry Pi 3 Modelo B
× 1
Arduino Nano R3
× 1
SparkFun Logic Level Converter - Bidireccional
× 1
NFC RFID-RC522
× 1
Sharp GP2Y0A41SK0F (4cm - 30cm) - Sensor de distancia analógico
× 1
MLX90614-DCI I2C - Sensor de temperatura
× 1
Módulo de pantalla LCD Arduino DFRobot I2C 16x2
× 1
LED (genérico)
× 1
Resistencia de 330 ohmios
× 2
Buzzer
× 1

Aplicaciones y servicios en línea

Arduino IDE
Visual Studio Code (Pymakr)
API ThingSpeak
IFTTT
Putty
IDE IDE

Acerca de este proyecto

DECLARACIÓN DEL PROBLEMA

En Asia, debido al clima cálido y al brote del síndrome respiratorio agudo severo (SARS) en 2003, los estudiantes de primaria y secundaria deben realizar mediciones de temperatura durante todos los trimestres para garantizar el bienestar de los estudiantes. Siempre que haya un ejercicio de toma de temperatura programado por la escuela, los estudiantes deben traer su propio termómetro digital para este ejercicio. Sin embargo, es posible que algunos estudiantes no puedan participar durante el ejercicio debido a razones como el termómetro extraviado o dañado y se olviden de traer el dispositivo. Debido a la higiene personal, a los estudiantes no se les permite compartir sus termómetros y es posible que no tengan suficiente dinero para comprar una pieza nueva. Por lo tanto, afecta la tasa de éxito del ejercicio de toma de temperatura. Después del ejercicio de medición de temperatura, el personal tendrá que introducir manualmente todos los datos de temperatura de los estudiantes y los estudiantes específicos de la base de datos. La tarea es muy tediosa y requiere mucho tiempo, ya que cada profesor de formulario deberá realizar entradas para aproximadamente 40 estudiantes.

¿Cuál es la solución?

El tema de nuestro proyecto es Impacto social por SqwidNet, y en el área de Buena salud y bienestar en el Objetivo de Desarrollo Sostenible (ODS). La razón de esto es que nuestro sistema se puede implementar para medir automáticamente la temperatura de los usuarios válidos para que su temperatura pueda ser monitoreada y se envíe una alerta cada vez que exceda un cierto nivel de umbral.

CÓMO FUNCIONA:RaspberryPi y Arduino

El RaspberryPi tiene un programa Python y la base de datos MySQL.

Al iniciar el programa Python, comprueba automáticamente si la base de datos ya está creada; de lo contrario, se creará automáticamente. Las tablas del interior también se comprobarán y crearán automáticamente si es necesario. Esto reduce el trabajo manual de los maestros / personal administrativo en la escuela.

Luego, establece una conexión de consulta para verificar la base de datos y espera que Arduino envíe información relevante a través del puerto de comunicación serial.

Al tener una tarjeta RFID en el Arduino, la información de la tarjeta se almacena en el Arduino y se envía a la RaspberryPi a través de la comunicación en serie. Posteriormente, RaspberryPi confirma con la base de datos que dicha tarjeta es un usuario válido, y si lo es, envía al Arduino confirmándolo y el Arduino muestra "Bienvenido, nombre" en la pantalla LCD. Si no es un usuario válido, simplemente dirá "¡Error! ¡Usuario no válido!".

Digamos, ahora, tenemos un usuario válido que acaba de tocar. A continuación, Arduino le pedirá al usuario que tome su temperatura. Un sensor de distancia detectará si un usuario está listo para tomar su temperatura. Si es así, tomará su temperatura y mostrará su temperatura en la pantalla LCD. Si es una temperatura válida (28 * C - 42 * C), esta información se enviará tanto a RaspberryPi (MySQL) como a Sigfox (ThingSpeak) para el almacenamiento de datos. La base de datos MySQL almacenaría el ID de usuario, la fecha, la marca de tiempo y la temperatura de cada toma.

Al recibir los datos de temperatura del Arduino, RaspberryPi verificaría constantemente si la temperatura se entrega correctamente antes de continuar con cualquier otra cosa. Esto se debe a que, si el programa Python solo verifica una vez los datos de temperatura, es posible que Arduino aún no los haya enviado, porque ambos códigos se ejecutan en tiempos diferentes. Entonces, para sincronizar, verificamos constantemente los datos de temperatura en el código Python antes de continuar con el resto del programa.

NOTA: Tanto el código Python como el código Arduino de RaspberryPi utilizan un método de sincronización llamado Handshaking. Si la RaspberryPi no está lista para recibir otra información de temperatura / usuario, Arduino no permitirá que el usuario toque la tarjeta, viceversa .

Una forma sencilla de hacerlo es enviar constantemente una señal de "LISTO" hasta que la otra parte envía una señal de "RECIBIR" para que sepan que ambos están listos.

Arduino -

  boolean readySignal =Serial.readString () =="READY"; 


if (readySignal)
{

tocado =verdadero;

Serial.println ("RECIBIDO");

}

Python:

  while (readySignal ==True):

ser.write (b '' + "READY")



ivedSignal =ser.readline (). strip () =="RECIBIDO"


if (selectedSignal ==True):

readySignal =False

¡Recuerde cerrar su conexión de consulta cada vez que haya terminado con una consulta! Esto es para eliminar cualquier posible fuga de memoria y es una buena práctica en general.

CÓMO FUNCIONA:Sigfox (SiPy)

Después de recibir los datos de temperatura del Arduino, el SiPy separará el ID de usuario y la temperatura en números enteros y decimales. Después de hacer esto, todos los datos se envían al backend de Sigfox a través de bytes (para que puedan enviarse a Ubidots y a ThingSpeak) y deberían verse como en la siguiente imagen.

Después de recibir esto, el backend de Sigfox volverá a codificar estos datos para enviarlos a ThingSpeak y almacenarlos. Lo siguiente le mostrará cómo codificar el backend para enviar datos a Thingspeak.

En Sigfox Backend en Tipo de dispositivo> Nombre del dispositivo> DEVOLUCIONES DE LLAMADAS, deberá ingresar la carga útil personalizada exactamente como está es a menos que haya cambiado la codificación en el SiPy, ya que la carga útil personalizada establecerá lo que se recibe primero como el ID de usuario, por ejemplo, si envía la temperatura primero, en el backend convertirá esa temperatura en el ID de usuario en lugar de la temperatura. En el cuerpo, la clave de la API de escritura debe ir en la parte superior, mientras que los campos se pueden colocar con cualquiera de los datos personalizados que haya creado en la carga útil personalizada.

CÓMO FUNCIONA:La nube

Una vez que los datos se envían con éxito a ThingSpeak, primero los recibe en un canal de visualización privado donde un script de análisis MATLAB analiza los datos y combina los datos de temperatura en un valor en lugar de la separación de un valor de número entero y un valor decimal.

El código de la tabla se tomó de un proyecto de código abierto y se modificó para satisfacer nuestras necesidades. Es muy útil ya que la tabla se actualiza automáticamente cada vez que se envían nuevos datos, lo que es perfecto para nuestro uso.

Al mismo tiempo, verifica si la temperatura está en un nivel peligroso (fiebre), de ser así, se enviará un correo electrónico para notificar al personal / maestros.

En resumen, el primer canal que tiene el valor de temperatura separado en número entero y número decimal es un canal de backend, no realmente para visualización. Para el segundo canal, los valores de temperatura se combinaron y se hicieron agradables para que los vean el personal / la gerencia / los administradores y tiene una tabla similar a Excel para facilitar el análisis de datos.

1. Configuración de conexiones Arduino Nano

Para Arduino Nano, aquí están las conexiones que hemos hecho con nuestros módulos.

Nano y Uno tienen el mismo Pinout.

  RFID - RC522 

SDA D10
SCK D13
MOSI D11
MISO D12
IRQ DESCONECTADO
GND GND
RST D9
3.3V 3.3V

Cómo probar RFID

  LCD 

SDA A4
SCL A5
GND GND
5V 5V

Cómo probar I2C LCD

  Sensor de distancia 

5V 5V
GND GND
Entrada A0

Cómo probar el sensor de distancia IR de Sharp

  Buzzer 

GND GND
Salida D6

Cómo probar Buzzer

  Sensor de temperatura IR 

SDA A4
SCL A5
GND GND
5V 5V

Cómo probar el sensor de temperatura IR,

  LED 

Lado plano (cátodo) GND
Lado no plano (ánodo) D7

¡Bien! Para las conexiones de Arduino, debería estar listo ahora.

2. Configuración de RaspberryPi

Hay principalmente dos cosas que deben instalarse en su máquina Raspberry Pi 3,

1. Operación Raspbian Sistema -

La instalación del sistema operativo Raspbian se considera bastante sencilla.

Una respuesta breve sobre cómo hacerlo sería flashear (escribir) un archivo de imagen en una tarjeta SD y colocar esta tarjeta SD en la Raspberry Pi 3.

Sin embargo, si está buscando un tutorial de respuestas largas paso a paso, aquí le mostramos cómo hacerlo:

En primer lugar, debe descargar un software que le permita almacenar archivos flash.img en una unidad de almacenamiento. Puede utilizar el software llamado balenaEtcher.

Luego, diríjase a la página Raspberry Pi - Raspbian y elija una que se adapte a sus necesidades. Elegí "Raspbian Buster con escritorio y software recomendado" porque, como dice el nombre, viene con el software recomendado y eso te ahorra la molestia adicional de descargar software.

Una vez que haya terminado con los pasos antes mencionados, simplemente inicie el software balenaEtcher. Este paso es bastante autoexplicativo:seleccione la imagen (su archivo.img Raspbian), luego seleccione su tarjeta SD y presione flash. Ahora solo tienes que esperar. Una vez hecho esto, debería avisarle y ahora puede insertar la tarjeta SD recién flasheada en su Raspberry Pi.

Después de esto, conecte su máquina Raspberry Pi a través de HDMI a un monitor y realice su configuración inicial. Por último, dirígete a Preferencias -> Configuración de Raspberry Pi y deberías estar en este menú -

Siga las opciones, este paso habilita interfaces como SSH, VNC que le permite conectarse a direcciones IP a través de eth0 o wlan0 (por lo que ya no necesita el cable HDMI, puede hacerlo todo a través de SSH).

(paso opcional) - Abro la terminal y edito el archivo dhcpcd.conf (sudo nano /etc/dhcpcd.conf) y agrego estas líneas de comando,

  interfaz eth0 
dirección_ip estática =192.168.0.11 / 24

Lo anterior me permite conectarme a la Raspberry Pi a través de un cable Ethernet con la dirección estática, 192.168.0.11, así que sé cada vez que esa es la dirección de mi Raspberry Pi.

Este es un paso opcional ya que, una vez que esté conectado a WiFi, obtendrá una dirección ip wlan0 que le permite conectarse a la Raspberry Pi sin un cable Ethernet y en cualquier lugar de la ubicación siempre que esté conectado a la misma Wifi. Para ver cuál es su DIRECCIÓN IP wlan0, simplemente coloque el mouse sobre el símbolo de WiFI ubicado en la parte superior derecha e indicará.

¡Bien! ¡Terminaste con la configuración inicial de tu Raspberry Pi!

3. Configuración de la base de datos MySQL

Consideraría este paso un poco difícil, especialmente la parte en la que tienes que configurar el usuario root de MySQL, síguelo con atención porque es muy difícil corregir cualquier error.

Primero, debe asegurarse de que su sistema esté actualizado y actualizado con el último firmware. Puede asegurarse ingresando estos comandos,

  actualización de sudo apt 
actualización de sudo apt

Una vez hecho esto, instalará apache2.

  sudo apt install apache2  

Apache2 le permitirá crear un servidor web para que pueda acceder a los sitios web que cree más tarde.

Una vez que apache2 está instalado, necesita instalar PHP.

  sudo apt install php php-mbstring  

PHP le permitirá crear y ver sus propios sitios web PHP.

Detengámonos y veamos si todo lo que acaba de instalar funciona, simplemente escriba la IP de su Raspberry Pi en su navegador web o "localhost" si todavía está conectado a través de HDMI, y debería ver una página de índice de Apache.

Ahora, necesitará instalar la base de datos. Para ello, utilizará MySQL y mariadb.

  sudo apt install mariadb-server php-mysql  

IMPORTANTE - Por favor, asegúrese de leer lo que se muestra a continuación con mucha atención.

Ahora, creará su usuario raíz de MySQL para que pueda usarlo para acceder a la base de datos.

  sudo mysql --user =root  

Ahora ingresará a una sesión de MySQL donde puede escribir códigos MySQL, escríbalos línea por línea, (puede reemplazar la contraseña con su propia contraseña)

  DROP USER 'root' @ 'localhost'; 
CREAR USUARIO 'root' @ 'localhost' IDENTIFICADO POR 'contraseña';
OTORGAR TODOS LOS PRIVILEGIOS EN *. * A 'root' @ 'localhost' CON OPCIÓN DE SUBVENCIÓN;
DESCARGAR PRIVILEGIOS;
salir;

Ahora puede probar su usuario root de MySQL iniciando sesión;

  mysql --user =root --password =yourmysqlpassword  

Si todo funciona, ahora puede instalar PHPMyAdmin, el Panel de control del administrador para que pueda acceder (ver) y modificar la base de datos MySQL.

  sudo apt install phpmyadmin 

(después de la instalación)
sudo phpenmod mysqli
sudo /etc/init.d/apache2 restart

¡Felicitaciones! Ahora puede acceder a su base de datos recién creada usando http:// your_raspberrypi_ip_address / phpmyadmin.

4. Guía de instalación y software de la placa de expansión SiPy 2.0

En primer lugar, deberá insertar el módulo SiPy en la placa de expansión con el botón de reinicio hacia el conector USB y debe hacer clic firmemente en su lugar con los pines ya no visibles.

Fuente:Documentación de Pycom

Después de hacer eso, deberá actualizar el firmware en el SiPy, para que pueda cargar y ejecutar programas, así como obtener el ID del dispositivo Sigfox y el número PAC que se utilizará para registrarse en el backend de Sigfox. Descargue el actualizador de firmware según el sistema operativo (sistema operativo) que esté utilizando.

  • Windows
  • macOS (10.11 o superior)
  • Linux (requiere cuadro de diálogo y python-serial paquete)

Después de descargar la actualización del firmware de pycom, cuando inicie el actualizador por primera vez, las siguientes imágenes solo aparecerán una vez así que asegúrese de seleccionar la Región Sigfox correcta, Tablero.

Siga las instrucciones de la actualización del firmware con cuidado, ya que puede hacer que su Sigfox no funcione correctamente, ya que la ID del dispositivo Sigfox y el número PAC son todos "F" (como a continuación) en lugar de una mezcla entre números y alfabetos.

  b 'FFFFFFFF' 
b 'FFFFFFFFFFFFFFFF'

Una vez que se haya actualizado el firmware, deberá descargar Visual Studio Code e instalar la extensión Pymkr y nodejs antes de poder comenzar a cargar y ejecutar programas en SiPy.

En primer lugar, deberá crear una nueva carpeta para guardar todos los archivos que va a cargar en el SiPy más adelante o simplemente para almacenar todos los programas que va a ejecutar. Presione el archivo en la esquina superior izquierda y presione Abrir carpeta o Ctrl + K + O luego seleccione dónde desea colocar esta carpeta y haga clic derecho para crear una nueva carpeta. Después de eso, cree un archivo nuevo o Ctrl + N para abrir un nuevo archivo. Después de crear un nuevo archivo, deberá guardar el nuevo archivo como python y cambiar el tipo de archivo guardado a python para que el código se pueda ejecutar en el SiPy más adelante y guardarlo en la nueva carpeta que creó.

Nota: El nombre del archivo puede ser cualquier cosa como Prueba, Prueba, etc. Pero si se carga en el nombre del archivo SiPy, debe llamarse principal .

Para ejecutar su código sin cargarlo en el Módulo Sipy, todo lo que tiene que hacer es presionar el botón Ejecutar ubicado en la parte inferior del programa. La carga junto a ella carga la carpeta actual en el Módulo SiPy. Tenga cuidado al usar bucles while 1, ya que una vez que estos se cargan en el Módulo SiPy, la única forma de acceder al Módulo SiPy nuevamente es mediante FTP en la memoria flash y eliminar el archivo main.py del SiPy Módulo.

Si agregó accidentalmente un bucle while infinito, no debe preocuparse, ya que aún puede cargar su programa o eliminar el anterior a través de FTP. En primer lugar, descargue la versión gratuita de filezilla e instálela.

Después de la instalación, deberá configurar la conexión. En primer lugar, abra filezilla y vaya al administrador del sitio que se encuentra debajo del archivo o presione Ctrl + S y presione nuevo sitio.

Puedes cambiar el nombre del sitio a SiPy o como quieras llamar a esta conexión y cambiar la configuración de encriptación a Solo usar FTP simple (inseguro) y transfiera la configuración a pasivo y limite el número de conexiones activas a 1

Puede encontrar el host (dirección), el usuario y la contraseña a través de Visual Studio Code presionando todos los comandos y seleccionando la configuración global. Esto le mostrará la configuración predeterminada para el Host (dirección), Usuario (nombre de usuario) y contraseña. Esto se puede cambiar presionando la configuración del proyecto en todos los comandos.

A continuación, deberá conocer el SSID del módulo SiPy, que se puede encontrar usando todos los comandos y presionando obtener SSID WiFI AP. Cada SSID de módulo SiPy será único, pero la contraseña es la misma en todo momento y no se puede cambiar. La contraseña para el SSID del módulo SiPy es www.pycom.io

Nota: Los usuarios de escritorio necesitarán un adaptador WiFi

¡Ahora puede comenzar a usar filezilla para acceder a SiPy Flash! Primero conéctese al SSID SiPy, luego vaya al administrador del sitio de filezilla y conéctese al nuevo sitio que creó y escriba la contraseña. Ahora abra la carpeta flash y elimine main.py SOLAMENTE! Después de eliminar main.py, reinicie SiPy y podrá comenzar a ejecutar / cargar sus programas.

Nota: Es posible que desee copiar la carpeta flash en su sistema operativo (sistema operativo) en caso de que elimine todo.

5. Registrarse con Sigfox Backend

Después de instalar Visual Studio Code, conecte la placa de extensión pycom a la computadora y detectará automáticamente la conexión cuando abra Visual Studio Code. Copie el código a continuación y péguelo en la terminal o en un archivo y ejecútelo. Cualquiera de los dos métodos servirá.

  from network import Sigfox 
import binascii

# initalise Sigfox for RCZ * (Es posible que necesite una región RCZ diferente)
sigfox =Sigfox (mode =Sigfox .SIGFOX, rcz =Sigfox.RCZ *)

# print Sigfox Device ID
print (binascii.hexlify (sigfox.id ()))

# print Número de PAC de Sigfox
imprimir (binascii.hexlify (sigfox.pac ()))

Nota :Reemplace * con su Número de Región RCZ.

Método de terminal para obtener el ID del dispositivo Sigfox y el número PAC

Para abrir el terminal en Visual Studio Code, presione Ctrl + ~. Luego pegue el código dentro y se mostrará como en la siguiente imagen.

Método de archivo para obtener el ID del dispositivo Sigfox y el número PAC

Una vez que el nuevo archivo se guarda presionando Ctrl + S o yendo al archivo y luego guarde, pegue el código en el archivo y guarde el archivo, luego podrá ejecutar el archivo presionando el botón Ejecutar en la parte inferior de la pantalla y debería ser igual a la imagen de abajo.

Después de obtener su ID de dispositivo Sigfox y su número PAC, deberá registrar su Sigfox en Sigfox Backend antes de poder comenzar a transmitirle. La primera página que verá será la ubicación de su empresa sigfox. Debe elegir el país en el que se utilizará este dispositivo Sigfox, ya que cada una de las zonas Sigfox está configurada de forma diferente.

Después de elegir el país correcto, la página siguiente requerirá su ID de dispositivo Sigfox y el número PAC que obtuvo al comienzo de este capítulo. Pégalos en el campo correcto y la página debería verse como la imagen. En cuanto al resto, llénelo en consecuencia.

Después de llenar la página del dispositivo, crear una cuenta Sigfox o iniciar sesión en una cuenta Sigfox existente, debe registrar Sigfox en su cuenta. Si está creando una nueva cuenta de Sigfox, Sigfox le enviará un correo electrónico al correo electrónico registrado para configurar la contraseña.

Una vez que haya configurado su cuenta de backend de sigfox, puede ejecutar este código para enviar algunos datos y ver si el backend puede recibirlos.

Nota **: Conecte su antena sigfox primero antes de ejecutar cualquier programa sigfox.

  de la importación de red Sigfox 
import socket

# initalise Sigfox para RCZ * (Es posible que necesite una región RCZ diferente)
sigfox =Sigfox (mode =Sigfox .SIGFOX, rcz =Sigfox.RCZ *)

# crear un socket Sigfox
s =socket.socket (socket.AF_SIGFOX, socket.SOCK_RAW)

# hacer el bloqueo de socket
s.setblocking (True)

# configurarlo como enlace ascendente solamente
s.setsockopt (socket.SOL_SIGFOX, socket.SO_RX, False)

# enviar algunos bytes
s.send (bytes ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]))

Nota :Reemplace * con su Número de Región RCZ.

6. Configuración de la nube

En primer lugar, deberá configurar el IFTTT para enviar correos electrónicos, ir al sitio web de IFTTT y crear una cuenta. Después de configurar la cuenta e iniciar sesión, vaya a su perfil, que se encuentra cerca de la esquina superior derecha de la pantalla en el lado izquierdo de "Explorar" y presione Crear .

Haga clic en " Esto " and then search for Webhooks and press it. If you are unsure, the following pictures will help you with what to do.

After selecting Webhooks, press the Receive a web request box and enter an event name to fit your requirements (in this example fever is used), afterwards press Create trigger .

Press the word "That ", type email in the search box and press Email then press Send me an email box

Enter message information. You can pass data about the event that triggered your message by using ingredients. For example, including {{Event Name}} adds the event name to your text message. The Body section must include at least {{Value1}} and {{Value2}}. Click Create action to finish the new applet. Note:Value 1, value 2 and value 3 in body message are derived from MATLAB Analysis and can be modified according to your requirement

ThingSpeak is an IOT (Internet of Things) platform which can be easily setup, learned and is open source.

First, we create two channels; (SIGFOX) TEMPERATURE PRIVATE VIEWING &(SIGFOX) TEMPERATURE PUBLIC VIEWING.

For the (SIGFOX) TEMPERATURE PRIVATE VIEWING , its purpose is to obtain data from the Sigfox backend. Sigfox sends up using bytes, this is because, we have realised that Ubidots (a web service) do not really work well with decoding Strings, so to make it work and accessible with both ThingSpeak and Ubidots, we chose to use bytes as it contain numbers from 0-255.

Therefore, using bytes makes it so we have to send both the whole number and the decimal number of the temperature information separately. So, this channel is mainly for keeping these messy values, later transferring to another channel for viewing which is the (SIGFOX) TEMPERATURE PUBLIC VIEWING channel.

We use MATLAB Analysis to convert the two messy values (whole number &decimal number) into just one combined value and transfer it onto the other channel. At the same time, we also transfer the userID onto the (SIGFOX) TEMPERATURE PUBLIC VIEWING as it's used for viewing. The MATLAB script is triggered on data insertion using a ThingSpeak REACT which will be explained below.

To setup the react, first go to Apps and then select React which will open the reacts tab. Press New React to create a new react for the MATLAB Analysis to be triggered when new data arrives from the Sigfox backend. Set the condition type to string, test frequency to on data insertion, condition to field 3 (which should be your userid) of the (SIGFOX) TEMPERATURE PRIVATE VIEWING when its not equal to 0, action to MATLAB Analysis with the code for calculating the temperature and Options to Run Action only the first time condition is met.

The table code was taken from an open sourced project and modified to suit our needs. It's very useful as the table auto updates every time a new data is sent in, perfect for our usage.

Unfortunately, the MATLAB plugin for the table is only view-able in private view and not in the public view. As it's intended for administrative purposes only, we do not subject this as an issue, it's intended to be only viewed in private view.

To retrieve Webhooks information, Click on your profile logo near the top right corner of the screen on the left of the “Explore” tab. Select My Services, select Webhooks then click documentation near the top right of the web page, from there you can see your key and format for sending a request. Enter that event name. The event name for this project is fever

https://maker.ifttt.com/trigger/{event}/with/key/(example)

https://maker.ifttt.com/trigger/fever/with/key/(example)

The service can be tested to see if it works or not by pasting the URL(example of the URL are shown above) into your browser or pressing the test button upon creation of the webhooks and email applet

After all that is done, you should be able to receive an email like the following picture, after you have finished setting up the ThingSpeak React.

Contributions

Aden - RaspberryPi + Arduino + its modules + ThingSpeak (MATLAB+ Setup)

Reginald - Sigfox + ThingSpeak Data Collection + Schematics

Bo Sheng - IFTTT Setup

Código

  • [C] ARDUINO NANO
  • [PYTHON] RaspberryPi
  • [MicroPython] Sigfox (Pycom)
  • [ThingSpeak] MATLAB SCRIPT
[C] ARDUINO NANOArduino
This code is used for checking if there's a RFID card tap, if there is, there will be temperature taking and also handshaking between the Raspberry Pi to send data over like the card's ID, temperature and ready/standby signal and more.

It also uses LCD to show informative information.

If you're interested in knowing more, please read the section on "HOW IT WORKS:RaspberryPi &Arduino"
/*90% is coded from scratch by Aden,http://www.astero.methe other 10% consists of open sourced libraries(Credits found below) used, like the RFID &temperature module.*//* * Initial Author:ryand1011 (https://github.com/ryand1011) * * Reads data written by a program such as "rfid_write_personal_data.ino" * * See:https://github.com/miguelbalboa/rfid/tree/master/examples/rfid_write_personal_data * * Uses MIFARE RFID card using RFID-RC522 reader * Uses MFRC522 - Library * ----------------------------------------------------------------------------------------- * MFRC522 Arduino Arduino Arduino Arduino Arduino * Reader/PCD Uno/101 Mega Nano v3 Leonardo/Micro Pro Micro * Signal Pin Pin Pin Pin Pin Pin * ----------------------------------------------------------------------------------------- * RST/Reset RST 9 5 D9 RESET/ICSP-5 RST * SPI SS SDA(SS) 10 53 D10 10 10 * SPI MOSI MOSI 11 / ICSP-4 51 D11 ICSP-4 16 * SPI MISO MISO 12 / ICSP-1 50 D12 ICSP-1 14 * SPI SCK SCK 13 / ICSP-3 52 D13 ICSP-3 15*//***************** This is a library example for the MLX90614 Temp Sensor Designed specifically to work with the MLX90614 sensors in the adafruit shop ----> https://www.adafruit.com/products/1748 ----> https://www.adafruit.com/products/1749 These sensors use I2C to communicate, 2 pins are required to interface Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Escrito por Limor Fried / Ladyada para Adafruit Industries. BSD license, all text above must be included in any redistribution ******************/ // INCLUDE NECESSARY HEADER FILES #include #include #include #include #include #include // DEFINITION OF PINS#define RST_PIN 9 // Configurable, see typical pin layout above#define SS_PIN 10 // Configurable, see typical pin layout above#define BUZZER_PIN 7 //Pin define for Buzzer#define LED_PIN 6 //Pin define for LED #define dist_sensePin A0MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.LiquidCrystal_I2C lcd(0x27,16,2); // Calls the LiquidCrystal class and creats an instance for the LCD.// set the LCD address to 0x27 with 16 chars and 2 line displayAdafruit_MLX90614 mlx =Adafruit_MLX90614(); // Calls the Adafruit MLX90614 instance.SoftwareSerial unoSerial(2, 3); // RX, TX // Calls the SoftwareSerial instance (for Pycom communication)// GLOBAL VARIABLESboolean tapped =true; boolean confirmation =false;String GetUID(){ String card_UID=""; String card_UID_no_space =""; for (byte i =0; i  200)) // Check if there is actually a valid user infront of the machine. If no, it'll keep looping what's under. { dist_senseValue =analogRead(dist_sensePin); // Keep checking until there's a person that comes in the distance sensor's range. lcd.setCursor (0,0); lcd.print("Please take"); lcd.setCursor (0,1); lcd.print("your temperature."); // Prompt the user to take their temperature by standing infront of the machine. } digitalWrite(BUZZER_PIN, 1); digitalWrite(LED_PIN, 1); lcd.clear (); // Turns on the Buzzer and LED, at the same time, clear the LCD too. meas_temp =(float)mlx.readObjectTempC(); temp_Hbyte =floor(meas_temp); temp_Lbyte =(meas_temp - temp_Hbyte) * 100; sMeasTemp +=userID; sMeasTemp +=","; sMeasTemp +=temp_Hbyte; sMeasTemp +=","; sMeasTemp +=temp_Lbyte; // Collect the temperature data that is taken. Serial.println("TEMP"); Serial.println(meas_temp); // Transfer the temperature data through Serial Communication to the RaspberryPi. if((meas_temp>
=28) &&(meas_temp <=42)) // Check if it's a valid temperature. unoSerial.print(sMeasTemp); // If it is, send to the sigfox module for cloud storage. lcd.setCursor (0,0); lcd.print("Temperature:"); lcd.setCursor (0,1); lcd.print(" " + String(meas_temp)); // Shows the temperature of the user through the LCD screen. } else // If it's an invalid user, { lcd.setCursor(0,0); lcd.print("Error!"); lcd.setCursor (0,1); lcd.print("Invalid User."); // Tells the user that he's not a valid user and he is unable to proceed to the temperature taking phase. } rawData =Serial.readString(); commaPos =rawData.indexOf(','); userInitial =rawData.substring(0, commaPos); // Above reads the incoming rawData again and converts into a userInitial variable. if(userInitial =="0") // If the user initial sent back is 0, it means that it's an invalid temperature because the RaspberryPi is unable to process it. { lcd.clear(); lcd.setCursor (0,0); lcd.print("Error!"); lcd.setCursor (0,1); lcd.print("Invalid Temperature."); // Prompts the user it's an invalid temperature range. } Serial.println("STANDBY"); // Sends Serial that the Arduino is still processing data. retraso (1000); // Delay for 1 second. mfrc522.PICC_HaltA(); mfrc522.PCD_StopCrypto1(); }} 
[PYTHON] RaspberryPiPython
This code is mainly used for updating the MySQL database and also to handshake with the Arduino via Serial Communication. It plays a vital role with the Arduino in this project

If you're interested in knowing more, please read the section on "HOW IT WORKS:RaspberryPi &Arduino".
'''Coded from scratch by Aden; for the Hackster.io Sigfox competition.http://www.astero.me'''# IMPORTSimport mysql.connectorimport serialimport osimport time# METHODSdef queryConnection():cursor =conn.cursor(buffered=True) cursor.execute("USE `" + databaseName + "`") # Use the userInfo database, return cursor # DATABASE INFORMATIONhost ="localhost"user ="root"password ="password"databaseName ="smartTemp"conn =mysql.connector.connect(host=host, user=user,passwd=password)# Serial CommunicationcomPort ='ttyUSB0'baudRate =9600ser =serial.Serial('/dev/' + comPort, baudRate, timeout=0) # Set the timeout as 0 so if it doesn't read a serial, it skips.print("Confirming USB Serial Port now, please wait") connected =False# Below, is to ensure that the RaPi receives the correct COM port of the Arduino board.for x in range(2):time.sleep(2) ser.write("RAPI") # Basically, here, we're writing to the Arduino to confirm communication. if connected ==False:serialConfirmation =ser.readline().strip() =="ARDUINO" # Check if the RaPi is reading the correct COM port, whether it can read the Arduino's serial communications. print(serialConfirmation) if(serialConfirmation ==False):comPort ='ttyUSB1' connected =True else:comPort ='ttyUSB0' connected =True print(comPort) ser =serial.Serial('/dev/' + comPort, baudRate) # Re-initiates this variable again, this time without a Serial Communication timeout. Meaning, it'll try to communicate with the Arduino w/o a timeout. print("COM PORT confirmed, using " + comPort) # Print to let you know which PORT the Arduino is on.# File CreationcountFile =open("count.txt", "a++") # Creates a count file if it doesn't exist.# GLOBAL VARIABLEStapRFID =Falsecursor =queryConnection()if(os.stat("count.txt").st_size ==0):# Checks if the count.txt is empty. print("Count has not been set, setting to 1 now.") count =1else:for countNumber in countFile:count =int(countNumber) # Set the count to the last counted count. print("Count has been restored from previous session:" + str(count)) try:# Tries to create the database if it doesn't already exists. print("Creating " + databaseName + " database now..") cursor.execute("CREATE DATABASE " + databaseName) # Create a database. print("Database has been sucessfully created.") except(mysql.connector.errors.DatabaseError):# If the database already exists, it excepts here. print(databaseName + " database is already created.") # If that database is found, run this block of code instead.cursor.execute("CREATE TABLE IF NOT EXISTS `userInfo` (id int, cardID VARCHAR(9), userID VARCHAR(4), userInitial VARCHAR(8))") # Create a userInfo table if it doesn't exist.cursor.execute("CREATE TABLE IF NOT EXISTS `tempData` (id int, userID VARCHAR(4), dateMeas date, timeMeas time, tempMeasure decimal(5,2))") # Create a tempData table if it doesn't exist.while True:# Endless loop. cursor =queryConnection() # Re-establishes the query connection using the queryConnection() method. cardID =str(ser.readline().strip()) # Reads the serial line and converts it to a String, stripping any empty spaces. cursor.execute("SELECT * FROM userInfo WHERE cardID ='" + cardID + "'") # Select the userInfo table with the inputted cardID from the Arduino. items =cursor.fetchone() # Fetch one line of the table. if(items !=None):# If it's able to fetch (valid user) print(cardID) # Print out the cardID that it's currently fetching. userID =str(items[2]) # Gets the userID from the fetched line. userDetails =str(items[3] + ", " + items[2]) # Get the userDetails from the fetched line. # Get the currentDate ¤tTime. currentDate =str(time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()))[0:10] currentTime =str(time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()))[11:] print(items) # Print the whole item array that was fetched. (for debugging) ser.write(b'' + userDetails) # Serial communication to the Arudino. countFile.close() # Closes the count file. countFile =open("count.txt", 'w') # Makes it so it overwrites the count file with the new saved count below. tempSignal =False while(tempSignal ==False):# Keeps looping until it gets the temperature reading from the Arduino. print("Getting Temperature") tempSignal =ser.readline().strip() =="TEMP" # Read the Arudino incoming serial. tempData =float(ser.readline().strip()) # Read the Arduino incoming serial of the temperature data. print(tempData) # Prints the retrieved temperature data from the Arduino. if(tempData>=28 and tempData <=42):# Check if the temperature is of a valid range. cursor.execute("INSERT INTO `tempData`(`id`, `userID`, `dateMeas`, `timeMeas`, `tempMeasure`) VALUES (" + str(count) + ",'" + userID + "','" + currentDate + "','" + currentTime + "','" + str(tempData) + "')") # Write into the database the necessary information. conn.commit() # Commit the INSERT changes into the database. count =count + 1 # Ups the count. countFile.write(str(count)) # Update the count file with the new count. else:# If it's not a valid temperature. ser.write(b'' + "0, 0") # Serial Communication to the Arduino informing that it's invalid temperature. else:# If it's not a valid user. ser.write(b'' + ", 0") # Serial Communication to the Arduino informing that no valid cardID is found. print("Nothing found") readySignal =ser.readline().strip() =="STANDBY" # Waits for the Arduino to tell that it's ready to do it again, to read/validate data. while(readySignal ==True):# If the Arduino is ready, loop until we're able to tell him back that we're also ready for another session. ser.write(b'' + "READY") # Serial communication basically to say we're ready too. print("sending") receivedSignal =ser.readline().strip() =="RECEIVED" if(receivedSignal ==True):readySignal =False print("received") cursor.close() # Close the query connection to prevent memory leaks. conn.close() # Closes the connection to the MySQL.
[MicroPython] Sigfox (Pycom)Python
This code is mainly used to read the serial communication from the Arduino and upload the received values to the Sigfox backend

If you're interested in knowing more, please read the section on "HOW IT WORKS:Sigfox (Pycom)"
'''100% is coded by Reginald,'''from machine import UART # Tx and Rx (``P3`` and ``P4``)from network import Sigfox # Import the sigfox library from the pycom controllerimport binascii # Import the Binary to ASCII library for converting from Binary (1,0) to ASCII (readable characters)import socket # Import socket module to enable socket connection for Sigfoximport time # Import time that can be used for delaysimport pycom # Import pycom module that contains fucntions that controls the pycom deviceimport sys # Import sys module to enable exit from the pycom running programpycom.heartbeat(False)#init Sigfox for RCZ4 (Asia)sigfox =Sigfox(mode=Sigfox.SIGFOX,rcz=Sigfox.RCZ4)uart1 =UART(1, baudrate=9600) # To set the serial communcation parametersuart1.init(9600,bits=8,parity=None, stop=1, pins =('P3', 'P4'), timeout_chars=20) # To set the serial communcation parameterswhile True:try:recv=uart1.readline() # It always reads the serial communcation for any messages if recv !=None:'''If there is a message recieved from the serial communcation, it will procced to establish the sigfox connection and process the message for sending''' #print Sigfox DeviceID print(binascii.hexlify(sigfox.id())) # print Sigfox PAC number print(binascii.hexlify(sigfox.pac())) #create Sigfox socket sk1 =socket.socket(socket.AF_SIGFOX, socket.SOCK_RAW) #make thesocket blocking sk1.setblocking(False) #configure as uplink only sk1.setsockopt(socket.SOL_SIGFOX, socket.SO_RX, False) dataList =recv.decode("utf-8") #decode the received message print("dataList :%s" %(dataList)) split_val =dataList.split(",") #split the listing based on commas # eg. if receive message is 8,35,60 -> userID =8, temperature =35.60 degree celsius userID =int(split_val[0]) # assign the 1st element in the listing to userID. temp_H =int(split_val[1]) # assign the 2nd element in the listing to the whole number of the temperature. temp_L =int(split_val[2]) # assign the 3rd element in the listing to the decimal numner of the temperature. print("userID :%d temp_H :%d temp_L :%d" % (userID, temp_H, temp_L)) bData =[userID,temp_H,temp_L] # create a list print(bData) meas_temp =temp_H + (temp_L*0.01) # merge temperature values print("measure temperature :%.2f" %(meas_temp)) sk1.send(bytes(bData)) #cast the data list to bytes and send to Sigfox backend. sk1.close() #close Sigfox socket connection. time.sleep(5) #delay for 5 seconds. except KeyboardInterrupt:sys.exit() 
[ThingSpeak] MATLAB SCRIPTMATLAB
This script focuses on combining the raw data that is sent up by the Sigfox to ThingSpeak and put them together into a presentable visual state, allowing users to properly visualize the information. It also works alongside with IFTTT by triggering a webhook URL when it reaches a fever temperature, alerting user(s) via Email.

If you're interested in learning more about this code, please read the section on "HOW IT WORKS:ThingSpeak".
%% Made from scratch by Aden; for the Hackster.io Sigfox Competition.%% http://www.astero.mereadChannelID =870479; %% Channel to read.webhookTrigger ='https://maker.ifttt.com/trigger/student_fever/with/key/h10MdSGwjSPtZQ43wH-AgoiKI0pwaljBNnGUEu4Yecn';readAPIKey ='QGHINBPNJQKULBH2'; %% Channel read API Key.writeChannelID =870482; %% Channel to write.writeAPIKey ='R6NJIM8NT5A42R9N'; %% Channel write API Key.wholeNumber =thingSpeakRead(readChannelID, 'ReadKey', readAPIKey, 'Fields', 1); %% Read the value from field 1 and save it to a variable.decimalNumber =thingSpeakRead(readChannelID, 'ReadKey', readAPIKey, 'Fields', 2)/100;%% Read the value from field 2 and save it to a variable.userID =thingSpeakRead(readChannelID, 'ReadKey', readAPIKey, 'Fields', 3);%% Read the value from field 3 and save it to a variable.display(wholeNumber, 'BEFORE') %% Display value for debugging.analyzedData =wholeNumber + decimalNumber; %% Converting the two into one whole number instead of two separate values.display(analyzedData, 'AFTER')display(userID, 'USERID')%%thingSpeakWrite(writeChannelID, analyzedData, 'Fields', 1, 'WriteKey', writeAPIKey);thingSpeakWrite(writeChannelID,'Fields',[1,2],'Values',{analyzedData,userID},'WriteKey', writeAPIKey)if(analyzedData>=38) %% Check if fever temperature. webwrite(webhookTrigger,'value1',analyzedData,'value2',userID); %% If yes, trigger the webhook and send an email of the values.end

Esquemas

How everything is connected together Connections for Distance Sensor for Arduino Connections for Temperature Sensor Connections for LED for Arduino Connections for RFID for Arduino Connections for LCD for Arduino Connections for Buzzer for Arduino

Proceso de manufactura

  1. Monitoreo de temperatura en Raspberry Pi
  2. Supervisión de la temperatura con Raspberry Pi
  3. Bricolaje:Regulación y monitoreo de temperatura para HomeBrew
  4. Monitoreo de CO2 con sensor K30
  5. Persianas inteligentes
  6. Puerta de control de temperatura sin contacto
  7. Arduino - Enviar temperatura a la web a través de serie
  8. Biblioteca de puertos IO de 8 bits para Arduino
  9. Guante de mano inteligente
  10. Health Band:un asistente inteligente para los ancianos
  11. Agricultura inteligente:una solución integral de IoT para el monitoreo de la agricultura