Player MP3 e Relógio Despertador com Touch Screen Arduino – Guia Passo a Passo
Neste projeto, mostrarei como você pode fazer um Player de Música MP3 com Touch Screen Arduino e Relógio Despertador. Você pode assistir ao vídeo a seguir ou ler o tutorial escrito abaixo.
Visão Geral
A tela inicial apresenta um grande relógio, data e informações de temperatura, bem como dois botões para o Player de Música e o Relógio Despertador.

Se entrarmos no Player de Música, podemos começar a tocar a música pressionando o grande botão "Play" no meio da tela. Ao lado dele, há mais dois botões, para tocar a música anterior ou a próxima.

Acima destes botões, há a barra de progresso da música, e na parte inferior da tela temos uma barra de volume e dois botões para diminuir e aumentar o volume. No canto superior direito, há um relógio e no lado esquerdo está o botão "Menu" que nos leva de volta à tela inicial.
Por outro lado, se entrarmos no Relógio Despertador, podemos definir um alarme usando os dois botões para definir as horas e os minutos.

Quando o alarme for ativado, uma música começará a tocar em volume mais alto e continuará tocando até pressionarmos o botão "Dismiss" (Dispensar).

Como Funciona
Agora, vamos ver como este dispositivo funciona. Ele usa uma placa Arduino Mega e uma tela touch TFT de 3.2" com um shield adequado para conectar a tela à placa Arduino. Para tocar a música, usa o módulo MP3 Player BY8001 e para o relógio despertador usa o módulo Real Time Clock DS3231.

Você pode obter os componentes necessários para este Projeto Arduino nos links abaixo:
- Módulo MP3 BY8001-16P
- Display Touch TFT 3.2"
- Shield TFT Display Mega
- Alto-falante 0.5W
- Real Time Clock DS3231
- Arduino Mega
Esquemáticos do Circuito
Aqui está o esquemático do circuito deste projeto:

Podemos notar aqui que o shield TFT está bloqueando os pinos livres da placa Arduino, então precisamos fazer headers de pinos personalizados que poderemos inserir entre o shield e o Arduino.

Também note que, para alimentar o Arduino, precisamos soldar um header de pinos adicional ao pino 5V no shield, pois o shield já usa todos os pinos VCC do Arduino.
Uma vez conectado tudo, podemos prosseguir com a programação do Arduino. No entanto, antes de continuar, gostaria de sugerir que você confira meus tutoriais detalhados anteriores para a tela touch TFT e o módulo Real Time Clock DS3231. E quanto ao módulo MP3 Player, darei uma explicação rápida aqui neste artigo.
Módulo MP3 Player BY8001-16P
O BY8001-16P é um módulo MP3 que funciona com cartões MicroSD e suporta arquivos de áudio nos formatos MP3 e WAV. O módulo tem um amplificador de potência de 3W embutido e pode acionar diretamente um único alto-falante de 3W.

O módulo MP3 Player pode ser controlado por botões usando os 5 pinos de entrada ou usando um microcontrolador via comunicação serial.

Note aqui que os pinos da porta serial do módulo funcionam a 3.3V, então o pino RX do módulo precisa ser conectado através de um resistor de 1K ao pino TX do Arduino. Note também as 3 portas A, B e C que são usadas para selecionar os modos de controle. Para controlar o módulo usando um microcontrolador, os 3 resistores nestes pads precisam ser removidos. Os pinos número 6 e 7 podem ser usados para conectar diretamente alto-falantes de baixa potência ou os pinos 4 e 5 se usando amplificador externo.
Quanto à parte Arduino, a maneira mais fácil é usar a biblioteca BY8001 que pode ser baixada do GitHub. Se abrirmos alguns de seus exemplos de demonstração, podemos ver como funciona. Então, após inicializar o módulo na seção setup, podemos usar qualquer uma das funções personalizadas para controlar o módulo.
Código Fonte
Agora, estamos prontos para ver o código deste Player de Música MP3 com Touch Screen Arduino e Relógio Despertador. Como o código é um pouco longo, para melhor entendimento, postarei o código fonte do programa em seções com descrição para cada seção. E no final deste artigo, postarei o código fonte completo.
Então, primeiro precisamos incluir as bibliotecas para a tela touch TFT, o MP3 Player BY8001-16P e o módulo Real Time Clock DS3231, bem como a biblioteca para comunicação serial. Então, temos que criar os objetos apropriados e definir algumas variáveis necessárias para o programa.
#include <UTFT.h>
#include <URTouch.h>
#include <SoftwareSerial.h>
#include <BY8001.h>
#include <DS3231.h>
//==== Criando Objetos
UTFT myGLCD(SSD1289, 38, 39, 40, 41); // Parâmetros devem ser ajustados ao seu modelo de Display/Shield
URTouch myTouch(6, 5, 4, 3, 2);
SoftwareSerial mp3Serial(11, 10); // RX, TX
BY8001 mp3; // criando instância da classe BY8001 e chamando 'mp3'
DS3231 rtc(SDA, SCL);
//==== Definindo Fontes
extern uint8_t SmallFont[];
extern uint8_t BigFont[];
extern uint8_t SevenSegNumFont[];
extern unsigned int MusicPlayerButton[0x1040];
extern unsigned int AlarmButton[0x1040];
extern unsigned int ButtonPlay[0x1AE9];
extern unsigned int ButtonPause[0x1AE9];
extern unsigned int PreviousButton[0x9C4];
extern unsigned int NextButton[0x9C4];
extern unsigned int VolumeDown[0x170];
extern unsigned int VolumeUp[0x3B8];
int x, y; // Variáveis para coordenadas onde a tela foi pressionada
char currentPage, playStatus;
int iV = 15;
int trackNum = 1;
int b = 16;
int aHours = 0;
int aMinutes = 0;
boolean alarmNotSet = true;
String alarmString = "";
float currentTemperature, temperature;
static word totalTime, elapsedTime, playback, minutes, seconds, lastSeconds, minutesR, secondsR;
String currentClock, currentHours, currentMinutes, currentSeconds, currentDate;
String timeString, hoursString, minutesString, secondsString, hoursS, minutesS, secondsS, dateS;
Podemos notar aqui a definição dos bitmaps. Alguns dos botões do programa são na verdade imagens convertidas em bitmaps usando a ferramenta ImageConverter565 que vem com a biblioteca TFT.

Então, estes arquivos ".c" precisam ser incluídos no diretório do arquivo de código para que carreguem ao iniciar o sketch. Aqui você pode baixar estas imagens e arquivos ".c".
Na seção setup, após inicializar os objetos, chamamos a função personalizada drawHomeScreen() que desenha todos os gráficos da tela inicial. Também aqui definimos os valores iniciais de algumas variáveis, como playStatus, temperatura atual e Data, o valor inicial do volume e assim por diante.
void setup() {
// Inicia display
myGLCD.InitLCD();
myGLCD.clrScr();
myTouch.InitTouch();
myTouch.setPrecision(PREC_MEDIUM);
// Inicializa objeto rtc
rtc.begin();
// Música
Serial.begin(9600); // define taxa de baud do monitor serial para Arduino IDE
mp3Serial.begin(9600); // BY8001 definido para 9600 baud (obrigatório)
mp3.setup(mp3Serial); // diz à biblioteca BY8001 qual porta serial usar
delay(800); // permite tempo para cold boot do BY8001; pode ajustar dependendo do tamanho do armazenamento flash
drawHomeScreen(); // Desenha a Tela Inicial
currentPage = '0'; // Indica que estamos na Tela Inicial
playStatus = '0';
mp3.setVolume(15);
delay(100);
currentTemperature = rtc.getTemp();
currentDate = rtc.getDateStr();
currentClock = rtc.getTimeStr();
timeString = rtc.getTimeStr();
currentHours = timeString.substring(0, 2);
currentMinutes = timeString.substring(3, 5);
currentSeconds = timeString.substring(6, 8);
}
Em seguida, está a seção loop. A primeira instrução if é verdadeira, pois definimos a variável currentPage como 0, o que indica que estamos na tela inicial. Aqui, com a próxima instrução if, verificamos se há uma mudança no relógio e isso acontece a cada segundo. Agora, como estamos usando a fonte de sete segmentos das bibliotecas TFT, que não suporta nenhum caractere exceto números, temos que extrair apenas os números da string que vem com a função getTimeStr() para ler o relógio do módulo RTC DS3231.

Então, usando a função substring(), obtemos as horas, minutos e segundos em variáveis separadas e as imprimimos cada vez que uma mudança aconteceu nos segundos, minutos ou horas. Quanto à data e temperatura, similarmente, verificamos se há uma mudança em comparação ao estado anterior.
void loop() {
// Tela Inicial
if (currentPage == '0') {
// Verifica mudança no relógio
if (currentClock != rtc.getTimeStr()) {
timeString = rtc.getTimeStr();
hoursS = timeString.substring(0, 2);
minutesS = timeString.substring(3, 5);
secondsS = timeString.substring(6, 8);
myGLCD.setFont(SevenSegNumFont);
myGLCD.setColor(0, 255, 0);
myGLCD.print(secondsS, 224, 50);
if (currentMinutes != minutesS) {
myGLCD.print(minutesS, 128, 50);
currentMinutes = minutesS;
}
if (currentHours != hoursS) {
myGLCD.print(hoursS, 32, 50);
currentHours = hoursS;
}
// Verifica mudança na data
dateS = rtc.getDateStr();
delay(10);
if (currentDate != dateS) {
myGLCD.setColor(255, 255, 255); // Define cor branca
myGLCD.setFont(BigFont); // Define fonte grande
myGLCD.print(rtc.getDateStr(), 153, 7);
}
// Verifica mudança na temperatura
temperature = rtc.getTemp();
delay(10);
if (currentTemperature != temperature) {
myGLCD.setColor(255, 255, 255);
myGLCD.setFont(BigFont);
myGLCD.printNumI(temperature, 39, 7);
currentTemperature = temperature;
}
delay(10);
currentClock = rtc.getTimeStr();
}
// Verifica se a tela foi tocada
if (myTouch.dataAvailable()) {
myTouch.read();
x = myTouch.getX(); // Coordenada X onde a tela foi pressionada
y = myTouch.getY(); // Coordenada Y onde a tela foi pressionada
// Se pressionarmos o botão Player de Música
if ((x >= 55) && (x <= 120) && (y >= 125) && (y <= 190)) {
drawFrame(87, 157, 33);
currentPage = '1';
myGLCD.clrScr();
delay(100);
drawMusicPlayerScreen();
delay(100);
}
// Se pressionarmos o botão Alarme
if ((x >= 195) && (x <= 260) && (y >= 125) && (y <= 190)) {
drawFrame(227, 160, 29);
currentPage = '2';
myGLCD.clrScr();
}
}
}
// Tela do Player de Música
if (currentPage == '1') {
if (myTouch.dataAvailable()) {
myTouch.read();
x = myTouch.getX();
y = myTouch.getY();
// Se pressionarmos o botão Play
if ((x >= 116) && (x <= 204) && (y >= 77) && (y <= 165)) {
if (playStatus == '0') {
drawFrame(159, 121, 42);
drawPauseButton();
mp3.playTrackFromFolder(00, 001);
delay(100);
playStatus = '2';
return;
}
if (playStatus == '1') {
drawFrame(159, 121, 42);
drawPauseButton();
mp3.play();
delay(100);
playStatus = '2';
return;
}
if (playStatus == '2') {
drawFrame(159, 121, 42);
drawPlayButton();
mp3.pause();
delay(100);
playStatus = '1';
return;
}
}
// Se pressionarmos o botão Anterior
if ((x >= 45) && (x <= 95) && (y >= 97) && (y <= 147)) {
drawFrame(70, 121, 26);
mp3.previousTrack();
delay(100);
drawTrackBar();
}
// Se pressionarmos o botão Próximo
if ((x >= 227) && (x <= 277) && (y >= 97) && (y <= 147)) {
drawFrame(252, 122, 26);
mp3.nextTrack();
delay(100);
drawTrackBar();
}
// Se pressionarmos o botão Volume Baixo
if ((x >= 35) && (x <= 75) && (y >= 165) && (y <= 209)) {
drawUnderline(45, 205, 65, 205);
if (iV >= 0 && iV <= 30) {
iV--;
drawVolume(iV);
}
mp3.decreaseVolume();
delay(100);
}
// Se pressionarmos o botão Volume Alto
if ((x >= 230) && (x <= 280) && (y >= 165) && (y <= 209)) {
drawUnderline(235, 205, 275, 205);
if (iV >= 0 && iV <= 30) {
iV++;
drawVolume(iV);
}
mp3.increaseVolume();
delay(100);
}
// Se pressionarmos o botão MENU
if ((x >= 0) && (x <= 75) && (y >= 0) && (y <= 30)) {
myGLCD.clrScr();
drawHomeScreen(); // Desenha a Tela Inicial
currentPage = '0';
return;
}
}
// Atualiza a barra de progresso da faixa
if (playStatus == '1' || playStatus == '2') {
trackPlayTime();
}
// Imprime o relógio no canto superior direito
myGLCD.setFont(BigFont);
myGLCD.setColor(255, 255, 255);
printClock(187, 5);
}
// Tela do Relógio Despertador
if (currentPage == '2') {
myGLCD.setFont(BigFont);
myGLCD.setColor(255, 255, 255);
myGLCD.print("MENU", 5, 5);
myGLCD.print("Definir Alarme", CENTER, 20);
// Desenha dois pontos entre horas e minutos
myGLCD.setColor(0, 255, 0);
myGLCD.fillCircle(112, 65, 4);
myGLCD.setColor(0, 255, 0);
myGLCD.fillCircle(112, 85, 4);
myGLCD.setFont(SevenSegNumFont);
myGLCD.setColor(0, 255, 0);
myGLCD.printNumI(aHours, 32, 50, 2, '0');
myGLCD.printNumI(aMinutes, 128, 50, 2, '0');
myGLCD.setColor(255, 255, 255);
myGLCD.drawRoundRect(42, 115, 82, 145);
myGLCD.drawRoundRect(138, 115, 178, 145);
myGLCD.setFont(BigFont);
myGLCD.print("H", 54, 122);
myGLCD.print("M", 150, 122);
myGLCD.drawRoundRect(215, 60, 303, 90);
myGLCD.print("SET", 236, 67);
myGLCD.drawRoundRect(215, 115, 303, 145);
myGLCD.print("CLEAR", 220, 122);
alarmNotSet = true;
while (alarmNotSet) {
if (myTouch.dataAvailable()) {
myTouch.read();
x = myTouch.getX();
y = myTouch.getY();
// Botão definir horas
if ((x >= 42) && (x <= 82) && (y >= 115) && (y <= 145)) {
drawRectFrame(42, 115, 82, 145);
aHours++;
if (aHours >= 24) { aHours = 0; }
myGLCD.setFont(SevenSegNumFont);
myGLCD.setColor(0, 255, 0);
myGLCD.printNumI(aHours, 32, 50, 2, '0');
}
// Botão definir minutos
if ((x >= 138) && (x <= 178) && (y >= 115) && (y <= 145)) {
drawRectFrame(138, 115, 178, 145);
aMinutes++;
if (aMinutes >= 60) { aMinutes = 0; }
myGLCD.setFont(SevenSegNumFont);
myGLCD.setColor(0, 255, 0);
myGLCD.printNumI(aMinutes, 128, 50, 2, '0');
}
// Botão definir alarme
if ((x >= 215) && (x <= 303) && (y >= 60) && (y <= 80)) {
drawRectFrame(215, 60, 303, 90);
if (aHours < 10 && aMinutes < 10) {
alarmString = "0" + (String)aHours + ":" + "0" + (String)aMinutes + ":" + "00";
} else if (aHours < 10 && aMinutes > 9) {
alarmString = "0" + (String)aHours + ":" + (String)aMinutes + ":" + "00";
} else if (aHours > 9 && aMinutes < 10) {
alarmString = (String)aHours + ":" + "0" + (String)aMinutes + ":" + "00";
} else {
alarmString = (String)aHours + ":" + (String)aMinutes + ":" + "00";
}
myGLCD.setFont(BigFont);
myGLCD.print("Alarme definido para:", CENTER, 165);
myGLCD.print(alarmString, CENTER, 191);
}
// Botão limpar alarme
if ((x >= 215) && (x <= 303) && (y >= 115) && (y <= 145)) {
drawRectFrame(215, 115, 303, 145);
alarmString = "";
myGLCD.setColor(0, 0, 0);
myGLCD.fillRect(45, 165, 275, 210);
}
// Se pressionarmos o botão MENU
if ((x >= 0) && (x <= 75) && (y >= 0) && (y <= 30)) {
alarmNotSet = false;
currentPage = '0';
myGLCD.clrScr();
drawHomeScreen(); // Desenha a Tela Inicial
}
}
}
}
// Ativação do alarme
if (alarmNotSet == false) {
if (alarmString == rtc.getTimeStr()) {
myGLCD.clrScr();
mp3.setVolume(25);
mp3.playTrackByIndexNumber(1);
delay(100);
myGLCD.setFont(BigFont);
myGLCD.setColor(255, 255, 255);
myGLCD.print("ALARME", CENTER, 90);
myGLCD.drawBitmap(127, 10, 65, 64, AlarmButton);
myGLCD.print(alarmString, CENTER, 114);
myGLCD.drawRoundRect(94, 146, 226, 170);
myGLCD.print("DISPENSAR", CENTER, 150);
boolean alarmOn = true;
while (alarmOn) {
if (myTouch.dataAvailable()) {
myTouch.read();
x = myTouch.getX();
y = myTouch.getY();
// Botão parar alarme
if ((x >= 94) && (x <= 226) && (y >= 146) && (y <= 170)) {
drawRectFrame(94, 146, 226, 170);
alarmOn = false;
alarmString = "";
myGLCD.clrScr();
mp3.stopPlayback();
delay(100);
currentPage = '0';
playStatus = '0';
mp3.setVolume(15);
drawHomeScreen();
}
}
}
}
}
}
Note aqui que precisamos ajustar esta string para ter a mesma forma que a string que obtemos da função getTimeString(). Dessa forma, poderemos compará-las e ativar o alarme quando o relógio atingir esse mesmo valor ou hora.

Se pressionarmos o botão limpar, limparemos a alarmString e, se pressionarmos o botão menu, sairá do loop while e voltará à tela inicial.
Para ativar o alarme, verificamos se o alarme foi definido e se o alarme corresponde ao relógio, a primeira música no cartão MicroSD começará a tocar em volume mais alto. Também desenharemos todos os gráficos junto com o botão "Dispensar" e definiremos a variável alarmOn como true. Isso nos colocará no próximo loop while que permitirá a música continuar tocando até pressionarmos o botão "Dispensar".
// Ativação do alarme
if (alarmNotSet == false) {
if (alarmString == rtc.getTimeStr()) {
myGLCD.clrScr();
mp3.setVolume(25);
mp3.playTrackByIndexNumber(1);
delay(100);
myGLCD.setFont(BigFont);
myGLCD.setColor(255, 255, 255);
myGLCD.print("ALARME", CENTER, 90);
myGLCD.drawBitmap(127, 10, 65, 64, AlarmButton);
myGLCD.print(alarmString, CENTER, 114);
myGLCD.drawRoundRect(94, 146, 226, 170);
myGLCD.print("DISPENSAR", CENTER, 150);
boolean alarmOn = true;
while (alarmOn) {
if (myTouch.dataAvailable()) {
myTouch.read();
x = myTouch.getX();
y = myTouch.getY();
// Botão parar alarme
if ((x >= 94) && (x <= 226) && (y >= 146) && (y <= 170)) {
drawRectFrame(94, 146, 226, 170);
alarmOn = false;
alarmString = "";
myGLCD.clrScr();
mp3.stopPlayback();
delay(100);
currentPage = '0';
playStatus = '0';
mp3.setVolume(15);
drawHomeScreen();
}
}
}
}
}
É assim que o código funciona e você pode encontrar o código fonte completo no final do artigo.
Construindo o Dispositivo
Usando SolidWorks, fiz o design e aqui está como fica.

Você pode baixar este modelo para obter as medidas aqui:
Para este projeto, escolhi usar chapa de alumínio que cortei no tamanho usando uma multi-ferramenta. Então, na borda da minha mesa e com a ajuda de alguns grampos e ripas, dobrei a chapa de metal.

Quanto aos alto-falantes, imprimi um padrão circular, fixei no lugar e, usando uma furadeira, fiz todos os furos.

Depois, cortei os lados na forma apropriada e os fixei à chapa de metal previamente dobrada usando uma pistola de cola quente.
No final, pintei a caixa de chapa de metal e estava pronta para os componentes eletrônicos serem fixados. Novamente, usando uma pistola de cola quente, fixei todos os componentes, conectei tudo e fixei a tampa traseira do dispositivo usando dois parafusos.

É isso, sinta-se à vontade para fazer qualquer pergunta na seção de comentários abaixo.
Aqui está o código fonte completo do dispositivo:
/*
* Arduino Touch Screen MP3 Music Player and Alarm Clock
* Crated by Dejan Nedelkovski
* www.HowToMechatronics.com
* UFTF, URTouch e DS3231 libraries feitas por Henning Karlsen, encontradas em www.rinkydinkelectronics.com.
* BY8001 MP3 Player Library feita por borland do fórum Arduino, domínio público. Link: https://github.com/r0ndL/BY8001
*/
#include <UTFT.h>
#include <URTouch.h>
#include <SoftwareSerial.h>
#include <BY8001.h>
#include <DS3231.h>
//==== Criando Objetos
UTFT myGLCD(SSD1289, 38, 39, 40, 41);
URTouch myTouch(6, 5, 4, 3, 2);
SoftwareSerial mp3Serial(11, 10);
BY8001 mp3;
DS3231 rtc(SDA, SCL);
//==== Definindo Fontes
extern uint8_t SmallFont[];
extern uint8_t BigFont[];
extern uint8_t SevenSegNumFont[];
extern unsigned int MusicPlayerButton[0x1040];
extern unsigned int AlarmButton[0x1040];
extern unsigned int ButtonPlay[0x1AE9];
extern unsigned int ButtonPause[0x1AE9];
extern unsigned int PreviousButton[0x9C4];
extern unsigned int NextButton[0x9C4];
extern unsigned int VolumeDown[0x170];
extern unsigned int VolumeUp[0x3B8];
int x, y;
char currentPage, playStatus;
int iV = 15;
int trackNum = 1;
int b = 16;
int aHours = 0;
int aMinutes = 0;
boolean alarmNotSet = true;
String alarmString = "";
float currentTemperature, temperature;
static word totalTime, elapsedTime, playback, minutes, seconds, lastSeconds, minutesR, secondsR;
String currentClock, currentHours, currentMinutes, currentSeconds, currentDate;
String timeString, hoursString, minutesString, secondsString, hoursS, minutesS, secondsS, dateS;
void setup() {
myGLCD.InitLCD();
myGLCD.clrScr();
myTouch.InitTouch();
myTouch.setPrecision(PREC_MEDIUM);
rtc.begin();
Serial.begin(9600);
mp3Serial.begin(9600);
mp3.setup(mp3Serial);
delay(800);
drawHomeScreen();
currentPage = '0';
playStatus = '0';
mp3.setVolume(15);
delay(100);
currentTemperature = rtc.getTemp();
currentDate = rtc.getDateStr();
currentClock = rtc.getTimeStr();
timeString = rtc.getTimeStr();
currentHours = timeString.substring(0, 2);
currentMinutes = timeString.substring(3, 5);
currentSeconds = timeString.substring(6, 8);
}
void loop() {
if (currentPage == '0') {
if (currentClock != rtc.getTimeStr()) {
timeString = rtc.getTimeStr();
hoursS = timeString.substring(0, 2);
minutesS = timeString.substring(3, 5);
secondsS = timeString.substring(6, 8);
myGLCD.setFont(SevenSegNumFont);
myGLCD.setColor(0, 255, 0);
myGLCD.print(secondsS, 224, 50);
if (currentMinutes != minutesS) {
myGLCD.print(minutesS, 128, 50);
currentMinutes = minutesS;
}
if (currentHours != hoursS) {
myGLCD.print(hoursS, 32, 50);
currentHours = hoursS;
}
dateS = rtc.getDateStr();
delay(10);
if (currentDate != dateS) {
myGLCD.setColor(255, 255, 255);
myGLCD.setFont(BigFont);
myGLCD.print(rtc.getDateStr(), 153, 7);
}
temperature = rtc.getTemp();
delay(10);
if (currentTemperature != temperature) {
myGLCD.setColor(255, 255, 255);
myGLCD.setFont(BigFont);
myGLCD.printNumI(temperature, 39, 7);
currentTemperature = temperature;
}
delay(10);
currentClock = rtc.getTimeStr();
}
if (myTouch.dataAvailable()) {
myTouch.read();
x = myTouch.getX();
y = myTouch.getY();
if ((x >= 55) && (x <= 120) && (y >= 125) && (y <= 190)) {
drawFrame(87, 157, 33);
currentPage = '1';
myGLCD.clrScr();
delay(100);
drawMusicPlayerScreen();
delay(100);
}
if ((x >= 195) && (x <= 260) && (y >= 125) && (y <= 190)) {
drawFrame(227, 160, 29);
currentPage = '2';
myGLCD.clrScr();
}
}
}
if (currentPage == '1') {
if (myTouch.dataAvailable()) {
myTouch.read();
x = myTouch.getX();
y = myTouch.getY();
if ((x >= 116) && (x <= 204) && (y >= 77) && (y <= 165)) {
if (playStatus == '0') {
drawFrame(159, 121, 42);
drawPauseButton();
mp3.playTrackFromFolder(00, 001);
delay(100);
playStatus = '2';
return;
}
if (playStatus == '1') {
drawFrame(159, 121, 42);
drawPauseButton();
mp3.play();
delay(100);
playStatus = '2';
return;
}
if (playStatus == '2') {
drawFrame(159, 121, 42);
drawPlayButton();
mp3.pause();
delay(100);
playStatus = '1';
return;
}
}
if ((x >= 45) && (x <= 95) && (y >= 97) && (y <= 147)) {
drawFrame(70, 121, 26);
mp3.previousTrack();
delay(100);
drawTrackBar();
}
if ((x >= 227) && (x <= 277) && (y >= 97) && (y <= 147)) {
drawFrame(252, 122, 26);
mp3.nextTrack();
delay(100);
drawTrackBar();
}
if ((x >= 35) && (x <= 75) && (y >= 165) && (y <= 209)) {
drawUnderline(45, 205, 65, 205);
if (iV >= 0 && iV <= 30) {
iV--;
drawVolume(iV);
}
mp3.decreaseVolume();
delay(100);
}
if ((x >= 230) && (x <= 280) && (y >= 165) && (y <= 209)) {
drawUnderline(235, 205, 275, 205);
if (iV >= 0 && iV <= 30) {
iV++;
drawVolume(iV);
}
mp3.increaseVolume();
delay(100);
}
if ((x >= 0) && (x <= 75) && (y >= 0) && (y <= 30)) {
myGLCD.clrScr();
drawHomeScreen();
currentPage = '0';
return;
}
}
if (playStatus == '1' || playStatus == '2') {
trackPlayTime();
}
myGLCD.setFont(BigFont);
myGLCD.setColor(255, 255, 255);
printClock(187, 5);
}
if (currentPage == '2') {
myGLCD.setFont(BigFont);
myGLCD.setColor(255, 255, 255);
myGLCD.print("MENU", 5, 5);
myGLCD.print("Definir Alarme", CENTER, 20);
myGLCD.setColor(0, 255, 0);
myGLCD.fillCircle(112, 65, 4);
myGLCD.setColor(0, 255, 0);
myGLCD.fillCircle(112, 85, 4);
myGLCD.setFont(SevenSegNumFont);
myGLCD.setColor(0, 255, 0);
myGLCD.printNumI(aHours, 32, 50, 2, '0');
myGLCD.printNumI(aMinutes, 128, 50, 2, '0');
myGLCD.setColor(255, 255, 255);
myGLCD.drawRoundRect(42, 115, 82, 145);
myGLCD.drawRoundRect(138, 115, 178, 145);
myGLCD.setFont(BigFont);
myGLCD.print("H", 54, 122);
myGLCD.print("M", 150, 122);
myGLCD.drawRoundRect(215, 60, 303, 90);
myGLCD.print("SET", 236, 67);
myGLCD.drawRoundRect(215, 115, 303, 145);
myGLCD.print("CLEAR", 220, 122);
alarmNotSet = true;
while (alarmNotSet) {
if (myTouch.dataAvailable()) {
myTouch.read();
x = myTouch.getX();
y = myTouch.getY();
if ((x >= 42) && (x <= 82) && (y >= 115) && (y <= 145)) {
drawRectFrame(42, 115, 82, 145);
aHours++;
if (aHours >= 24) { aHours = 0; }
myGLCD.setFont(SevenSegNumFont);
myGLCD.setColor(0, 255, 0);
myGLCD.printNumI(aHours, 32, 50, 2, '0');
}
if ((x >= 138) && (x <= 178) && (y >= 115) && (y <= 145)) {
drawRectFrame(138, 115, 178, 145);
aMinutes++;
if (aMinutes >= 60) { aMinutes = 0; }
myGLCD.setFont(SevenSegNumFont);
myGLCD.setColor(0, 255, 0);
myGLCD.printNumI(aMinutes, 128, 50, 2, '0');
}
if ((x >= 215) && (x <= 303) && (y >= 60) && (y <= 80)) {
drawRectFrame(215, 60, 303, 90);
if (aHours < 10 && aMinutes < 10) {
alarmString = "0" + (String)aHours + ":" + "0" + (String)aMinutes + ":" + "00";
} else if (aHours < 10 && aMinutes > 9) {
alarmString = "0" + (String)aHours + ":" + (String)aMinutes + ":" + "00";
} else if (aHours > 9 && aMinutes < 10) {
alarmString = (String)aHours + ":" + "0" + (String)aMinutes + ":" + "00";
} else {
alarmString = (String)aHours + ":" + (String)aMinutes + ":" + "00";
}
myGLCD.setFont(BigFont);
myGLCD.print("Alarme definido para:", CENTER, 165);
myGLCD.print(alarmString, CENTER, 191);
}
if ((x >= 215) && (x <= 303) && (y >= 115) && (y <= 145)) {
drawRectFrame(215, 115, 303, 145);
alarmString = "";
myGLCD.setColor(0, 0, 0);
myGLCD.fillRect(45, 165, 275, 210);
}
if ((x >= 0) && (x <= 75) && (y >= 0) && (y <= 30)) {
alarmNotSet = false;
currentPage = '0';
myGLCD.clrScr();
drawHomeScreen();
}
}
}
}
if (alarmNotSet == false) {
if (alarmString == rtc.getTimeStr()) {
myGLCD.clrScr();
mp3.setVolume(25);
mp3.playTrackByIndexNumber(1);
delay(100);
myGLCD.setFont(BigFont);
myGLCD.setColor(255, 255, 255);
myGLCD.print("ALARME", CENTER, 90);
myGLCD.drawBitmap(127, 10, 65, 64, AlarmButton);
myGLCD.print(alarmString, CENTER, 114);
myGLCD.drawRoundRect(94, 146, 226, 170);
myGLCD.print("DISPENSAR", CENTER, 150);
boolean alarmOn = true;
while (alarmOn) {
if (myTouch.dataAvailable()) {
myTouch.read();
x = myTouch.getX();
y = myTouch.getY();
if ((x >= 94) && (x <= 226) && (y >= 146) && (y <= 170)) {
drawRectFrame(94, 146, 226, 170);
alarmOn = false;
alarmString = "";
myGLCD.clrScr();
mp3.stopPlayback();
delay(100);
currentPage = '0';
playStatus = '0';
mp3.setVolume(15);
drawHomeScreen();
}
}
}
}
}
}
void drawHomeScreen() {
myGLCD.setBackColor(0, 0, 0);
myGLCD.setColor(255, 255, 255);
myGLCD.setFont(BigFont);
myGLCD.print(rtc.getDateStr(), 153, 7);
myGLCD.print("T:", 7, 7);
myGLCD.printNumI(rtc.getTemp(), 39, 7);
myGLCD.print("C", 82, 7);
myGLCD.setFont(SmallFont);
myGLCD.print("o", 74, 5);
if (alarmString == "") {
myGLCD.setColor(255, 255, 255);
myGLCD.print("by www.HowToMechatronics.com", CENTER, 215);
} else {
myGLCD.setColor(255, 255, 255);
myGLCD.print("Alarme definido para: ", 68, 215);
myGLCD.print(alarmString, 188, 215);
}
drawMusicPlayerButton();
drawAlarmButton();
drawHomeClock();
}
void drawMusicPlayerScreen() {
myGLCD.setBackColor(0, 0, 0);
myGLCD.setColor(255, 255, 255);
myGLCD.setFont(BigFont);
myGLCD.print("MENU", 5, 5);
myGLCD.setColor(255, 0, 0);
myGLCD.drawLine(0, 26, 319, 26);
myGLCD.setColor(255, 255, 255);
myGLCD.setFont(SmallFont);
myGLCD.print("by www.HowToMechatronics.com", CENTER, 215);
myGLCD.setColor(255, 255, 255);
myGLCD.fillRect(78, 184, 78 + 150, 184 + 8);
myGLCD.setColor(240, 196, 30);
myGLCD.fillRect(78, 184, 78 + 75, 184 + 8);
myGLCD.setColor(255, 255, 255);
myGLCD.fillRect(48, 50, 48 + 224, 50 + 8);
myGLCD.setFont(SmallFont);
myGLCD.setColor(255, 255, 255);
myGLCD.print("0:00", 8, 48);
myGLCD.print("-0:00", 276, 48);
drawPlayButton();
if (playStatus == '2') {
drawPauseButton();
}
drawPreviousButton();
drawNextButton();
drawVolumeDown();
drawVolumeUp();
}
void drawMusicPlayerButton() {
myGLCD.drawBitmap(55, 125, 65, 64, MusicPlayerButton);
}
void drawAlarmButton() {
myGLCD.drawBitmap(195, 125, 65, 64, AlarmButton);
}
void drawPlayButton() {
myGLCD.drawBitmap(118, 79, 83, 83, ButtonPlay);
}
void drawPauseButton() {
myGLCD.drawBitmap(118, 79, 83, 83, ButtonPause);
}
void drawNextButton() {
myGLCD.drawBitmap(227, 97, 50, 50, NextButton);
}
void drawPreviousButton() {
myGLCD.drawBitmap(45, 97, 50, 50, PreviousButton);
}
void drawVolumeDown() {
myGLCD.drawBitmap(50, 177, 16, 23, VolumeDown);
}
void drawVolumeUp() {
myGLCD.drawBitmap(241, 175, 34, 28, VolumeUp);
}
bool checkFor_mp3IsStopped() {
if (mp3Serial.available() > 0) {
if (mp3.getPlaybackStatus() == 0) {
return true;
}
} else return false;
}
void drawFrame(int x, int y, int r) {
myGLCD.setColor(255, 0, 0);
myGLCD.drawCircle(x, y, r);
while (myTouch.dataAvailable()) myTouch.read();
myGLCD.setColor(0, 0, 0);
myGLCD.drawCircle(x, y, r);
}
void drawRectFrame(int x1, int y1, int x2, int y2) {
myGLCD.setColor(255, 0, 0);
myGLCD.drawRoundRect(x1, y1, x2, y2);
while (myTouch.dataAvailable()) myTouch.read();
myGLCD.setColor(255, 255, 255);
myGLCD.drawRoundRect(x1, y1, x2, y2);
}
void drawUnderline(int x1, int y1, int x2, int y2) {
myGLCD.setColor(255, 0, 0);
myGLCD.drawLine(x1, y1, x2, y2);
while (myTouch.dataAvailable()) myTouch.read();
myGLCD.setColor(0, 0, 0);
myGLCD.drawLine(x1, y1, x2, y2);
}
void drawVolume(int x) {
myGLCD.setColor(255, 255, 255);
myGLCD.fillRect(78 + 5 * x, 184, 78 + 150, 184 + 8);
myGLCD.setColor(240, 196, 30);
myGLCD.fillRect(78, 184, 78 + 5 * x, 184 + 8);
}
void drawTrackBar() {
myGLCD.setColor(255, 255, 255);
myGLCD.fillRect(48, 50, 48 + 224, 50 + 8);
}
void trackPlayTime() {
totalTime = mp3.getTotalTrackPlaybackTime();
delay(10);
elapsedTime = mp3.getElapsedTrackPlaybackTime();
delay(10);
minutes = (int)elapsedTime / 60;
seconds = (((float)elapsedTime / 60) - minutes) * 60;
playback = totalTime - elapsedTime;
minutesR = (int)playback / 60;
secondsR = (((float)playback / 60) - minutesR) * 60;
myGLCD.setFont(SmallFont);
myGLCD.setColor(255, 255, 255);
myGLCD.printNumI(minutes, 8, 48);
myGLCD.print(":", 16, 48);
myGLCD.printNumI((int)seconds, 24, 48, 2, '0');
myGLCD.print("-", 276, 48);
myGLCD.printNumI(minutesR, 284, 48);
myGLCD.print(":", 292, 48);
myGLCD.printNumI((int)secondsR, 300, 48, 2, '0');
int trackBarX = map(elapsedTime, 0, totalTime, 0, 224);
myGLCD.setColor(255, 0, 0);
myGLCD.fillRect(48, 50, 48 + trackBarX, 50 + 8);
if (totalTime == elapsedTime) {
mp3.nextTrack();
delay(30);
myGLCD.setColor(255, 255, 255);
myGLCD.fillRect(48, 50, 48 + 224, 50 + 8);
}
}
void printClock(int x, int y) {
if (currentClock != rtc.getTimeStr()) {
myGLCD.print(rtc.getTimeStr(), x, y);
currentClock = rtc.getTimeStr();
}
}
void drawColon() {
myGLCD.setColor(0, 255, 0);
myGLCD.fillCircle(112, 65, 4);
myGLCD.setColor(0, 255, 0);
myGLCD.fillCircle(112, 85, 4);
myGLCD.setColor(0, 255, 0);
myGLCD.fillCircle(208, 65, 4);
myGLCD.setColor(0, 255, 0);
myGLCD.fillCircle(208, 85, 4);
}
void drawHomeClock() {
timeString = rtc.getTimeStr();
currentHours = timeString.substring(0, 2);
currentMinutes = timeString.substring(3, 5);
currentSeconds = timeString.substring(6, 8);
myGLCD.setFont(SevenSegNumFont);
myGLCD.setColor(0, 255, 0);
myGLCD.print(currentSeconds, 224, 50);
myGLCD.print(currentMinutes, 128, 50);
myGLCD.print(currentHours, 32, 50);
drawColon();
}
Sinta-se à vontade para fazer qualquer pergunta na seção de comentários abaixo e não se esqueça de conferir minha coleção de Projetos Arduino.
Processo de manufatura
- Relógio POV com Arduino: Construa um Display LED de Persistência de Visão
- Construa um Relógio Mestre LED Personalizado com Alarme – Visível a 12 Metros
- Monitor de Temperatura e Relógio Tempo Real com Arduino Due e Display TFT 3.2"
- Como Reproduzir Áudio com Arduino UNO e DFPlayer Mini – Guia Passo a Passo
- Relógio Digital TM1637 com Configuração de Hora e Alarme – Prototipo Arduino Nano
- Reprodutor MP3 Controlado via Web com Arduino: Reprodução de Áudio Fácil pelo Navegador
- Jogo da Velha com Arduino, Matriz LED MAX7219 e Caixa de Papelão
- Construa um Voltímetro DIY com Arduino e Display Nokia 5110 – Guia Passo a Passo
- Construa um Temporizador Regressivo Confiável com Arduino e Display de 7 Segmentos SparkFun
- Construa um Relógio Despertador Confiável com RTC DS1302 e Arduino UNO