Manufaturação industrial
Internet das coisas industrial | Materiais industriais | Manutenção e reparo de equipamentos | Programação industrial |
home  MfgRobots >> Manufaturação industrial >  >> Manufacturing Technology >> Processo de manufatura

Notificador da data de lançamento do novo episódio de série de TV / anime

Componentes e suprimentos

PCB personalizado JLCPCB
× 1
Arduino Nano 33 IoT
× 1
Raspberry Pi 3 Modelo B
Raspberry Pi 3 ou Raspberry Pi 4
× 1
Raspberry Pi 4 Modelo B
Raspberry Pi 3 ou Raspberry Pi 4
× 1
Tela SparkFun Nokia 5110
× 1
Reprodutor de MP3 serial por OPEN-SMART
× 1
RGB Diffused Common Anode
× 1
Cartão de memória Flash, cartão SD
× 2
Resistor 220 ohm
× 12
Botão de pressão 6x6x5
× 4
TaydaElectronics DC POWER JACK 2.1MM MONTAGEM DE PCB TIPO BARRIL
× 1

Ferramentas e máquinas necessárias

Ferro de soldar (genérico)
Pistola de cola quente (genérica)

Aplicativos e serviços online

Arduino IDE
KiCad
Bloco de notas ++

Sobre este projeto





Descrição


Embora existam miríades de aplicativos da web e móveis para rastrear datas de lançamento de programas favoritos, eu queria criar um dispositivo que me notificasse quando um novo episódio de uma série ou anime em minha lista fosse lançado do zero - hardware e software - com vários recursos.

Em primeiro lugar, criei um aplicativo web - Rastreador de Data de Lançamento de Série de TV / Anime - em PHP para criar uma lista de séries / animes e reunir informações sobre as datas de lançamento. Nesse sentido, utilizei a API REST TVMAZE que permite ao aplicativo obter informações do episódio precisamente por data de lançamento, embora sem etapas de codificação diversas e complicadas. Em seguida, configurei um servidor LAMP (w / MariaDB) no Raspberry Pi para executar o aplicativo. Mas, para quem não tem um Raspberry Pi nem quer usar um como host, publiquei uma versão gratuita do aplicativo com interface amigável em meu site. Além disso, você pode encontrar o código-fonte do aplicativo abaixo.

Depois de cumprir a transferência de informações com o aplicativo web, se houver um novo episódio no lançamento, decidi usar um Arduino Nano 33 IoT como placa de desenvolvimento para coletar os dados gerados pelo aplicativo. Você pode encontrar mais informações abaixo sobre como classifiquei a resposta transferida pelo aplicativo usando um delimitador. E, para gerenciar recursos e modos que implementei no Nano 33 IoT, projetei uma interface de usuário (menu) com uma tela do Nokia 5110 e botões.

Por fim, para me informar quando um novo episódio de um programa da minha lista for lançado com sua música de abertura, usei um Módulo Serial MP3 Player (OPEN-SMART) devido à sua lista de comandos UART simples de usar. Além disso, permitiu-me adicionar o modo MP3 Player para tocar todas as músicas de abertura, o que transformou o dispositivo em um acessório intrigante para o meu quarto :)

Depois de concluir meu projeto em uma placa de ensaio e testar o código, projetei um PCB (Notificador de Data de Lançamento de Série de TV / Anime) com um formato de telefone retrô exclusivo para criar um dispositivo totalmente novo e fácil de usar.

Muito obrigado ao JLCPCB por patrocinar este projeto.






Etapa 1:Projetando e soldando a PCB do Notificador da Data de Lançamento da Série de TV / Anime


Eu projetei o Notificador de Data de Lançamento de Série de TV / Anime usando o KiCad. Anexei o arquivo Gerber do PCB abaixo, então se você quiser, pode solicitar este PCB do JLCPCB para replicar este projeto e ser notificado quando houver novos episódios de seus programas favoritos no lançamento :)



Em primeiro lugar, usando um ferro de soldar, conectei conectores, botões, resistores de 220Ω, o conector de força e LED RGB de ânodo de 5 mm.

Lista de componentes no PCB:

A1 (cabeçalhos para Arduino Nano 33 IoT)

J1 (cabeçalhos para MP3 player serial)

J2 (cabeçalhos para DS3231 - não obrigatório)

J3 (cabeçalhos para tela Nokia 5110)

J4 (Power Jack)

D1 (LED RGB ânodo 5 mm)

K1, K2, K3, K4 (botões de pressão)

R1, R2, R3, R4, R5, R6, R7, R8, R9, R10, R11, R12 (resistores de 220Ω)










Etapa 2:configurar um servidor da web LAMP com MariaDB no Raspberry Pi


Se você é um novato em programação com Raspberry Pi, você pode inspecionar instruções e tutoriais bem explicados no site oficial do Raspberry Pi.

Para ir para o tutorial oficial de configuração do Raspberry Pi, clique aqui.


  • Abra uma janela de terminal selecionando Acessórios> Terminal no menu.
  • Instale o pacote apache2 digitando o seguinte comando no terminal e pressionando Enter:

sudo apt-get install apache2 -y


  • Para testar o servidor, abra o Chromium selecionando Internet> Chromium Web Browser no menu e digite http:// localhost.
  • Se desejar, você também pode usar o endereço IP do seu Raspberry Pi.

hostname -I




  • Instale o pacote PHP com o seguinte comando:
  • Não se esqueça de atualizar o Pi.

sudo apt-get update

sudo apt-get install php -y


  • Instale o servidor MySQL (MariaDB) e os pacotes PHP-MySQL inserindo o seguinte comando na janela do terminal:

sudo apt-get install mariadb-server php-mysql -y


  • Para criar um novo usuário, execute o comando de instalação segura do MySQL na janela do terminal.

sudo mysql_secure_installation
  • Será solicitado que você digite a senha atual do root (digite nenhuma): - pressione Enter.
  • Digite Y e pressione Enter para Definir senha root .
  • Digite bot em Nova senha: prompt e pressione Enter.
  • Digite Y para Remover usuários anônimos .
  • Digite Y para Proibir login de root remotamente .
  • Digite Y para Remover banco de dados de teste e acesso a ele .
  • Digite Y para recarregar tabelas de privilégios agora .
  • Quando terminar, você verá esta mensagem - Tudo pronto! e obrigado por usar MariaDB!


  • Para criar um banco de dados (tvseries) para salvar as variáveis ​​geradas pela API REST TVMAZE, execute este comando MySQL na janela do terminal:

sudo mysql -uroot -p
  • Digite a senha de root - bot
  • Você será saudado pela mensagem Bem-vindo ao monitor MariaDB .
  • Siga as linhas abaixo após MariaDB [(nenhum)]> :prompt para criar a série de tv banco de dados em MariaDB:

criar séries de tv de banco de dados;

CONCEDE TODOS OS PRIVILÉGIOS NA tvseries. * TO 'root' @ 'localhost' IDENTIFICADO POR 'bot';

PRIVILÉGIOS DE FLUSH;
  • Saia do prompt do MariaDB com Ctrl + D.


  • Para obter dados da API REST TVMAZE simplesmente usando file_get_contents () função em PHP, instale o pacote php-curl:

sudo apt-get install php-curl


  • Em seguida, reinicie o servidor apache para poder usar os pacotes instalados no host local:

sudo service apache2 restart





Etapa 3:Obtendo informações da API REST TVMAZE sobre sua série / anime favorito


TVMAZE fornece uma API REST gratuita e fácil de usar, que permite aos usuários pesquisar programas por nome, data, número do episódio, etc. Você pode inspecionar os endpoints e consultas disponíveis:

Acesse TVMAZE REST API.



Usei o Episódio por Data opção de recuperar todos os episódios de um determinado programa que foi ao ar em uma data específica.

Para obter informações sobre as datas de lançamento, você precisa pesquisar seus programas favoritos no TVMAZE e usar o ID da TV indicado em seus links.
  • URL:/ shows /:id / episodesbydate? date =:date
  • Data:formato ISO 8601
  • Exemplo:http://api.tvmaze.com/shows/1/episodesbydate?date=2013-07-01



Se houver um episódio transmitido na data determinada, a API retorna uma matriz de informações completas do episódio.



Caso contrário, a API retornará um HTTP 404.



Abaixo, você pode inspecionar minha lista de séries / animes favoritos que criei para rastrear se há um novo episódio de um deles que está sendo lançado com meu projeto.

Eu adicionei The Late Late Show para testar meu código, pois é um programa diário.

1) One Piece

ID de TV: 1505

https://www.tvmaze.com/shows/1505/one-piece



2) My Hero Academia

ID da TV: 13615

https://www.tvmaze.com/shows/13615/boku-no-hero-academia



3) Westworld

ID da TV: 1371

https://www.tvmaze.com/shows/1371/westworld



4) Os Simpsons

ID de TV: 83

https://www.tvmaze.com/shows/83/the-simpsons



5) The Late Late Show com James Corden

ID da TV: 2831

https://www.tvmaze.com/shows/2831/the-late-late-show-with-james-corden






Etapa 4:desenvolvendo o rastreador de datas de lançamento de séries de TV / Anime (aplicativo) em execução no Raspberry Pi em PHP e criando a tabela de séries para inserir dados


Desenvolvi o Rastreador de Data de Lançamento de Série de TV / Anime em PHP e expliquei o código-fonte do aplicativo na seção Explicação do Código abaixo para os interessados.

No entanto, se você não gosta de desenvolvimento web com PHP, pode baixar o aplicativo em Downloads - chamado TV-Series-Anime-Episode-Tracker.zip - e carregá-lo no Raspberry Pi sem mergulhar na codificação PHP.

Upload :

Seguindo as etapas a seguir, instale o Rastreador de Data de Lançamento de Série de TV / Anime no host local:
  • Baixe o aplicativo - TV-Series-Anime-Episode-Tracker.zip - incluindo os arquivos index.php e query.php.


  • Extraia o TV-Series-Anime-Episode-Tracker.zip.


  • Mova a pasta do aplicativo (TV-Series-Anime-Episode-Tracker) de Downloads para o servidor (/ var / www / html) usando o terminal, pois o servidor apache é um local protegido.

sudo mv / home / pi / Downloads / TV-Series-Anime-Episode-Tracker / / var / www / html /


  • Vá para o Rastreador de datas de lançamento de séries de TV / anime:

http:// localhost / TV-Series-Anime-Episode-Tracker /

Recursos :

1) Após a instalação, abra o aplicativo para criar uma tabela chamada série no banco de dados (tvseries). Quando você abre o arquivo index.php pela primeira vez, o aplicativo cria a tabela chamada série automaticamente e informa ao usuário - Tabela do banco de dados criada!



2) Se a tabela (série) do banco de dados for criada com sucesso no banco de dados, o aplicativo informa ao usuário - Tabela do banco de dados encontrada!



3) Depois de criar a tabela de banco de dados (série), para inserir as variáveis ​​necessárias para a API REST TVMAZE para cada programa em sua lista, execute as seguintes etapas:
  • Execute este comando MySQL na janela do terminal:

sudo mysql -uroot -p
  • Digite a senha de root - bot
  • Selecione a série de tv banco de dados:

USE séries de tv;
  • Insira as variáveis ​​necessárias - nome da série, ID de TV, status - na tabela para cada programa. A variável de status é usada pelo aplicativo para notificar o usuário sem se repetir quando um novo episódio for lançado em uma determinada data.

INSERT INTO `series` (` series_name`, `tv_id`,` status`) VALUES ('One Piece', '1505', 'Pending');



5) No query.php, o aplicativo faz solicitações à API TVMAZE REST para detectar se novos episódios de programas no banco de dados estão em lançamento. Se TVMAZE REST API retornar uma matriz de informações completas do episódio de um episódio lançado, o aplicativo imprime informações agrupáveis ​​pelo Arduino Nano 33 IoT uma vez para evitar uma recorrência.

http://localhost/TV-Series-Anime-Episode-Tracker/query.php

% Series_Name% temporada% Episode_Number% Episode_Name%

% The Late Show% 2020% 91% Jason Schwartzman, Alicia Key%



6) Caso contrário, o aplicativo imprimirá Nenhuma entrada encontrada!



Explicação do código :

1) index.php
  • Defina as configurações de conexão do banco de dados - "localhost", "root", "bot", "tvseries".
  • No checkDatabase () função, detecte se há uma tabela de banco de dados com o nome dado - série.
  • Na createTable () função, crie a tabela série se não for encontrada no banco de dados e informe ao usuário.



2) query.php
  • Na consulta classe, defina o caminho para TVMAZE API para fazer solicitações.
  • No define_user () função, obtenha as configurações de conexão e o nome da tabela.
  • Na check_ep_release_date () função, usando file_get_contents () , detecte se um novo episódio está sendo lançado para um determinado ID de TV na data atual. Altere a variável de status no banco de dados de Pendente para Lançado se um novo episódio estiver no lançamento para evitar uma recorrência.
  • No track_db_entries () função, execute o check_ep_release_date () para cada show registrado na tabela de banco de dados - série.








Etapa 4.1:Execução de aplicativo da web sem Raspberry Pi


Para assinantes do meu site (TheAmplituhedron), desenvolvi uma versão gratuita do Rastreador de Data de Lançamento de Série de TV / Anime para quem não tem um Raspberry Pi e nem deseja usar um como hospedeiro para este projeto.

Ele fornece uma interface amigável para gerenciar o banco de dados. Se você deseja usar esta interface com seu projeto em vez de usar o terminal no Raspberry Pi para inserir dados, entre em contato comigo.

Vá para o aplicativo:

https://www.theamplituhedron.com/dashboard/TV-Series-Anime-Episode-Tracker/






Etapa 5:Configurando o Arduino Nano 33 IoT


Se você é um novato em programação com Arduino Nano 33 IoT:não se preocupe, é simples de usar com Arduino IDE. Basta baixar os drivers necessários - Arduino SAMD Core - conforme explicado aqui.



Para poder se conectar ao WiFi via Arduino Nano 33 IoT, baixe a biblioteca WiFiNINA aqui.



Para imprimir texto e desenhar gráficos na tela do Nokia 5110, baixe a biblioteca LCD5110_Basic aqui.

Usei a segunda porta serial (Serial1) no Arduino Nano 33 IoT para me comunicar com o Serial MP3 Player.

Portas seriais no Arduino Nano 33 IoT :

"O conector USB da placa é conectado diretamente aos pinos do host USB do SAMD21. Este roteamento permite que você use o Arduino NANO 33 IoT como um periférico USB cliente (atuando como um mouse ou teclado conectado ao computador ) ou como um dispositivo host USB para que dispositivos como mouse, teclado ou telefone Android possam ser conectados ao Arduino NANO 33 IoT. Essa porta também pode ser usada como uma porta serial virtual usando o objeto Serial na linguagem de programação do Arduino . Os pinos RX0 e TX1 são uma segunda porta serial disponível como Serial1. "

Então, o Arduino Nano 33 IoT está pronto para executar o código do projeto :)





Etapa 6:Envio de comandos para o Serial MP3 Player (OPEN-SMART)


Eu criei uma lista de reprodução que consiste em músicas de abertura da minha lista de séries / animes favoritos neste projeto:

1) One Piece - Abertura | Ouvir

2) My Hero Academia - Abertura | Ouvir

3) Westworld - Abertura | Ouvir

4) Os Simpsons - Abertura | Ouvir

5) The Late Late Show - Abertura | Ouvir

Se desejar, você pode baixar minha lista de reprodução em uma pasta compactada - abrindo_songs.zip.

É fácil usar um Serial MP3 Player com Arduino Nano 33 IoT, desde que você conheça os comandos UART necessários para acionar as funções corretas. Usei um módulo Serial MP3 Player com alto-falante da OPEN-SMART. Portanto, se você tiver um Serial MP3 Player com uma marca diferente, os comandos mostrados a seguir não funcionarão para você.

Siga as instruções da orientação:

"O módulo é um tipo de dispositivo reprodutor de MP3 simples baseado em um chip de áudio MP3 de alta qualidade. Ele pode suportar formatos de arquivo MP3 e WAV de frequência de amostragem de 8k Hz ~ 48k Hz. Há um soquete para cartão TF integrado , para que você possa conectar o cartão micro SD que armazena arquivos de áudio. O MCU pode controlar o estado de reprodução de MP3 enviando comandos para o módulo por meio da porta UART, como alternar músicas, alterar o volume e o modo de reprodução e assim por diante. Você também pode depurar o módulo via USB para o módulo UART. É compatível com Arduino / AVR / ARM / PIC. "

"Certifique-se de que seu cartão micro SD está formatado como FAT16 ou FAT32 e de que haja algumas músicas nele. Você deve criar as pastas“ 01 ”e“ 02 ”e colocar algumas músicas com o nome 001xxx.mp3 / 002xxx.mp3 / 003xxx.mp3 neles. "

Em outras palavras, para poder executar comandos com precisão, salve suas músicas em uma pasta chamada '01' e adicione números consecutivos aos nomes das músicas - 001One Piece-Opening.mp3, 002My Hero Academia-Opening.mp3, etc.



Para enviar comandos UART para o Serial MP3 Player com Arduino Nano 33 IoT, criei uma função chamada send_command_to_MP3_player . Ele transfere cada byte no comando solicitado para o Serial MP3 Player através da segunda porta serial nos pinos RX0 e TX1 - Serial1 - dependendo do comprimento do comando solicitado - 4, 5 ou 6.

Conforme mostrado abaixo, separe o comando que deseja enviar para o Serial MP3 Player por bytes - 0x7e. Todos os comandos começam com '7E' e terminam com 'EF'. O segundo byte é o número de bytes entre - '02', '03', '04'. Abaixo, baixe o manual do Serial MP3 Player da OPEN-SMART para inspecionar todos os comandos e obter instruções mais detalhadas.
  // Defina os comandos do MP3 Player necessários. 
// Você pode inspecionar todos os comandos fornecidos na página do projeto:
// Selecione o dispositivo de armazenamento para o cartão TF
static int8_t select_SD_card [] ={0x7e, 0x03, 0X35, 0x01, 0xef}; // 7E 03 35 01 EF
// Toca a música com o diretório:/01/001xxx.mp3
static int8_t play_song_1 [] ={0x7e, 0x04, 0x41, 0x00, 0x01, 0xef}; // 7E 04 41 00 01 EF
// Toque a música com o diretório:/01/002xxx.mp3
static int8_t play_song_2 [] ={0x7e, 0x04, 0x41, 0x00, 0x02, 0xef}; // 7E 04 41 00 02 EF
// Toque a música com o diretório:/01/003xxx.mp3
static int8_t play_song_3 [] ={0x7e, 0x04, 0x41, 0x00, 0x03, 0xef}; // 7E 04 41 00 03 EF
// Toque a música com o diretório:/01/004xxx.mp3
static int8_t play_song_4 [] ={0x7e, 0x04, 0x41, 0x00, 0x04, 0xef}; // 7E 04 41 00 04 EF
// Toque a música com o diretório:/01/005xxx.mp3
static int8_t play_song_5 [] ={0x7e, 0x04, 0x41, 0x00, 0x05, 0xef}; // 7E 04 41 00 05 EF
// Toca a música.
static int8_t play [] ={0x7e, 0x02, 0x01, 0xef}; // 7E 02 01 EF
// Pausa a música.
static int8_t pause [] ={0x7e, 0x02, 0x02, 0xef}; // 7E 02 02 EF
// Próxima música.
static int8_t next_song [] ={0x7e, 0x02, 0x03, 0xef}; // 7E 02 03 EF
// Música anterior.
static int8_t previous_song [] ={0x7e, 0x02, 0x04, 0xef}; // 7E 02 04 EF






Etapa 7:Programação do Arduino Nano 33 IoT

  • Inclua as bibliotecas necessárias.
  • Defina suas configurações de WiFi - SSID e senha.
  • Digite o endereço IP do seu Raspberry Pi.
  • Defina o caminho do aplicativo (query.php) no Raspberry Pi.
  • Inicialize a biblioteca cliente Ethernet.
  • Defina as configurações de tela do Nokia 5110.
  • Defina os gráficos para os modos de tela relacionados - tv e música.
  • Para criar gráficos diferentes (imagens monocromáticas), vá para Conversor de imagens monocromáticas.
  • Defina os comandos do reprodutor de MP3 necessários.
  • Definir opções e modos de menu usando booleanos voláteis.
  • Defina os botões de controle e pinos de LED RGB.
  • Inicie a comunicação serial para o Módulo Serial MP3 Player na segunda porta serial - Serial1 .
  • Conecte-se à rede WiFi.
  • Verifique a conexão no monitor serial e no Nokia 5110 Screen.
  • No read_buttons () função, obtenha dados dos botões de controle - Direita, OK, Esquerda e Sair.
  • Em change_menu_options () , aumente ou diminua o número da opção usando os botões direito e esquerdo.
  • Na interface () função, imprima a interface (menu).
  • Se o Init Tracker modo estiver selecionado, conecte-se ao aplicativo da web denominado TV Series / Anime Release Date Tracker.
  • Se houver bytes de entrada disponíveis, obtenha a resposta do aplicativo da web.
  • Usando o endsWith () , detecte se a resposta contém o símbolo de porcentagem (delimitador) ou não.
  • Se incluído, divida a string de resposta por um delimitador predefinido de maneira simples. '%' (porcentagem) é definido como o delimitador neste projeto.
  • Colete informações como substrings - Series_Name, Season, Episode, Episode_Name.
  • Imprima as informações e toque a música de abertura da série / anime lançada até o fim.
  • Espere até que o botão Sair seja pressionado.
  • Se houver uma resposta em branco, imprima Nenhum episódio liberado detectado :(
  • Desenhe o ícone da TV enquanto conta para a nova solicitação.
  • Espere até a próxima solicitação.
  • Se o modo MP3 Player estiver selecionado, desenhe o ícone do reprodutor de música. Controle o MP3 Player com os botões de controle - Direita, Esquerda, OK.
  • Se o modo de suspensão for selecionado, ative o modo de espera em 10 segundos e imprima os segundos restantes.


















Conexões e ajustes

// Connections
// Arduino Nano 33 IoT:
// Nokia 5110 Screen
// D2 -------------------------- SCK (Clk)
// D3 -------------------------- MOSI (Din)
// D4 -------------------------- DC
// D5 -------------------------- RST
// D6 -------------------------- CS (CE)
// RGB
// D9 -------------------------- R
// D10 -------------------------- G
// D11 -------------------------- B
// LEFT_BUTTON
// A0 --------------------------- S
// OK_BUTTON
// A1 --------------------------- S
// RIGHT_BUTTON
// A2 --------------------------- S
// EXIT_BUTTON
// A3 --------------------------- S
// DS3231 (Optional for Nano and Not Required for Nano 33 IoT)
// A4 --------------------------- SDA
// A5 --------------------------- SCL

After finishing and uploading the code to the Arduino Nano 33 IoT, I attached all required components to the board via headers.

I also provided a connection slot for a DS3231 RTC Module for those who want to change the Arduino Nano 33 IoT with the Arduino Nano. But, you need to enter release dates manually for each show to the Arduino Nano without being able to obtain data from the web application to create a countdown timer with the RTC.



Note:You can connect either a speaker or headphones to the Serial MP3 Player to listen to soundtracks in the playlist. I connected the speaker delivered in addition to the Serial MP3 Player (OPEN-SMART).








Modes and Features


1) While the device tries to connect to the WiFi network, it displays Waiting... Attempting to connect to WiFi .



2) After establishing a successful connection, the device informs the user with this message - Connected to WiFi!!!



3) Then, the device prints the interface (menu) presenting available modes - A.Init Tracker, B.MP3 Player , and C.Sleep . To switch among modes, use the Right and Left buttons. Subsequently, press the OK button to select a mode.



A.Init Tracker

A.1) After selecting the A.Init Tracker mode, the device attempts to connect to the localhost hosted by the Raspberry Pi. If successful, it informs the user with this message - Connected to the server!!! Conversely, the device displays this message - Connection Error!!!





A.2) If the application (TV Series / Anime Release Date Tracker) sends a data string that of a released episode of a registered series/anime in the database, then the device:
  • Prints the episode information - Series Name, Season, Episode Number, and Episode Name:

One Piece, 10x54, Luffy's Determination
  • Plays the opening song of the released series/anime,
  • And, turns the RGB to the color assigned to the released series/anime.

For instance, I assigned these colors below for each show in my list:
  • One Piece -> Red
  • My Hero Academia -> Green
  • Westworld -> Blue
  • The Simpsons -> Yellow
  • The Late Late Show -> Purple

Unless the Exit button is pressed, the device keeps displaying the episode information and showing the assigned color.

The device notifies the user for once for each released episode to prevent any recurrence.



A.3) After the Exit button is pressed, the device draws the television icon while waiting for the next request to the application.



A.4) If there is no released episode of a registered series/anime in the database, the device displays this message - No Released Episode Detected :( - and then; draws the television icon until the next request to the application.





A.5) The device returns to the interface (menu) if the Exit button is pressed while displaying the television icon.

B. MP3 Player

I implemented this feature as a subsidiary and fun one to turn this device into an intriguing accessory for my room.

B.1) After selecting the B.MP3 Player mode, the device draws the music note icon and lets the user play all opening songs by using the control buttons:
  • Right - Next Song
  • Left - Previous Song
  • OK - Pause

B.2) The device returns to the interface (menu) if the Exit button is pressed.





C.Sleep

C.1) After selecting the C.Sleep mode, the device enables the sleep mode in 10 seconds and prints the remaining seconds on the screen.





C.2) While maintaining the sleep mode, the device applies a given color pattern to the RGB as a nightlight.





C.3) The device returns to the interface (menu) if the Exit button is pressed.





Videos and Conclusion




After completing all steps above, I decided to fasten the device to my bookcase by using a hot glue gun. It works stupendously :)






Código

  • Series_Release_Date_Notifier.ino
  • index.php
  • query.php
Series_Release_Date_Notifier.inoArduino
 //////////////////////////////////////////////////// // TV Series / Anime New Episode // // Release Date Notifier // // ------------------------- // // Arduino Nano 33 IoT // // by Kutluhan Aktar // // // ////////////////////////////////////////////////////// Get informed when new episodes of your favorite shows are on release with their opening songs via Nano 33 IoT and Raspberry Pi. //// I developed a corroborating web application in PHP for this project, named TV Series / Anime Release Date Tracker. // You can either use a Raspberry Pi as the server, explained in the project tutorial, or TheAmplituhedron with the real-time database interface if you are a member. //// For more information:// https://www.theamplituhedron.com/projects/TV-Series-Anime-New-Episode-Release-Date-Notifier/// // You can use the mentioned web application in free version on TheAmplituhedron as the host server if you are a subscriber:// https://www.theamplituhedron.com/dashboard/TV-Series-Anime-Episode-Tracker///// Connections// Arduino Nano 33 IoT:// Nokia 5110 Screen// D2 --------------------------- SCK (Clk)// D3 --------------------------- MOSI (Din) // D4 --------------------------- DC // D5 --------------------------- RST// D6 --------------------------- CS (CE)// RGB// D9 --------------------------- R// D10 --------------------------- G// D11 --------------------------- B// LEFT_BUTTON// A0 --------------------------- S// OK_BUTTON// A1 --------------------------- S// RIGHT_BUTTON// A2 ---------- ----------------- S// EXIT_BUTTON// A3 --------------------------- S// DS3231 (Optional for Nano and Not Required for Nano 33 IoT)// A4 --------------------------- SDA // A5 --------------------------- SCL// Include required libraries:#include #include #include char ssid[] ="[_SSID_]"; // your network SSID (name)char pass[] ="[_PASSWORD_]"; // your network password (use for WPA, or use as key for WEP)int keyIndex =0; // your network key Index number (needed only for WEP)int status =WL_IDLE_STATUS;// Note:Uncomment equivalent connection settings provided under related lines for using the web application hosted on TheAmplituhedron if you are a subscriber.// Enter the IPAddress of your Raspberry Pi.IPAddress server(192, 168, 1, 22);/* // name address for TheAmplituhedron. Change it with your server if you are using a different host server than TheAmplituhedron.char server[] ="www.theamplituhedron.com";*/// Define the pathway of the application in Raspberry Pi.String application ="/TV-Series-Anime-Episode-Tracker/query.php";/*// Define your hedron if you are using TheAmplituhedron as the host server for this project:String HEDRON ="[_HEDRON_]";// Define the pathway of the web application. If you are using TheAmplituhedron as the host server for this project as I did, just enter your hedron. Otherwise, enter the pathway on your server.String application ="/dashboard/TV-Series-Anime-Episode-Tracker/" + HEDRON;*/// Initialize the Ethernet client libraryWiFiClient client;/* WiFiSSLClient client; */// Define screen settings.LCD5110 myGLCD(2,3,4,5,6);extern uint8_t SmallFont[];extern uint8_t MediumNumbers[];// Define the graphics for related screen modes.extern uint8_t tv[];extern uint8_t music[];// Define the required MP3 Player Commands.// You can inspect all given commands from the project page:// Select storage device to TF cardstatic int8_t select_SD_card[] ={0x7e, 0x03, 0X35, 0x01, 0xef}; // 7E 03 35 01 EF// Play the song with the directory:/01/001xxx.mp3static int8_t play_song_1[] ={0x7e, 0x04, 0x41, 0x00, 0x01, 0xef}; // 7E 04 41 00 01 EF// Play the song with the directory:/01/002xxx.mp3static int8_t play_song_2[] ={0x7e, 0x04, 0x41, 0x00, 0x02, 0xef}; // 7E 04 41 00 02 EF// Play the song with the directory:/01/003xxx.mp3static int8_t play_song_3[] ={0x7e, 0x04, 0x41, 0x00, 0x03, 0xef}; // 7E 04 41 00 03 EF// Play the song with the directory:/01/004xxx.mp3static int8_t play_song_4[] ={0x7e, 0x04, 0x41, 0x00, 0x04, 0xef}; // 7E 04 41 00 04 EF// Play the song with the directory:/01/005xxx.mp3static int8_t play_song_5[] ={0x7e, 0x04, 0x41, 0x00, 0x05, 0xef}; // 7E 04 41 00 05 EF// Play the song.static int8_t play[] ={0x7e, 0x02, 0x01, 0xef}; // 7E 02 01 EF// Pause the song.static int8_t pause[] ={0x7e, 0x02, 0x02, 0xef}; // 7E 02 02 EF// Next song.static int8_t next_song[] ={0x7e, 0x02, 0x03, 0xef}; // 7E 02 03 EF// Previous song.static int8_t previous_song[] ={0x7e, 0x02, 0x04, 0xef}; // 7E 02 04 EF// Define menu options and modes using volatile booleans.volatile boolean TV =false;volatile boolean Music =false;volatile boolean Sleep =false;volatile boolean Activated =false;// Define the control buttons.#define B_Exit A3#define B_Right A2#define B_OK A1#define B_Left A0// Define RGB LED pins.#define redPin 9#define greenPin 10#define bluePin 11// Define data holders:int Right, OK, Left, Exit;int selected =0;void setup() { // Buttons:pinMode(B_Exit, INPUT); pinMode(B_Right, INPUT); pinMode(B_OK, INPUT); pinMode(B_Left, INPUT); // RGB:pinMode(redPin, OUTPUT); pinMode(greenPin, OUTPUT); pinMode(bluePin, OUTPUT); adjustColor(0, 0, 0); // Black // Initiate screen. myGLCD.InitLCD(); myGLCD.setFont(SmallFont); Serial.begin (9600); // Initiate serial communication for the Serial MP3 Player Module. Serial1.begin(9600); // Select the SD Card. send_command_to_MP3_player(select_SD_card, 5); // check for the WiFi module:if (WiFi.status() ==WL_NO_MODULE) { Serial.println("Communication with WiFi module failed!"); myGLCD.print("Connection Failed!", 0, 8); while (true); } // attempt to connect to Wifi network:while (status !=WL_CONNECTED) { Serial.print("Attempting to connect to SSID:"); Serial.println(ssid); myGLCD.print("Waiting...", 0, 8); myGLCD.print("Attempting to", 0, 16); myGLCD.print("connect to", 0, 24); myGLCD.print("WiFi !!!", 0, 32); // Connect to WPA/WPA2 network. Change this line if using open or WEP network:status =WiFi.begin(ssid, pass); // wait 10 seconds for connection:delay(10000); } // Verify connection on both the serial monitor and Nokia 5110 Screen. Serial.println("Connected to wifi"); myGLCD.clrScr(); myGLCD.print("Connected to", 0, 8); myGLCD.print("WiFi!!!", 0, 16); delay(2000); myGLCD.clrScr();}void loop() { read_buttons(); change_menu_options(); interface(); if(TV ==true){ do{ myGLCD.invertText(true); myGLCD.print("A.Init Tracker", 0, 16); myGLCD.invertText(false); atraso (100); if(OK ==HIGH){ myGLCD.clrScr(); Activated =true; while(Activated ==true){ // Connect to the web application named TV Series / Anime Release Date Tracker. Change '80' with '443' if you are using TheAmplituhedron as the host. if (client.connect(server, 80)) { Serial.println("connected to server"); // if you get a connection, report back via serial:myGLCD.print("Connected to", 0, 8); myGLCD.print("the server!!!", 0, 16); // Make an HTTP request:client.println("GET " + application + " HTTP/1.1"); //client.println("Host:www.theamplituhedron.com"); client.println("Host:192.168.1.22"); client.println("Connection:close"); client.println(); }else{ myGLCD.print("Connection", 0, 8); myGLCD.print("Error!!!", 0, 16); } delay(2000); // Wait 2 seconds after connection... // If there are incoming bytes available, get the response from the web application. String response =""; while (client.available()) { char c =client.read(); response +=c; } if(response !="" &&response.endsWith("%")){ // Split the response string by a pre-defined delimiter in a simple way. '%'(percentage) is defined as the delimiter in this project. int delimiter, delimiter_1, delimiter_2, delimiter_3, delimiter_4; delimiter =response.indexOf("%"); delimiter_1 =response.indexOf("%", delimiter + 1); delimiter_2 =response.indexOf("%", delimiter_1 +1); delimiter_3 =response.indexOf("%", delimiter_2 +1); delimiter_4 =response.indexOf("%", delimiter_3 +1); // Glean information as substrings. String Series_Name =response.substring(delimiter + 1, delimiter_1); String Season =response.substring(delimiter_1 + 1, delimiter_2); String Episode =response.substring(delimiter_2 + 1, delimiter_3); String Episode_Name =response.substring(delimiter_3 + 1, delimiter_4); // Print information. myGLCD.clrScr(); myGLCD.print(Series_Name, 0, 0); myGLCD.print(Season + " x " + Episode, 0, 16); myGLCD.print(Episode_Name, 0, 32); // Play the opening song of the released series / anime until ceased:if(Series_Name =="One Piece") { send_command_to_MP3_player(play_song_1, 6); adjustColor(255,0,0); } if(Series_Name =="My Hero Academia") { send_command_to_MP3_player(play_song_2, 6); adjustColor(0,255,0); } if(Series_Name =="Westworld") { send_command_to_MP3_player(play_song_3, 6); adjustColor(0,0,255); } if(Series_Name =="The Simpsons") { send_command_to_MP3_player(play_song_4, 6); adjustColor(255,255,0); } if(Series_Name =="The Late Late Show") { send_command_to_MP3_player(play_song_5, 6); adjustColor(80,0,80); } // Wait until the Exit button pressed... volatile boolean song =true; while(song ==true){ read_buttons(); if(Exit ==HIGH){ song =false; send_command_to_MP3_player(pause, 4); adjustColor(0,0,0); } } myGLCD.clrScr(); }else{ // Print information. myGLCD.clrScr(); myGLCD.print("No Released", 0, 0); myGLCD.print("Episode", 0, 16); myGLCD.print("Detected :(", 0, 32); delay(5000); // Wait 5 seconds to display information... myGLCD.clrScr(); } // Draw TV icon while counting to the new request... myGLCD.drawBitmap(8, 0, tv, 60, 48); delay(10 * 1000); // Wait until next request... myGLCD.clrScr(); // Exit. read_buttons(); if(Exit ==HIGH){ Activated =false; myGLCD.clrScr(); } } } }while(TV ==false); } if(Music ==true){ do{ myGLCD.invertText(true); myGLCD.print("B.MP3 Player", 0, 24); myGLCD.invertText(false); delay(100); if(OK ==HIGH){ myGLCD.clrScr(); Activated =true; while(Activated ==true){ read_buttons(); // Draw music player icon. myGLCD.drawBitmap(8, 0, music, 60, 48); // MP3 Player:if(Right ==true) send_command_to_MP3_player(next_song, 4); if(Left ==true) send_command_to_MP3_player(previous_song, 4); if(OK ==true) send_command_to_MP3_player(pause, 4); // Exit. if(Exit ==HIGH){ Activated =false; myGLCD.clrScr(); send_command_to_MP3_player(pause, 4); } } } }while(Music ==false); } if(Sleep ==true){ do{ myGLCD.invertText(true); myGLCD.print("C.Sleep", 0, 32); myGLCD.invertText(false); atraso (100); if(OK ==HIGH){ // Activate the sleep mode in 10 seconds. myGLCD.clrScr(); myGLCD.print("Entering", CENTER, 0); myGLCD.print("Sleep Mode", CENTER, 8); myGLCD.print("in", CENTER, 16); myGLCD.print("Seconds", CENTER, 40); // Print remaining seconds. myGLCD.setFont(MediumNumbers); for (int s=10; s>=0; s--){ myGLCD.printNumI(s, CENTER, 24, 2, '0'); atraso (1000); } myGLCD.enableSleep(); Activated =true; while(Activated ==true){ // Color Pattern:adjustColor(255,0,0); atraso (500); adjustColor(0,255,0); atraso (500); adjustColor(0,0,255); atraso (500); adjustColor(255,255,0); atraso (500); adjustColor(80,0,80); atraso (500); // Exit. read_buttons(); if(Exit ==HIGH){ Activated =false; myGLCD.clrScr(); myGLCD.disableSleep(); myGLCD.setFont(SmallFont); adjustColor(0,0,0); } } } }while(Sleep ==false); }}void read_buttons(){ // Read the control buttons:Right =digitalRead(B_Right); OK =digitalRead(B_OK); Left =digitalRead(B_Left); Exit =digitalRead(B_Exit);}void send_command_to_MP3_player(int8_t command[], int len){ Serial.print("\nMP3 Command => "); for(int i=0;i 3) selected =1; atraso (100); // Depending on the selected option number, change boolean status. switch(selected){ case 1:TV =true; Music =false; Sleep =false; pausa; case 2:TV =false; Music =true; Sleep =false; pausa; case 3:TV =false; Music =false; Sleep =true; pausa; }}void adjustColor(int red, int green, int blue){ red =255 - red; green =255 - green; blue =255 - blue; analogWrite(redPin, red); analogWrite(greenPin, green); analogWrite(bluePin, blue);}
index.phpPHP
 0) ? true :false;}function createTable($table_name, $conn){ if(!checkDatabase($table_name, $conn)){ $sql ="CREATE TABLE `$table_name`( id int(11) AUTO_INCREMENT PRIMARY KEY NOT NULL, series_name varchar(255) NOT NULL, tv_id varchar(255) NOT NULL, status varchar(255) NOT NULL );"; if(mysqli_query($conn, $sql)){ echo "Database Table Created!"; }else{ echo "Error!"; } }else{ echo "Database Table Found!"; }}createTable("series", $conn_database);?>
query.phpPHP
conn =$conn; $this->table_name =$table_name; } private function check_ep_release_date($API_ID, $series_name, $status){ $date =date("Y-m-d"); $URL =self::ROOT.$API_ID.self::PATH.$date; if($get_content =json_decode(file_get_contents((String)$URL))){ if($status !="Released"){ echo "%".$series_name."%".$get_content[0]->season."%".$get_content[0]->number."%".$get_content[0]->name."%"; $sql ="UPDATE `$this->table_name` SET `status`='Released' WHERE series_name='$series_name'"; mysqli_query($this->conn, $sql); } }else{ if($status !="Pending"){ $sql ="UPDATE `$this->table_name` SET `status`='Pending' WHERE series_name='$series_name'"; mysqli_query($this->conn, $sql); } } } public function track_db_entries(){ $sql ="SELECT * FROM `$this->table_name` ORDER BY `id` DESC"; if($result =mysqli_query($this->conn, $sql)){ $check =mysqli_num_rows($result); if($check> 0){ while($row =mysqli_fetch_assoc($result)){ $this->check_ep_release_date($row['tv_id'], $row['series_name'], $row['status']); } }else{ echo "No Entry Found!"; } }else{ echo "No Database Found!"; } }}// Define the connection settings and the table name.$conn_database =mysqli_connect("localhost", "root", "bot", "tvseries");$table ="series";// Define the object to check release date for each registered series / anime.$q =new query();$q->define_user($conn_database, $table);$q->track_db_entries();?>

Peças personalizadas e gabinetes

gerber_ycEfXzZq6h.zip tv-series-anime-episode-tracker_gCfN0nFiA8.zip opening_songs_y2LCEw79tg.zip tv_Iz2isO8nGI.c music_SA2xR86cZw.c

Esquemas


Processo de manufatura

  1. Controle remoto universal Raspberry Pi
  2. Uma fatia de Raspberry Pi
  3. Cycle Chaser
  4. Detector de ladrão Raspberry Pi
  5. Sensor de temperatura Raspberry Pi
  6. RASPBERRY PI HOME AUTOMATION
  7. NOVO FRAMBOESA PI 3 MODELO B + RECURSOS E COMPRA
  8. Robô da caixa de CD do Raspberry Pi
  9. Placa RaspiRobot V2
  10. Rover