Introduction: IoT Cat Litter Box (with ESP32, Arduino IDE, Thingspeak and 3D Printing)

About: Maker, engineer, mad scientist and inventor

If you follow my tutorials, you know that I live with some cats and I love doing projects involving four things: 3D printing, internet of things, robots and, of course, cats! You can find other of my projects like this scale saves weight measurements in the cloud or this hanging cat bed made with PVC pipes.

When I was shooting the video on the IoT scale, I realized that it would even be used to track the weight of my cats. They usually come up on the wooden surface regularly (especially if I'm trying to weigh myself in an attempt to troll me and make I look heavier), but they don't have not have the patience to stand on the device for long enough to complete the measurements. It made me think of ways to weigth them regularly without having to worry about having to put them on some specific surface and hold them there for a while. And that's where the idea of using their litter boxes as "bait" came up.

They usually stay inside the litter box long enough to make the necessary measurements, and they use it several times a day without the need for human intervention, making the box the ideal surface for the installation of a similar device used om my IoT scale. In addition, their weights are considerably different (one has about 3 kg and the other one 5 kg), so that it would be possible to distinguish between the measurements which cat was on the scale.

But I finally realized that it would be possible to use the device to extract a lot of new information! By measuring the weight of the box it would be possible to monitor the amount of sand available inside (as a way of indicating that it is time to fill with more sand or change all the contents), the number of times the cats have used the box per day, when the box was last cleaned, etc.

I rolled up my sleeves and set out to design the project described here: a cat litter box with WiFi, using an ESP32, able to measure the weight of my cats (using weight sensors and HX711 amplifiers), monitor the general cleaning conditions of the cat litter box and even store all the data in the cloud (using the Thingspeak platform)! The device is even able to generate notifications by email, Twitter, etc.
Surely it may seem like a shitty idea (in this case, cat poo), but that can be used by the reader to learn some new skill that can be used in other projects:

- How to program an ESP32 using the Arduino IDE;

- How to read digital inputs using an ESP32;

- How to use load sensor and an HX711 for weight measurement;

- How to send ESP32 data to the cloud using Thingspeak platform;

- How to design and print a 3D case using Fusion360.

Did you like this project? Please consider supporting my future projects with a small bitcoin donation! : D

Deposit Address: 1FiWFYSjRaL7sLdr5wr6h86QkMA6pQxkXJn

_______________________________

Se você segue os meus tutoriais, sabe que eu moro com algumas gatas e que adoro fazer projetos envolvendo quatro coisas: impressão 3D, internet das coisas, robôs e, é claro, gatos! Você pode encontrar outros dos meus projetos como essa balança que armazena informações sobre o peso na nuvem ou essa rede para gatos feita com tubos de PVC.

Durante a elaboração do meu vídeo sobre a balança, percebi que seria possível até utilizá-la para monitorar o peso das minhas gatas. Elas normalmente sobem na superfície de madeira regularmente (especialmente se eu estiver tentando me pesar, numa tentativa de me trollar e fazer parecer mais pesado), porém não tem paciência de ficar sobre o dispositivo por tempo o suficiente para que haja tempo de concluir a medição. Isso me fez pensar em maneiras para pesa-las regularmente, sem ter que me preocupar em ter que coloca-las em alguma superfície especificar e segura-las lá por um tempo. E foi aí que surgiu a ideia de utilizar suas caixas de areia como "isca".

Elas normalmente ficam sobre/dentro da caixa por tempo suficiente para fazer as medições necessárias, e vão para a caixa várias vezes por dia sem a necessidade de intervenção humana, fazendo com que a caixa se tornasse a superfície ideal para a instalação de um dispositivo similar a uma balança. Além disso, seus pesos são consideravelmente diferentes (uma tem cerca de 3 kg e a outra uns 5 kg), de forma que seria possível distinguir entre as medições qual gata estava sobre a balança.

Porém eu acabei percebendo que seria possível utilizar o dispositivo para extrair uma série de novas informações! Medindo o peso da caixa seria possível monitorar a quantidade de areia disponível em seu interior (como uma forma de indicação de que está na hora de preencher com mais areia ou trocar todo o conteúdo), a quantidade de vezes que as gatas tem utilizado a caixa por dia, quando a caixa foi limpa pela última vez, etc.

Arregacei as mangas e parti para elaboração do projeto descrito aqui: uma caixa de areia para gatos com WiFi, usando um ESP32, capaz de medir o peso das minhas gatas (usando sensores de peso e amplificadores HX711), monitorar as condições gerais de limpeza da caixa e ainda armazenar todos os dados na nuvem (utilizando a plataforma Thingspeak)! De quebra o dispositivo ainda é capaz de gerar notificações por e-mail, Twitter, etc.

Certamente pode parecer uma ideia de merda (no caso, de gato mesmo), mas que poder servir para o leitor aprender algumas habilidade que podem ser utilizadas em outros projetos:

- Como programar um ESP32 utilizando a IDE do Arduino;

- Como ler entradas digitais com o ESP32;

- Como utilizar sensor de carga e um HX711 para medição de peso;

- Como enviar dados do ESP32 para a nuvem utilizado a plataforma Thingspeak;

- Como projetar e imprimir um case em 3D usando Fusion360.

Gostou desse projeto? Por favor considere a possibilidade de financiar meus futuros projetos com uma pequena doação de bitcoins! :D

Endereço de deposito: 1FiWFYSjRaL7sLdr5wr6h86QkMA6pQxkXJn

Step 1: Tools and Materials

The following tools and materials were used in this project:

Tools and materials:

  • 3D printer (link / link / link). It was used for printing the case where the electronics are encloused.
  • PLA filament (link / link / link) of any color you want.
  • Solder iron and wire. Some of the components (ESP32 Firebeetle and HX711, for instance) doesn't come with soldered terminals. I needed to solder some wires or pins in order to connect those devices.
  • Shrinking tube. l also had to solder the wires of each load cell. A piece of shrinking tube might be used for a better isolation of the conductors.
  • Screwdriver. The structure is mounted using some screws. A set of screwdrivers was used.
  • M2x6mm Bolts. They were used for mounting the electronics inside the case.
  • FireBeetle ESP32 dev board. It's really easy to use and program using Arduino IDE. It has built-in Wi-Fi module, so you can use it in a variaty of projects. You can also use other ESP8266 based bords (link / link / link) if you wish.
  • HX711 module (link / link / link). This works as a load cell amplifier. Four strain gauge load cells are connected to this module, and it communicates on a serial communication with the microcontroller.
  • 50kg load cell (x4); (link / link / link). They are used to measure the weight. Four of them were used for a maximum weight of 200kg.
  • Magnetic door sensor (link / link / link). It consists in a magnectic switch, which was used to detect that the litter box is opened.
  • Micro USB cable;
  • 6 female-female jumper wires;
  • Cat litter box.

The links described above are only a suggestion of where you can find the items used in this tutorial (and support my future hacks). Feel free to search for them elsewhere and buy at your favourite store.

I used a FireBeetle ESP32 dev board, which was kindly supplied by DFRobot.

Did you know you can buy a Creality Ender 3 3Dprinter for only $168.99? Get yours! https://rebrand.ly/3Dprinter-BG

_______________________________

As seguintes ferramentas e materiais foram utilizadas nesse projeto:

Ferramentas e materiais:

  • Impressora 3D (link / link / link). Foi utilizada para impressão do case onde os componentes eletrônicos ficam protegidos.
  • Filamento PLA (link / link / link) de qualquer cor desejada.
  • Ferro de solda e fio de solda. Alguns componentes (ESP32 Firebeetle e HX711, por exemplo) não vem com terminais soldados. Eu precisei soldar alguns fios e pinos a fim de conectar os dispositivos.
  • Tubo termoretrátil. Eu também tive que soldar os fios das células de carga. Um pedaõ de macarão termoretrátil pode ser usado para melhor isolamento dos condutores
  • Chave Phillips: parte da estrutura é montada usando parafusos. Um conjunto de chaves ajudará na montagem.
  • Parafusos M2x6mm: Usados para montar os componentes eletrônicos dentro do case.
  • Placa de desenvolvimento FireBeetle ESP32. Essa placa é realmente fácil de usar e programar usando a IDE do Arduino. Ela vem com módulo WiFi integrado, permitindo a sua utilização em uma variedade de projetos. Você também pode usar outras placas de desenvolvimento com ESP8266, por exemplo (link / link / link) se desejado.
  • Módulo HX711 (link / link / link). Esse módulo funciona como amplificador para as células de carga. Quatro strain gauges foram conectados nesse módulo, o qual se comunica através de comunicação serial com o microcontrolador.
  • Células de carga de 50kg (x4); (link / link / link). Elas sáo usadas para medição do peso. Quatro delas foram usadas, permitindo a medição de até 200 kg.
  • Sensor magnético de porta (link / link / link). Consiste em uma chave magnética, a qual foi utilizada para detectar que a caixa foi aberta.
  • Cabo Micro USB;
  • Jumpers e fios;
  • Caixa de areia para gatos.

Os links descritos acima são apenas uma sugestão de onde você pode achar cada um dos item usados nesse tutorial (e ajudar a financiar meus futuros tutoriais). Sinta-se a vontate para procurar por eles em outros lugares e comprar de sua loja favorita.

Eu usei uma placa de desenvolvimento Firebeetle ESP32, a qual foi gentilmente fornecida pelo site DFRobot. Ela funcionou perfeitamente!

Você sabia que pode comprar uma impressora 3D Creality Ender 3 por apenas $168,99 dólares? Adquira a sua em: https://rebrand.ly/3Dprinter-BG

Step 2: Setup FireBeetle ESP32 on Arduino IDE

For this project I used Arduino IDE for programming my ESP32 module. It's the easiest way if you've already used an Arduino before, and you won't need to learn a new programming language, like Python or Lua for instance.

If you've never done this before, first you'll have to add ESP32 board support to the Arduino software.


1. Download and install Arduino IDE latest version

You can find the latest version for Windows, Linux or MAC OSX on Arduino's website: https://www.arduino.cc/en/main/software

Download it for free, install it on your computer and launch it.

2. Adding ESP32 board

Arduino IDE already comes with support to a lot of different boards: Arduino Nano, Mine, Uno, Mega, Yún, etc. Unfortunatly ESP32 isn't by default among those suported development boards. So in order to upload your codes to a ESP32 base board, you'll have to add its properties to Arduino's software first.

  • Navigate to File > Preferences;
  • Add the following URL to Additional Boards Manager textbox (the one on the bottom of the Preferences window):

https://git.oschina.net/dfrobot/FireBeetle-ESP32/raw/master/package_esp32_index.json

  • If the text box wasn't blank, it means had already add other boards before on Arduino IDE before. Add a comma at the end of the previous URL and the one above.
  • Hit "Ok" button and close the Preferences Window.
  • Navigate for Tools > Board > Boards Manager for adding your ESP32 board.
  • Type "FireBeetle-ESP32" on the search text box, select "FireBeetle-ESP32 Mainboard by DFRobot DFRDuino" and install it.

Now your Arduino IDE will be ready to work with ESP32 FireBeetle board.

Plug the microUSB cable on the ESP32 and on your computer. It will automatically install Windows communication driver. If it fails to install the driver, download the following file and manually install the driver for the newly connected device.

https://git.oschina.net/dfrobot/FireBeetle-ESP32/raw/master/FireBeetle-ESP32.inf

If you wish to use an alternative ESP32 based board, add the appropriate board.


3. Adding the libraries

The following libraries will be used for our Arduino code. Download the following libraries:

Navigate to Sketch-> Include Library -> Manage Libraries... on your Arduino IDE and add the libraries above.

............

Now that your dev environment is ready, let's move on to the next step!

_______________________________

Para esse projeto eu utilizei a IDE do Arduino para programar meu módulo ESP32. É a maneira mais fácil se você já utilizou antes um Arduino, e você não precisará aprender uma linguagem de programação nova, como Python ou Lua por exemplo. Se você nunca fez isso antes, primeiramente você precisará adicionar o suporte às placas ESP32 no Arduino IDE.

1. Baixe e instale a versão mais nova do Arduino IDE

Você pode encontrar a versão mais nova para Windows, Linux ou MAC OSX no site do Arduino: https://www.arduino.cc/en/main/software

Baixe o programa de graça, instale e abra no seu computador.

2. Adicionando placas ESP32 na IDE do Arduino

A IDE do Arduino já vem com suporte para várias placas: Arduino Nano, Mine, Uno, Mega, Yún, etc. Infelizmente as ESP32 não está por padrão entre as placas de desenvolvimento suportadas. Então, a fim de conserguir compilar os seus códigos e transferí-los para uma placa baseada em ESP32, primeiro você terá que adicionar algumas propriedades ao software do Arduino.

Se a caixa de texto não estiver me branco, seignifica que you já adicionou outras placas antes na IDE do Arduino. Adicione uma vírgula entre o fim da URL anterior e a URL acima. Aperte o butão "Ok" e feche a janela de preferências.

  • Navegue para Ferramentas > Placas > Gerenciar placas e adicione sua placa ESP32.
  • Digite "FireBeetle-ESP32" na caixa de busca, seleciono "FireBeetle-ESP32 Mainboard by DFRobot DFRDuino" e a instale.

Agora sua IDE do Arduino estará pronta para trabalhar com placas ESP32 Firebeetle.

Plugue o cabo microUSB no ESP32 e no seu computador. O Windows tentará instalar o driver de comunicação automaticamente. Se ele não conseguir prosseguir com a instalação, baixe o seguinte arquivo e instale o driver do dispositivo manualmente.

https://git.oschina.net/dfrobot/FireBeetle-ESP32/r...

Se você quiser utilizar outras placas ou módulos ESP32, adicione a placa desejada seguindo procedimento semelhante ao descrito acima.

3. Adicionando as bibliotecas

As seguintes bibliotecas foram usadas no código do Arduino desse projeto. Baixe as seguintes bibliotecas:

Navegue para Sketch -> Incluir biblioteca -> Gerenciar Bibliotecas... na IDE do Arduino e adicione as bibliotecas acima.

............

Agora que o seu ambiente de desenvolvimento está pronto, vamos para o próximo passo!

Step 3: Wiring Up - HX711, Load Cells, Reed Switch and ESP32

This project used the following electronic components:

  • ESP32 Firebeetle development board: This board has an Expressif microcontroller and is the component responsible for reading variables, handling and sending data to the cloud using a WiFi connection. It is in this device that the project code runs.
  • Load Sensors: component responsible for measuring the force, converting the pressure applied on the device into an electrical signal.
  • Amplifier HX711: circuit responsible for the amplification of the electric signal generated by the charge cells and digital analogue conversion of sina. The signal generated by the load cells has a very restricted amplitude (signal in mV). This circuit amplifies this signal and performs the conversion of the analog signal to digital, delivering the converted signal to the microcontroller.
  • Door sensor switch: consists of a switch that is normally closed in the absence of a magnetic field. When applied a magnetic field in its proximity, the switch closes an internal contact, allowing the conduction of electric current. In this project, a switch of this type was used to identify whether or not the top of the litter box was opened. A magnet has been attached to the top cover, while the switch is attached to the controlled and fixed on the bottom of the box. When that cover is closed, the magnet and key will be aligned and close together, keeping the switch closed. When the two parts are separated, the magnet will move away from the switch and the circuit will open.

Each device was connected according to the schematics.

HX711 - input:

  • Upper left load cell signal (red wire) => HX711 E- pin
  • Lower left load cell signal (red wire) => HX711 A+ pin
  • Upper right load cell signal (red wire) => HX711 A- pin
  • Lower right load cell signal (red wire) => HX711 E+ pin

HX711- output:

  • HX711 Vcc pin => ESP32 3.3V pin
  • HX711 GND pin => ESP32 GND pin
  • HX711 SCK pin => ESP32 GPIO 2 (pin D9)
  • HX711 DT pin => ESP32 GPIO 5 (pin D8)

Door sensor:

  • Reed switch (terminal 1) => ESP32 GND pin
  • Reed switch (terminal 2) => ESP32 GPIO 25 (pin D2)

When everything is wired up, plug a USB cabe on the ESP32 and get ready for uploading the code.

_______________________________

Esse projeto utilizou os seguintes componentes eletrônicos:

  • Placa de desenvolvimento ESP32 Firebeetle: essa placa conta com um microcontrolador Expressif e é o componente responsável pela leitura das variáveis, tratamento e envio dos dados para a nuvem usando uma conexão WiFi. É nesse dispositivo que o código do projeto roda.
  • Sensors de carga: componente responsáveis pela medição da força, convertendo a pressão aplicada sobre o dispositivo em um sinal elétrico.
  • Amplificador HX711: circuito responsável pela amplificação do sinal elétrico gerado pelas céluas de carga e conversão analógica digital do sina. O sinal gerado pelas células de carga possui amplitude bastante restrita (sinal em mV). Essa placa amplifica esse sinal e realiza a conversão do sinal analógico em digital, entregando o sinal convertido ao microcontrolador.
  • Sensor de porta: consiste em um chave que normalmente fica fechada na ausência de um campo magnético. Quando aplicado um campo magnético na sua proximidade, a chave fecha um contato interno, possibilitando a condução da corrente elétrica. Nesse projeto, uma chave desse tipo foi utilizada para identificar se a tampa superior da caixa de areia foi aberta ou não. Um imã foi colado na tampa superior, enquanto a chave fica conectada ao controlado e fixa na parte inferior da caixa. Quando a caixa estiver fechada, o ímã e a chave estarão alinhados e próximos entre si, mantendo assim a chave fechada. Quando as duas partes forem separadas, o ímã se distanciará da chave e o circuito será aberto.

Cada dispositivo foi conectado de acordo com o esquemático.

HX711 - entrada:

  • Sinal da célula do canto superior esquerdo (fio vermelho) => Pino E- do HX711
  • Sinal da céula do canto inferior esquerdo (fio vermelho) => Pino A+ do HX711
  • Sinal da célula do canto superior direito (fio vermelho) => Pino A- do HX711
  • Sinal da célula do canto inferior direito (fio vermelho) => Pino E+ do HX711

HX711- saída:

  • Pino Vcc do HX711 => Pino 3.3V do ESP32
  • Pino GND do HX711 => Pino GND do ESP32
  • Pino SCK do HX711 => Pino GPIO 2 (pino D9) do ESP32
  • Pino DT do HX711 => Pino GPIO 5 (pino D8) do ESP32

Sensor de porta:

  • Reed switch (terminal 1) => Pino GND do ESP32
  • Reed switch (terminal 2) => Pino GPIO 25 (pino D2) do ESP32

Quando tudo estiver conectado, plugue o cabo USB no ESP32 e se prepare para baixar o código.

Step 4: Thingspeak Setup

There are several cloud data storage services for use with the internet of things. They allow communication between your microcontroller and the network, allowing you to send and receive all kinds of data. You can see some of the projects I've developed using Adafruit.io, for example:

https://www.instructables.com/id/Wi-Fi-Smart-Scal...

https://www.instructables.com/id/Wi-Fi-Controlled-...

https://www.instructables.com/id/IoT-Air-Freshner-...

Thingspeak is another such service. It is really easy to use, allowed monitoring of various information.

1. Create your account: first you must create your account at https://thingspeak.com/.

2. Create your channel: Once your account is created, you can create a channel where your data will be stored. Click on "New channel" and enter the name of your channel In my case I created a channel called "IoT Litter Box".

3. Set the fields of your channel: each channel can have up to 8 fields. Each field is equivalent to a variable that will be stored on your channel. In my project, 6 channels were used:

  • Cat Weight #1
  • Cat Weight #2
  • Status
  • Sand level
  • Uses per day of cat #1
  • Uses per day of cat #2

4. Write down your writing key: click the "Keys" option and copy your write key. You will need this information later in your Arduino code.

And it's ready! Your channel will be set up to start receiving data from your controller. You can see the data beginning to arrive in the Public view tab (if your channel is configured as public) or Private view. You can create specific views for public and private modes.

_______________________________

Existem vários serviços de armazenamento de dados na nuvem para uso com internet das coisas. Eles permitem a comunicação entre o seu microcontrolador e a rede, permitindo enviar e receber todo tipo de dado. Você pode ver alguns dos projetos que desenvolvi utilizando o Adafruit.io, por exemplo:

https://www.instructables.com/id/Wi-Fi-Smart-Scale-with-ESP8266-Arduino-IDE-Adafrui/

https://www.instructables.com/id/Wi-Fi-Controlled-Robot-Using-Wemos-D1-ESP8266-Ardu/

https://www.instructables.com/id/IoT-Air-Freshner-with-NodeMCU-Arduino-IFTTT-and-Ad/

O Thingspeak é outro desses serviços. Ele é realmente fácio de utilizar, permitido o monitoramento de várias informações.

1. Crie a sua conta: primeio você deve criara a sua conta em https://thingspeak.com/.

2. Crie o seu canal: uma vez que sua conta esteja criada, é possível criar um canal onde seus dados serão armazenados. Clique em "New channel" e informe o nome do seu canal No meu caso eu criei um canal chamado "IoT Litter Box".

3. Defina os campos do seu canal: cada canal pode ter até 8 campos. Cada campo equivale a uma variável que será armazenada no seu canal. No meu projeto foram utilizados 6 canais:

  • Peso do gato #1
  • Peso do gato #2
  • Status
  • Nível de areia
  • Usos por dia do gato #1
  • Usos por dia do gato #2

4. Anote a sua chave de escrita: clique na opção "Chaves" e copie a sua chave de escrita. Você precisará dessa informação posteriormente no seu código do Arduino.

E pronto! O seu canal estará configurado para começar a receber dados do seu controlador. Você pode ver os dados que começarem a chegar na aba Public view (se seu canal for configurado como público) ou Private view. É possível criar visualizações específicas para os modos público e privado.

Step 5: Arduino Code

The code idea is as follows:
1 - The controller must be initially calibrated to know the empty box weight and adjust the calibration factor. The information on how to calibrate is presented at the end of this tutorial. This information will be stored in the controller memory and is not expected to change over time. This value will be used in the future to allow the calculation of the volume of sand and individual weight of the cats.

2 - Whenever the top of the box is opened, the controller understands that the box has gone into maintenance (cleaning) and should stop monitoring the box weight measurement. In that period, someone should be tossing sand (adding or removing sand, poop, etc.), and there should be fluctuations in box weight.

3 - As soon as the box is closed, the controller should wait some time for stabilization and re-check the weight. The first measurement performed should be stored in the controller memory as the weight of the box + sand. This value will be subtracted from future measurements to allow the calculation of the weight of the cats discounted from the weight of the box and its sand content.

4 - By subtracting the measured weight (in the absence of a cat inside the box) from the empty box weight (stored in the controller during its calibration), it is possible to determine the volume of sand in the box. This value is expected to decrease over time whenever the litter box is cleaned. You can set alarm limits to alert when the sand level in the bin is too low, indicating the need for general cleaning and sand replacement. The sand volume in the box will be sent to the cloud and you can generate alerts.

5 - Whenever the controller senses a significant increase in the weight of the box with the top cover closed, you will understand that some cat must have come in to make your needs. After stabilizing the measurement (understanding that the cat has stopped moving to make its needs), the controller will store the measured average weight. The value will be compared with expected maximum and minimum values for each of the cats (assuming more than one cat should use the box) in order to determine which cat has entered the box. The information on the weight of the cat and the count of times the cat used the box on the day will be updated and sent to the cloud.

6 - Periodically the controller check the time from a server. When detecting the beginning of a new day the counter of times that each cat used the box will be reset.

The following statements should be updated according to your case:

  • myChannelNumber = Thingspeak channel number
  • apiKey = ThingSpeak API key
  • ssid = ssid of WiFi network
  • pass = WiFi network password
  • weightbox = weight indicated for the empty box
  • cat1MinWeight = minimum weight of cat # 1
  • cat1MaxWeight = maximum weight of cat # 1
  • cat2MinWeight = minimum weight of cat # 2

_______________________________


A ideia do código é a seguinte:

1 - O controlador deverá ser inicialmente calibrado para saber o peso da caixa vazia e ajustar o fator de calibração. A informação sobre como calibrar é apresentada no final desse tutorial. Essa informação ficará armazenada na memória do controlador e não espera-se que varie com o tempo. Esse valor será utilizado no futuro para permitir o cálculo do volume de areia e peso individual dos gatos.

2 - Toda vez que a parte superior da caixa for aberta, o controlador entende que a caixa entrou em manutenção (limpeza) e deve parar de monitorar a medição de peso da caixa. Nesse período, alguém deverá está mexendo na areia (adicionando ou tirando areia, cocô, etc.), e deverão haver flutuações no peso da caixa.

3 - Assim que a caixa for fechada, o controlador deverá aguardar algum tempo para estabilização e voltar a verificar o peso. A primeira medição realizada deverá ser armazenada na memória do controlador como sendo o peso da caixa + areia. Esse valor será substraido de medições futuras para permitir o cálculo do peso dos gatos descontado do peso da caixa e de seu conteúdo de areia.

4 - Subtraindo-se o peso medido (na ausência de um gato no interior da caixa) do peso da caixa vazia (armazenado no controlador durante sua calibração), é possível determinar o volume de areia na caixa. Espera-se que esse valor diminua com o tempo sempre que a caixa é limpa. Pode-se definir limites de alarmes para alertar quando o nível de areia na caixa estiver muito baixo, indicando a necessidade de uma limpeza geral e reposição da areia. O volume de areia na caixa será enviado para a nuvem e poderá gerar alertas.

5 - Sempre que o controlador sentir um aumento significativo no peso da caixa com a tampa superior fechada, entenderá que algum gato deverá ter entrado para fazer suas necessidades. Após estabilização da medição (entendendo que o gato parou de se locomover para fazer as suas necessidade), o controlador armazenará o peso médio medido. O valor será comparado com valores máximos e mínimos esperados para cada um dos gatos (assumindo que mais de um gato deverá utilizar a caixa), de forma a determinar qual gato entrou na caixa. A informação do peso do gato e o contador de número de vezes que o gato utilizou a caixa no dia serão atualizadas e enviadas para a nuvem.

6 - Periodicamente o controlador verificar o horário a partir de um servidor. Ao detectar o início de um novo dia o contador de vezes que cada gato utilizou a caixa será zerado.

As seguintes constates deverão ser atualizadas de acordo com o seu caso:

  • myChannelNumber = número do canal do Thingspeak
  • apiKey = API key do ThingSpeak
  • ssid = ssid da rede WiFi
  • pass = senha da rede WiFi
  • weightbox = peso indicado para a caixa vazia
  • cat1MinWeight = peso mínimo do gato #1
  • cat1MaxWeight = peso máximo do gato #1
  • cat2MinWeight = peso mínimo do gato #2

Step 6: 3D Modeling

3D printing was used to make some of the parts in this project. Of course the litter box itself was bought in a normal pet shop. However, some custom parts had to be designed and printed to allow the electronics to be added to the litter box.
All parts were designed using Fusion360 CAD software.

The following parts were designed:

  • Supports for the load sensors: the load sensors are embedded inside four supports on the box feet. Such brackets allow the installation / removal of the sensors..

  • Case: the case protects the electronic components from physical contact. The case is designed to be installed in the box using double-sided adhesive tape, thus allowing the case to be subsequently removed (for cleaning the case, for example).
  • Case cover: allows frontal closure of the case, protecting electronic components.

    .

_______________________________

Foi utilizada impressão 3D para construção de algumas das partes nesse projeto. Naturalmente a caixa de areia em si foi comprada em um pet shop normal. Porém, algumas peças customizadas tiveram que ser projetadas e impressas para permitir adicionar os componentes eletrônicos à caixa. Todas as partes foram projetadas usando o software de CAD Fusion360.

As seguintes peças foram projetadas:

  • Suportes para as sensores de carga: os sensores de carga são encaixados no interior de quatro suportes nos pés da caixa. Tais suportes permitem a instalação/remoção do sensores.
  • Case: o case protege os componentes eletrônicos, protengedo-os de contato físico. O case foi projetado para ser instalado na caixa usando fita adesiva dupla face, permitindo assim que o case seja posteriormente removido (para limpeza da caixa, por exemplo).
  • Tampa do case: permite o fechamento frontal do case, protegendo os componentes eletrônicos.

Step 7: 3D Printing

You can download all the stl files on the following websites:

https://www.thingiverse.com/thing:3737074

I printed the whole structure in PLA, usign two different colors. The whole print took me around 5h, using 0.2 mm resolution and 10% infill. No supports needed. This is a experimental prototype. Notice that it was designed for a given ESP32 dev board model (the ESP32 Firebeetle).

Sensor pad:

Case:

Front cover:

If you don't have a 3D printer, here are some things you can do:

  • Ask a friend to print it for you;
  • Find a hacker/maker space nearby. The parts used in this model can be printed quickly. Some hacker/maker spaces will only charge your for the materials used;
  • Buy your own 3D printer. You can find the Creality Ender 3 for only $169.99! Get yours at https://rebrand.ly/3Dprinter-GB
  • Improvise! You can try to assemble a structure without 3D printed parts.

_______________________________

Você pode baixar os arquivo stl nos sites abaixo:

https://www.thingiverse.com/thing:3737074

Eu imprimi a estrutura inteira em PLA, usando duas cores diferentes. A impressão total levou cerca de 5h, usando resolução de 0,2 mm e 10% de preenchimento. Não foi necessário o uso de suportes.

Esse projeto é um protótipo experimental. Note que o case foi projetado para uma placa ESP32 específica (ESP32 Firebeetle).

Se você não tem uma impressora 3D, aqui vão algumas coisas que você pode fazer:

  • Pedir para um amigo imprimir para você;
  • Encontrar um makers space na sua cidade. As partes usadas nesse modelo podem ser impressa rapidamente. Alguns maker spaces te cobrarão apenas pelo mateiral utilizado;
  • Compre sua própria impressora 3D. Você pode encontrar a Creality Ender 3 por apenas USD 169,99 no seguinte link: https://rebrand.ly/3Dprinter-GB
  • Improvise! Você pode montar a estrutura sem as partes impressas em 3D.

Step 8: Assembling the Litter Box

Once the parts are printed, it's time to assemble!

1 - Solder the terminals of the HX711 module to the ESP32 using some jumpers according to the schematic previously presented;

2 - Solder a pin bar (male type) on the HX711 for later connection of the load cells;

3 - Install the ESP32 and HX711 in the case using 6 M2x6mm screws;

4 - Thread the reed switch wires through the bottom hole of the case. Solder the reed switch terminals according to the schematic above;

5 - Fit the load cells inside the supports printed in 3D;

6 - Apply double-sided tape to the back of the case and glue to the side of the litter box;

7 - Glue the load cells to the bottom of the litter box;

8 - Solder the wires of the load cells according to the schematic presented above. Solder a female connector on the red wire of each cell to allow its connection to the pin bar on the HX711;

9 - Arrange the wires. Use insulation tape to stick them to the box;

10 - Collect the load cells to the HX711 module according to the schematic previously presented;

11 - Install the front cover. Use three M2 x 6mm screws to secure the cover;

12 - Stick the reed switch on the box (bottom) and the magnet on the box cover (top). Both should be aligned;

13 - Plug the micro USB connector to power the circuit.

_______________________________

Uma vez que as partes estiverem impressas, é hora da montagem!

1 - Solde os terminais do módulo HX711 ao ESP32 usando alguns jumpers de acordo com o esquemático apresentado anteriormente;

2 - Solde uma barra de pinos (tipo macho) no HX711 para posterior conexão das células de carga;

3 - Instale o ESP32 e o HX711 no case usando 6 parafusos M2x6mm;

4 - Passe os fios do reed switch pelo orifício inferior do case. Solde os terminais do reed switch de acordo com o esquemático apresentado anteriormente;

5 - Encaixe as células de carga no interior dos suportes impressos em 3D;

6 - Aplique fita dupla-face na parte posterior do case e cole na lateral da caixa de areia;

7 - Cole as células de carga na parte inferior da caixa;

8 - Solde os fios das células de carga de acordo com o esquemático apresentado anteriormente. Solde um conector fêmea no fio vermelho de cada célula para permitir sua conexão à barra de pinos no HX711;

9 - Organize os fios. Use fita isolante para colá-los à estrutura;

10 - Colecte as células de carga ao módulo HX711 de acordo com o esquemático apresentado anteriormente;

11 - Instale a tampa frontal. Use três parafusos M2 x 6mm para fixar a tampa;

12 - Cole a reed switch na caixa (parte inferior) e o ímã na tampa da caixa (parte superior). Ambos devem ficar alinhados;

13 - Plugue o conector micro USB para alimentação do circuito.

Step 9: Calibration

The calibration of the balance consists of the determination of two values: the zero and the calibration factor.
For calibration of the scale, the following steps must be followed:

1 - Download the calibration code in the ESP32 and open the Serial Monitor;

2 - Every second the controller will read the weight in the load cells and print on the screen. Put a known weight on the box (a clean sandbag, for example) and check the value indicated on the screen. The value indicated on the serial port should match the weight of the reference weight.

3 - If the value is not as expected, type + or - in the Serial Monitor (followed by enter) to increase or decrease the calibration factor of the scale until the indicated weight coincides with its reference weight.

4 - Remove weight and press 0 followed by enter. The controller will measure the new value from zero, considering the current calibration factor.

5 - Put the reference weight again and check the indicated value. If the value is not nearly as expected, repeat steps 3 through 5 until the desired result is achieved.

Note the values of the calibration factor and the empty box weight. These values should be updated in the final Arduino code.

_______________________________

A calibração da balança consiste na determinação de dois valores: o zero e o fator de calibração.

Para a calibração da balança, os seguintes passos devem ser seguidos:

1 - Baixe o código de calibração no ESP32 e abra o Serial Monitor;

2 - A cada segundo o controlador irá ler o peso na células de carga e imprimir na tela. Coloque um peso conhecido sobre a caixa (um saco de areia limpa, por exemplo) e verifique o valor indicado na tela. O valor indicado na porta serial deverá coincidir com o peso do peso de referência.

3 - Caso o valor não seja o esperado, digite + ou - no Serial Monitor (seguido de enter) para incrementar ou decrementar o fator de calibração da balança, até que o peso indicado coincida com o seu peso de referência.

4 - Retire o peso e aperte 0 seguido de enter. O controlador medirá o novo valor do zero, considerando o fator de calibração atual.

5 - Recoloque o peso de referência e verifique o valor indicado. Caso o valor não esteja próximo do esperado, repita os passos 3 a 5 até atingir o resultado desejado.

Anote os valores do fator de calibração e do peso da caixa vazia. Esses valores deverão ser atualizados no código do Arduino final.

Step 10: Testing

Once the project is complete, open the lid, put sand in the box and power the circuit. The controller will connect to the internet and begin to run the code.
Now just wait for some of the cats to show up to see if everything is working properly.

You can track the data daily on the Thingspeak website.

_______________________________

Uma vez que o projeto estiver concluído, abra a tampa, coloque areia na caixa e alimente o circuito. O controlador se conectará a internet e começará a rodar o código.

Agora é só espera algum dos gatos aparecer para ver se está tudo funcionando corretamente.

Você poderá acompanhar os dados diarimente no site do Thingspeak.

Step 11: Bonus Round #1 - Daily E-mail Reports

Once the data is stored on the Thingspeak server, you can use this data to generate alerts, send emails, tweets, etc.
In this step I'll show you how you can generate a daily email report with a summary of the information collected. To do this, I'll use the integration between Thingspeak and IFTTT.

The following steps should be followed:

1) Create an account in IFTTT (or log in to the account if you already have one).

2) Create a new applet. Select "My Applets" and hit the "New Applet" button.

3) Select as "input" (+ This) the Webhooks service.

4) Complete the trigger configuration by clicking on "Receive a web request box". Create an event name (in my case I used "LitterBox", and create the trigger.

6) Choose the output (+ That). Select the "Email" option.

7) Select the "Send me an email box" option and configure the format of the message. In my case, I used only the "Event name", "OccuredAt" and "Value1" fields in the email body. Create the action and end the applet.

8) Select My Applets> Services and search for Webhooks. Click the documentation button. Copy your key (you will need this information later).

9) You should now create a code in Matlab (MATLAB Analysis) to evaluate the data and send the e-mail request to the IFTTT. In Thingspeak, select Applications> MATLAB Analysis.

10) Select "New" and enter the code below and save MATLAB Analysis.

% Read the channel data from the past Day.
% Send an email via the IFTTT service to report the user about the measurements

% Store the channel ID for the IoT Litter Box.
channelID = XXXXX;

% Enter the trigger url from IFTTT.  It will have the form:
iftttURL = 'https://maker.ifttt.com/trigger/LitterBox/with/key/XXXXX';

% Channel Read API Key (if you are using your own moisture channel)
% If your channel is private, then enter the read API Key between the '' below:
readAPIKey = 'XXXXX';

% Read the last day data from ThingSpeak
cat1weightData = thingSpeakRead(channelID,'NumDays',1,'Fields',1,'ReadKey',readAPIKey);
cat2weightData = thingSpeakRead(channelID,'NumDays',1,'Fields',2,'ReadKey',readAPIKey);
cat1usesData = thingSpeakRead(channelID,'NumDays',1,'Fields',5,'ReadKey',readAPIKey);
cat2usesData = thingSpeakRead(channelID,'NumDays',1,'Fields',6,'ReadKey',readAPIKey);
sandData = thingSpeakRead(channelID,'NumDays',1,'Fields',4,'ReadKey',readAPIKey);

% Calculate average daily values
avgcat1 = (max(cat1weightData) + min(cat1weightData))/2;
avgcat2 = (max(cat2weightData) + min(cat2weightData))/2;
avgsand = (max(sandData) + min(sandData))/2;

% Calculate number of uses of the box
usescat1 = max(cat1usesData);
usescat2 = max(cat2usesData);

% Create message
message = "<b>Daily report:</b><br> <b>- Cat #1:</b><br>- Average weight: " + ....
num2str(avgcat1,2) + " kg<br>" + "- Used the litter box " + num2str(usescat1) + ...
" times today<br><br>" + "<b>- Cat #2:</b><br>- Average weight: " + ...
num2str(avgcat1,2) + " kg<br>" + " - Used the litter box " + num2str(usescat2) + ...
" times today<br>" + "<br><b>- Sandbox status:</b><br>- Sand weight: " + ...
num2str(avgsand,2) + " kg<br>" + "- Total uses: " +  num2str(usescat1 + usescat2);

% Send message to IFTTT
webwrite(iftttURL,'value1',message);

Notice you'll have to update it with your Thingspeak channel and read key and IFTTT URL key.

11) You should now create a TimeControl that will serve as a trigger to execute the above code. Click Application> Timecontrol> New

12) Choose how often the code should be executed and the name of the analysis and save the new Timecontrol.

13) Ready! The Code should be executed daily at the established time and send a daily report to your email!

_______________________________

Uma vez que os dados estão armazenados no servidor do Thingspeak, é possível utilizar esses dados para gerar alertas, enviar e-mails, tweets, etc.

Nesse passo eu vou mostrar como é possível gerar um relatório diário por e-mail com um resumo das informações coletadas. Para isso, usarei a integração entre o Thingspeak e o IFTTT.

Os seguintes passos devem ser seguidos:

1) Crie uma conta no IFTTT (ou se logue na conta se já tiver uma).

2) Crie um novo applet. Selecionem "My Applets" e aperte no botão "New Applet".

3) Selecione como "input" (+This) o serviço do Webhooks.

4) Conclua a configuração do gatilho clicando em "Receive a web request box". Crie um nome de evento (no meu caso usei "LitterBox", e crie o gatilho.

6) Escolha a saída (+That). Selecione a opção "Email".

7) Selecione a opção "Send me an email box" e configure o formato da mensagem. No meu caso usei no corpo do e-mail apenas os campos "Event name", "OccuredAt" e "Value1". Crie a ação e termine o applet.

8) Selecione My Applets > Services e procure por Webhooks. Clique no botão de documentação. Copie a sua chave (você precisará dessa informação posteriormente).

9) Agora você deverá criar o um código em Matlab (MATLAB Analysis) para avaliar os dados e enviar a requisição de e-mail para o IFTTT. No Thingspeak, selecione Aplicações > MATLAB Analysis.

10) Selecione "Novo" e entre o código abaixo e salve o MATLAB Analysis.

Note que você precisará atualizá-lo as suas chaves do Thingspeak e do IFTTT e número do canal.

11) Agora você deverá criar um TimeControl que servirá de gatilho para executar o código acima. Clique em Aplicação > Timecontrol > New

12) Escolha a frequência com que o código deverá ser executado e o nome da análisee salve o novo Timecontrol.

13) Pronto! O Código deverá ser executado diariamente no horário estabelecido e enviar um relatório diário para o seu e-mail!

Step 12: Bonus Round #2 - Warnings! (coming Soon!)

Step 13: Final Considerations

I put a lot of effort into this project, to make it as clear and educational as possible. If you liked it, please don't forget to 'like' and 'share' it. Your support is very important to keep my job! :D

If you still don't follow my tutorials, take a look at those other projects in which I explain a little bit about internet of things, robotics and 3D printing. I hope you enjoy them too!

https://www.instructables.com/id/IoT-Wallet-smart...

https://www.instructables.com/id/IoT-Air-Freshner...

https://www.instructables.com/id/IoT-Wallet-smart...

https://www.instructables.com/id/3D-Printed-Artic...

Please consider supporting my future projects with a small donation! :D

_______________________________

Eu me esforcei bastante para deixar esse projeto o mais claro e educacional possível. Espero que tenha gostado e não se esqueça de curtir e compartilhar com seus amigos. Seu apoio é muito importante para que eu continue com esse trabalho! :D

Se você ainda não segue os meus tutoriais, dê uma olhada nesses outros projetos nos quais eu explico um pouco sobre internet das coisas, robótica e impressão 3D. Espero que curta eles tambem:

https://www.instructables.com/id/IoT-Wallet-smart....

https://www.instructables.com/id/IoT-Air-Freshner....

https://www.instructables.com/id/IoT-Wallet-smart....

https://www.instructables.com/id/3D-Printed-Artic....

Por favor considere financiar meus projetos futuros com uma pequna doação! :D

Pets Challenge

Participated in the
Pets Challenge