Resultados da busca - %E6%9D%8F%E5%BD%A9%E5%B9%B3%E5%8F%B0170%E5%88%B01840%E5%88%86%E5%88%AB%E4%BB%A3%E8%A1%A8%E4%BB%80%E4%B9%88%E6%84%8F%E6%80%9D?%E3%80%90%E2%94%83%E8%81%94%E7%B3%BB%EF%BC%9217431(%E6%89%A3)%E3%80%91%E3%80%91
status.
vlw pelas dicas
#include <DS3231.h>#include <Wire.h>[#include <SPI.h>#include <Ethernet.h>int buzzer = 13;
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };byte ip[] = { 192, 168, 1, 235 };EthernetServer server(80);String readString;int Pin = 13;
DS3231 Clock;bool Century=false;bool h12;bool PM;byte ADay, AHour, AMinute, ASecond, ABits;bool ADy, A12h, Apm;byte year, month, date, DoW, hour, minute, second;
void setup() { pinMode(Pin, OUTPUT); Ethernet.begin(mac, ip); server.begin(); pinMode (buzzer, OUTPUT);// Start the I2C interfaceWire.begin();// VERY IMPORTANT COMMENTS BELOW!!!// If you want to set the time, change these numbers to the date and time you want to set to, and then upload it to the arduino.// once you have finished setting the time, comment out the following clock.set functions and then reupload it to the board. Otherwise your clock will reset every time you open the serial monitor.// Clock.setSecond(05);//Set the second// Clock.setMinute(37);//Set the minute// Clock.setHour(10); //Set the hour// Clock.setDoW(7); //Set the day of the week// Clock.setDate(18); //Set the date of the month// Clock.setMonth(10); //Set the month of the year// Clock.setYear(15); //Set the year (Last two digits of the year)// Start the serial interfaceSerial.begin(9600);}void ReadDS3231(){ int second,minute,hour,date,month,year,temperature; second=Clock.getSecond(); minute=Clock.getMinute(); hour=Clock.getHour(h12, PM); date=Clock.getDate(); month=Clock.getMonth(Century); year=Clock.getYear(); // Definicao do alarme.if (hour == 10 && minute ==39 && second == 0)//Define a hora de tocar o alarme por 1o segundos{digitalWrite (buzzer, HIGH);// Eleva tensao pino 13 para 5Vdelay (10000);// Atrasa 50ms}{if (hour == 10 && minute == 56 && second == 05)//Define a hora de tocar o alarme por 10 segundos
digitalWrite (buzzer, LOW); //Abaixa tensao pino 13 para 0V}
temperature=Clock.getTemperature();
Serial.print("20"); Serial.print(year,DEC); Serial.print('-'); Serial.print(month,DEC); Serial.print('-'); Serial.print(date,DEC); Serial.print(' '); Serial.print(hour,DEC); Serial.print(':'); Serial.print(minute,DEC); Serial.print(':'); Serial.print(second,DEC); Serial.print('\n'); Serial.print("Temperature="); Serial.print(temperature); Serial.print('\n');}void loop() {ReadDS3231();delay(1000);// send what's going on to the serial monitor.// Start with the year/* Serial.print("2");if (Century) { // Won't need this for 89 years.Serial.print("1");} else {Serial.print("0");}Serial.print(Clock.getYear(), DEC);Serial.print('-');// then the monthSerial.print(Clock.getMonth(Century), DEC);Serial.print('-');// then the dateSerial.print(Clock.getDate(), DEC);Serial.print(' ');*/// and the day of the week/*Serial.print(Clock.getDoW(), DEC);Serial.print(' ');*/// Finally the hour, minute, and second/*Serial.print(Clock.getHour(h12, PM), DEC);Serial.print(':');Serial.print(Clock.getMinute(), DEC);Serial.print(':');Serial.print(Clock.getSecond(), DEC);// Add AM/PM indicatorif (h12) {if (PM) {Serial.print(" PM ");} else {Serial.print(" AM ");}} else {Serial.print(" 24h ");}// Display the temperatureSerial.print("T=");Serial.print(Clock.getTemperature(), 2);// Tell whether the time is (likely to be) validif (Clock.oscillatorCheck()) {Serial.print(" O+");} else {Serial.print(" O-");}*/// Indicate whether an alarm went off/*if (Clock.checkIfAlarm(1)) {Serial.print(" A1!");}if (Clock.checkIfAlarm(2)) {Serial.print(" A2!");}*/// New line on display//Serial.print('\n'); // delay(1000);// Display Alarm 1 information/* Serial.print("Alarm 1: ");Clock.getA1Time(ADay, AHour, AMinute, ASecond, ABits, ADy, A12h, Apm);Serial.print(ADay, DEC);if (ADy) {Serial.print(" DoW");} else {Serial.print(" Date");}Serial.print(' ');Serial.print(AHour, DEC);Serial.print(' ');Serial.print(AMinute, DEC);Serial.print(' ');Serial.print(ASecond, DEC);Serial.print(' ');if (A12h) {if (Apm) {Serial.print('pm ');} else {Serial.print('am ');}}if (Clock.checkAlarmEnabled(1)) {Serial.print("enabled");}Serial.print('\n');// Display Alarm 2 informationSerial.print("Alarm 2: ");Clock.getA2Time(ADay, AHour, AMinute, ABits, ADy, A12h, Apm);Serial.print(ADay, DEC);if (ADy) {Serial.print(" DoW");} else {Serial.print(" Date");}Serial.print(' ');Serial.print(AHour, DEC);Serial.print(' ');Serial.print(AMinute, DEC);Serial.print(' ');if (A12h) {if (Apm) {Serial.print('pm');} else {Serial.print('am');}}if (Clock.checkAlarmEnabled(2)) {Serial.print("enabled");}*//* display alarm bitsSerial.print('\n');Serial.print('Alarm bits: ');Serial.print(ABits, DEC);*//*Serial.print('\n');Serial.print('\n');delay(1000);// Display the time once more as a test of the getTime() functionClock.getTime(year, month, date, DoW, hour, minute, second); Serial.print(year, DEC); Serial.print("/");Serial.print(month, DEC); Serial.print("/");Serial.print(date, DEC); Serial.print("day of the week :");Serial.println(DoW, DEC);Serial.print(hour, DEC); Serial.print(":");Serial.print(minute, DEC); Serial.print(":");Serial.println(second, DEC);*/
EthernetClient client = server.available(); if (client) { while (client.connected()) { if (client.available()) { char c = client.read(); if (readString.length() < 100) { readString += c; } if (c == '\n') { client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println(); client.println("<HTML>"); client.println("<BODY>"); client.println("<H1>Acende LED</H1>"); client.println("<hr />"); client.println("<br />"); client.println("<a href=\"/?ledon\"\">Ligar o led</a>"); client.println("<a href=\"/?ledoff\"\">Desligar o led</a><br />"); client.println("</BODY>"); client.println("</HTML>"); delay(1); client.stop(); if(readString.indexOf("?ledon") > 0) { digitalWrite(Pin, HIGH); } else { if(readString.indexOf("?ledoff") > 0) { digitalWrite(Pin, LOW); } } readString=""; } } } }}…
6#define strobe 3#define clock 2#define numberboards 1RelayBoard relay(date, strobe, clock, numberboards);int i;int j;// MAC address from Ethernet shield sticker under boardbyte mac[] = { 0x90, 0xA2, 0xDA, 0x0D, 0x42, 0x3E };IPAddress ip(192,168,2,164); // IP address, may need to change depending on networkEthernetServer server(65); // create a server at port 80// File webFile; // the web page file on the SD cardchar HTTP_req[REQ_BUF_SZ] = {0}; // buffered HTTP request stored as null terminated stringchar req_index = 0; // index into HTTP_req bufferboolean LED_state[6] = {0}; // stores the states of the LEDsvoid setup(){ // disable Ethernet chip pinMode(10, OUTPUT); digitalWrite(10, HIGH); Serial.begin(9600); // for debugging /* // initialize SD card Serial.println("Initializing SD card..."); if (!SD.begin(4)) { Serial.println("ERROR - SD card initialization failed!"); return; // init failed } Serial.println("SUCCESS - SD card initialized."); // check for index.htm file if (!SD.exists("index.htm")) { Serial.println("ERROR - Can't find index.htm file!"); return; // can't find index file } Serial.println("SUCCESS - Found index.htm file."); // switch on pin 2 */ pinMode(A2, INPUT); pinMode(A3, INPUT); // LEDs Ethernet.begin(mac, ip); // initialize Ethernet device server.begin(); // start to listen for clients}void loop(){ EthernetClient client = server.available(); // try to get client if (client) { // got client? boolean currentLineIsBlank = true; while (client.connected()) { if (client.available()) { // client data available to read char c = client.read(); // read 1 byte (character) from client // limit the size of the stored received HTTP request // buffer first part of HTTP request in HTTP_req array (string) // leave last element in array as 0 to null terminate string (REQ_BUF_SZ - 1) if (req_index < (REQ_BUF_SZ - 1)) { HTTP_req[req_index] = c; // save HTTP request character req_index++; } // last line of client request is blank and ends with \n // respond to client only after last line received if (c == '\n' && currentLineIsBlank) { // send a standard http response header client.println("HTTP/1.1 200 OK"); // remainder of header follows below, depending on if // web page or XML page is requested // Ajax request - send XML file if (StrContains(HTTP_req, "ajax_inputs")) { // send rest of HTTP header client.println("Content-Type: text/xml"); client.println("Connection: keep-alive"); client.println(); SetLEDs(); // send XML file containing input states XML_response(client); } else { // web page request // send rest of HTTP header client.println("Content-Type: text/html"); client.println("Connection: keep-alive"); client.println(); // send web page /*webFile = SD.open("index.htm"); // open web page file if (webFile) { while(webFile.available()) { client.write(webFile.read()); // send web page to client } webFile.close(); }*/ } // display received HTTP request on serial port Serial.print(HTTP_req); // reset buffer index and all buffer elements to 0 req_index = 0; StrClear(HTTP_req, REQ_BUF_SZ); break; } // every line of text received from the client ends with \r\n if (c == '\n') { // last character on line of received text // starting new line with next character read currentLineIsBlank = true; } else if (c != '\r') { // a text character was received from client currentLineIsBlank = false; } } // end if (client.available()) } // end while (client.connected()) delay(1); // give the web browser time to receive the data client.stop(); // close the connection } // end if (client)}// checks if received HTTP request is switching on/off LEDs// also saves the state of the LEDsvoid SetLEDs(void){ // LED 1 (pin 6) if (StrContains(HTTP_req, "LED1=1")) { LED_state[0] = 1; // save LED state relay.set(0,0,1); } else if (StrContains(HTTP_req, "LED1=0")) { LED_state[0] = 0; // save LED state relay.set(0,0,0); } // LED 2 (pin 7) if (StrContains(HTTP_req, "LED2=1")) { LED_state[1] = 1; // save LED state relay.set(0,1,1); } else if (StrContains(HTTP_req, "LED2=0")) { LED_state[1] = 0; // save LED state relay.set(0,1,0); } // LED 3 (pin 8) if (StrContains(HTTP_req, "LED3=1")) { LED_state[2] = 1; // save LED state relay.set(0,2,1); } else if (StrContains(HTTP_req, "LED3=0")) { LED_state[2] = 0; // save LED state relay.set(0,2,0); } // LED 4 (pin 9) if (StrContains(HTTP_req, "LED4=1")) { LED_state[3] = 1; // save LED state relay.set(0,3,1); } else if (StrContains(HTTP_req, "LED4=0")) { LED_state[3] = 0; // save LED state relay.set(0,3,0); } // LED 5 (pin 5) if (StrContains(HTTP_req, "LED5=1")) { LED_state[4] = 1; // save LED state relay.set(0,4,1); } else if (StrContains(HTTP_req, "LED5=0")) { LED_state[4] = 0; // save LED state relay.set(0,4,0); } // LED 6 (pin 3) if (StrContains(HTTP_req, "LED6=1")) { LED_state[5] = 1; // save LED state relay.set(0,5,1); } else if (StrContains(HTTP_req, "LED6=0")) { LED_state[5] = 0; // save LED state relay.set(0,5,0); } // LED 7 (pin 3) if (StrContains(HTTP_req, "LED7=1")) { LED_state[6] = 1; // save LED state relay.set(0,6,1); } else if (StrContains(HTTP_req, "LED7=0")) { LED_state[6] = 0; // save LED state relay.set(0,6,0); } // LED 8 (pin 3) if (StrContains(HTTP_req, "LED8=1")) { LED_state[7] = 1; // save LED state relay.set(0,7,1); } else if (StrContains(HTTP_req, "LED8=0")) { LED_state[7] = 0; // save LED state relay.set(0,7,0); } // Ligar e desligar tudo. if (StrContains(HTTP_req, "LEDALL=1")) { for(int x = 0; x <= 7; x++){ LED_state[x] = 1; // save LED state relay.set(0,x,1); } } else if (StrContains(HTTP_req, "LEDALL=0")) { for(int x = 0; x <= 7; x++){ LED_state[x] = 0; // save LED state relay.set(0,x,0); } }}// send the XML file with analog values, switch status// and LED statusvoid XML_response(EthernetClient cl){ cl.println("<?xml version = \"1.0\" ?>"); cl.println("<inputs>"); // read analog inputs cl.print("<analog>"); cl.print(analogRead(4)); cl.println("</analog>"); cl.print("<analog>"); cl.print(analogRead(5)); cl.println("</analog>"); // read switches cl.print("<switch>"); if (digitalRead(2)) {cl.print("ON");} else {cl.print("OFF");} cl.println("</switch>"); cl.print("<switch>"); if (digitalRead(A2)) {cl.print("ON");} else {cl.print("OFF");} cl.println("</switch>"); cl.print("<switch>"); if (digitalRead(A3)) {cl.print("ON");} else {cl.print("OFF");} cl.println("</switch>"); // checkbox LED states // LED1 cl.print("<LED>"); if (LED_state[0]) {cl.print("checked");} else {cl.print("unchecked");} cl.println("</LED>"); // LED2 cl.print("<LED>"); if (LED_state[1]) {cl.print("checked");} else {cl.print("unchecked");} cl.println("</LED>"); // LED3 cl.print("<LED>"); if (LED_state[2]) {cl.print("on");} else {cl.print("off");} cl.println("</LED>"); // LED4 cl.print("<LED>"); if (LED_state[3]) {cl.print("on");} else {cl.print("off");} cl.println("</LED>"); // LED5 cl.print("<LED>"); if (LED_state[4]) {cl.print("on");} else {cl.print("off");} cl.println("</LED>"); // LED6 cl.print("<LED>"); if (LED_state[5]) {cl.print("on");} else {cl.print("off");} cl.println("</LED>"); cl.print("</inputs>");}// sets every element of str to 0 (clears array)void StrClear(char *str, char length){ for (int i = 0; i < length; i++) { str[i] = 0; }}// searches for the string sfind in the string str// returns 1 if string found// returns 0 if string not foundchar StrContains(char *str, char *sfind){ char found = 0; char index = 0; char len; len = strlen(str); if (strlen(sfind) > len) { return 0; } while (index < len) { if (str[index] == sfind[found]) { found++; if (strlen(sfind) == found) { return 1; } } else { found = 0; } index++; } return 0;}…
CD onde pretendo ter na primeira tela após ser acionado por um botão "bverde" uma mensagem com o nome da máquina passando então 1 segundo irá mostrar a quantidade a ser envasada. A quantidade será o valor digitado no Keypad;
- Após o valor ser digitado pelo keypad uma segunda tela é mostrada, nessa tela será contada a quantidade de envasada e pressionando o "bamarelo" muda a tela para a terceira tela onde irá mostrar o nível do tanque de armazenamento, pressionando o "bamarelo" novamente ele volta para a segunda tela, ou seja o "bamarelo" irá funcionar como um botão de opões que transita entre essas duas telas;
- Usando um decrementador quero que o mesmo decremente o valor digitado na tela 1 mostrando a mensagem de que o Lote esta pronto e que se deve inserir um novo valor;
- Um terceiro botão "bvermelho" seria o botão de emergência, ou seja se pressionado a máquina trava.
- Todo esse programa foi baseado em exemplos e projetos que encontrei aqui no fórum e em outros sites.
Segue o Programa:
//========================================================================
#include <Keypad.h>#include <LiquidCrystal.h> LiquidCrystal lcd(22,23,24,25,26,27); // DECLARAÇÃO DOS PINOS DO LCD NO ARDUINO
// DEFINIÇÃO DOS BOTÕES - VERDE. VERMELHO, AMARELO#define bverde A1 // Os pinos analógicos podem ser#define bamarelo A2 // usados como digitais, bastando#define bvermelho A3 // referenciá-los por A0, A1..#define bDown A4
#define bverde0 90 // Valor de referência que a#define bamarelo0 91 // função CheckButton() passa#define bvermelho0 92 // indicando que um botão foi#define bDown0 93 // solto
boolean averde, aamarelo, avermelho, aDown; // Grava o ultimo valor lidos nos botões.// Utilizado pela função Checkbutton p/ identificar quando há uma alteração no estado do pino dos botões
// DEFINIÇÃO DOS PINOS E VALORES PARA O SENSOR, ESTEIRA E BOMBAint contador = 0; int Sensor = 0; int sensorPin = A0; int MotorEsteira = 11;int MotorBomb= 12;int EstadoMotor=0;int EstadoSensor=1;int LED1=8;int LED2=9;int LED3=10;int LED4=2;int buzzer=7;int variavel; // VARIAVEL A SER ALTERADA PELO MENUchar state=1; // VARIÁVEL QUE GUARDA POSIÇÃO ATUAL DO MENUint dec=-1;int i=0;
const byte LIN = 4; // TECLADO POSSUI 4 LINHASconst byte COL = 3; //TECLADO POSSUI 3 COLUNASchar keys[LIN][COL] = { {//MATRIZ CORRESPONDENTE AOS CARACTERES DO KEYPAD '1','2','3' } , { '4','5','6' } , { '7','8','9' } , { '*','0','#' }};byte LinPins[LIN] = { 28,29,30,31}; //PINOS DO ARDUINO CORRESPONDENTES AS COLUNASbyte ColPins[COL] = { 32,33,34}; //E AS LINHAS DA MATRIZ
Keypad keypad = Keypad( makeKeymap(keys), LinPins, ColPins, LIN, COL );char key = keypad.getKey();
void setup(){ lcd.begin(16, 2); // Iniciando a biblioteca do LCD Serial.begin(9600); // DEFINIÇÃO DA PORTA SERIAL
pinMode(bverde, INPUT); // Botões pinMode(bamarelo,INPUT); pinMode(bvermelho, INPUT); pinMode(bDown, INPUT);
digitalWrite(bverde, HIGH); // Aciona o pull-up interno digitalWrite(bamarelo,HIGH); // dos botões digitalWrite(bvermelho, HIGH); digitalWrite(bDown, HIGH);
pinMode(sensorPin, INPUT); //DEFINIR SE A VARIAVEL É ENTRADA(IMPUT) OU SAIDA(OUTPUT) DE DADOS pinMode(MotorEsteira, OUTPUT); pinMode(MotorBomb, OUTPUT); pinMode(EstadoSensor, INPUT); pinMode(LED1, OUTPUT); pinMode(LED2, OUTPUT); pinMode(LED3, OUTPUT); pinMode(LED4, OUTPUT); pinMode(buzzer, OUTPUT);}
void loop(){ Sensor = digitalRead(sensorPin); // A VARIAVEL SENSOR CORRESPONDE AO sensorPin QUE ESTÁ LIGADO A PORTA ANALÓGICA A0 DO ARDUIN
if(Sensor == LOW){ digitalWrite(MotorEsteira, HIGH); // SE O SENSOR NÃO ESTIVER ACIONADO O MOTOR DA BOMBA ESTA PARADO E O LED1 ASCESO digitalWrite(LED1,HIGH); digitalWrite(LED2, LOW); digitalWrite(MotorBomb, LOW); digitalWrite(buzzer, LOW); } if(Sensor == HIGH) { // SE O SENSOR ESTIVER ACIONADO O MOTOR DA ESTEIRA ESTA PARADO E O LED1 APAGA digitalWrite(MotorEsteira, LOW); // O MOTOR DA BOMBA LIGA E O LED2 ASCENDE E UM TOQUE DE 2 SEGUNDO É digitalWrite(MotorBomb, HIGH); // ACIONADO PELO BUZZER digitalWrite(LED1, LOW); digitalWrite(LED2, HIGH);
delay(8000);//ESTE DELAY SERVE PARA A BOMBA JOGAR 200ml DE AGUA NA GARRAFA contador++; Sensor == !Sensor; //O SINAL DO SENSOR É INVERTIDO PARA A FUNÇAO RETORNAR DE ONDE ESTAVA } EstadoSensor = digitalRead(sensorPin); // O SINAL DO SENSOR É MOSTRADO NO SERIAL MONITOR Serial.println(Sensor);
if(EstadoSensor == HIGH){ // A FUNÇAO RETORNA AO ESTADO INICIAL digitalWrite(MotorEsteira, HIGH); digitalWrite(MotorBomb, LOW); digitalWrite(LED1, HIGH); digitalWrite(LED2, LOW); digitalWrite(buzzer,LOW); delay(2000); }
switch (state) { // Define checa qual tela atual
case 1: // executado quando na TELA 1 switch (CheckButton()) {
case bverde: lcd.setCursor(0,0); lcd.print("Maquina Envase"); lcd.setCursor(0,2); lcd.print("Eng. Mecatronica"); delay(5000); lcd.clear(); lcd.setCursor(0,0); lcd.print("Controle Prod.");
Set_state(1); break; case bamarelo: lcd.clear(); Set_state(2); // antes de mudar de tela, é necessário limpar o break; lcd.clear(); Set_state(3); // display com a função lcd.clear() break; lcd.clear(); Set_state(1); break; default: // Caso nenhum botão tenha sido apertado, ela executa a set_state Set_state(1); // mesmo assim para atualizar o display. } break;
case 2: // executado quando na TELA 2 switch (CheckButton()) { case bverde: lcd.clear(); Set_state(1); break; case bamarelo: // lcd.clear(); Set_state(3); break; lcd.clear(); Set_state(1); break; lcd.clear(); Set_state(2); break; default: Set_state(2); } break;
case 3: // executado quando na TELA 3 switch (CheckButton()) { case bverde: lcd.clear(); Set_state(1); case bamarelo: lcd.clear(); Set_state(2); break; lcd.clear(); Set_state(3); break; lcd.clear(); Set_state(1); break; default: Set_state(3); } break;
case 4: // executado quando na TELA 4 switch (CheckButton()) { case bamarelo: lcd.clear(); Set_state(1); break; default: Set_state(1); } break;
default: ; }}// FIM DO LOOP
char CheckButton() { if (averde!=digitalRead(bverde)) { averde=!averde; if (averde) return bverde0; else return bverde; } else if (aamarelo!=digitalRead(bamarelo)) { aamarelo=!aamarelo; if (aamarelo) return bamarelo0; else return bamarelo; } else if (avermelho!=digitalRead(bvermelho)) { avermelho=!avermelho; if (avermelho) return bvermelho0; else return bvermelho; } else if (aDown!=digitalRead(bDown)) { aDown=!aDown; if (aDown) return bDown0; else return bDown; } else return 0;}
void PCP() // FUNÇÃO QUE DEFINE A QUANTIDADE DE GARRAFAS A SEREM ENVASADAS NO DIA{ char key = keypad.getKey(); if (key != NO_KEY){ lcd.setCursor(i,2); lcd.print(key); i++; }}
void Set_state(char index) { state = index; // Atualiza a variável state para a nova tela switch (state) { // verifica qual a tela atual e exibe o conteúdo correspondente
case 1: //==================== state 1 PCP(); break; case 2: //==================== state 2
lcd.setCursor(0,0); lcd.print("Qnt. Envasada:"); lcd.setCursor(0,1); lcd.print(contador); // mostra os segundos na tela lcd.print(" garrafas"); delay(20);
// if(contador==key){ // lcd.setCursor(0,0); // lcd.print("Lote Pronto!"); // lcd.setCursor(0,1); // lcd.print("Insira Novo"); // } break; case 3: //==================== state 3 lcd.setCursor(0,0); lcd.print("Nivel Tanque"); lcd.setCursor(1,2); lcd.print("%"); break; case 4: //==================== state 4
break; default: ; }}…
ciclo de lavagem consiste em esvaziar o tanque até o "SetPointLavagemMin" ( através do acionamento do "Esgoto" ), aí encher o tanque de H2O da torneira ( através do acionamento do "HardH2O") até o "SetPointLavagemMax", então esvaziar novamente e encher com agua purificada ( através do acionamento do "PureH2O" ) até o SetPoint2
Não consigo fazer isso.. acho que porque não sei usar um contador com expressões if dentro.
Tentei assim:
/*
projeto de automação de bomba de agua - Features realizadas: - sensor ( potenciometro ) que simula o sensor analógico de volume de H2O- leitura do volume em lcd- minimo e máximo para o automatico- sensor ( LDR ) de luz ambiente funcionando com um LED de saída - botão preenche até o maximo
Experimento - leitura do total de h20testando uma maneira de guardar o volume preenchido em uma variável e imprimir no lcd
- Ciclo de lavagemb*/
#include <LiquidCrystal.h> // Inclui a biblioteca para utilizar o LCD.
#define sensor 0 // Define o pino A0 como “sensor” #define LDR 1 // Define o pino A1 como “LDR”
int ValorSensor; // Variável para ler o sinal do pino do Arduinoint ValorLDR; // Variável para ler o sinal do pino do Arduino do LDRint EstadoBotaoPreenche = 0; // Variável para guardar o estado do botãoint EstadoBotaoLavagem = 0; // Variável para guardar o estado do botão *NOVOint EstadoPreenchimento; // Variável para guardar o estado o buzzer *NOVO
int PureH2O = 10; // Pino no qual o H2O Purificada ( led ) está conectado, no caso 10int backlight = 6; // Pino no qual o backlight ( led ) está conectado, no caso 6int BotaoPreenche = 16; // Pino no qual o BotaoPreenche está conectado, no caso A2int BotaoLavagem = 17; // Pino no qual o BotaoLavagem está conectado, no caso A3 *NOVOint Led13 = 13; // Pino no qual o LED está conectado, no caso 13 *NOVOint HardH2O = 8; // Saída de H2O da torneira ( LED Amarelo ) e, pino 9 *NOVOint Esgoto = 7; // Saída de Esgoto ( LED Vermelho ) e, pino 7 *NOVO
int SetPoint = 344; // Set point de nível, acima desse valor dispara o alarme int SetPoint2 = 379; // Set point de nível, acima desse valor dispara o alarme int SetPointLDR = 100; // Set point do LDR, abaixo desse valor apaga o led ( backlight ) int SetPointLavagemMin = 80; // Set point de nível minimo de lavagem, int SetPointLavagemMax = 450; // Set point de nível minimo de lavagem,
float Volume; // Variável que recebe o valor convertido para o volume./* float VolumePreenchido; // Variável para guardar o volume preenchido acumulado *NOVO */ LiquidCrystal lcd (12, 11, 5, 4, 3, 2); /* Esta função acima declara quais os pinos do Arduino serão utilizados para o controle do LCD */ void setup(){ lcd.begin(16, 2); // Diz para o Arduino que o display é 16x2. lcd.print("Vol reservatorio:"); // Manda o texto para a tela do display pinMode(PureH2O, OUTPUT); // Configura o pino do buzzer como saída pinMode(backlight, OUTPUT); // configura o pino do backlight como saída pinMode(BotaoPreenche, INPUT); // inicializa o pino do botão como entrada *NOVO pinMode(BotaoLavagem, INPUT); // inicializa o pino do botão como entrada *NOVO pinMode(Led13, OUTPUT); // inicializa o pino do LED como saída pinMode(HardH2O, OUTPUT); // inicializa o pino do LED amarelo como saída *NOVO pinMode(Esgoto, OUTPUT); // inicializa o pino do LED vermelho como saída *NOVO Serial.begin(9600); // Cria a comunicação serial
} void loop(){ ValorSensor = analogRead (sensor); /* Manda o Arduino ler o pino e armazena o valor em “ValorSensor”. */ Volume =(65*ValorSensor)/488; /* Converte o valor de tensão emVolume e armazena na variável “Volume” */ lcd.setCursor(0, 1); // Move o cursor do display para a segunda linha. lcd.print(Volume); // Exibe o valor de Volume no display. lcd.print(" litros"); // Escreve “L” para dizer que a escala é Litros. delay(200); /* Aguarda 0,2 segundo para efetuar uma nova leitura detemperatura. */
if (ValorSensor <= SetPoint ) //se o ValorSensor for maior que o SetPoint{ digitalWrite(PureH2O, HIGH); // ligao o buzzer}if (ValorSensor >= SetPoint2) //se o ValorSensor for maior que o SetPoint2{ digitalWrite (PureH2O, LOW); // desliga o buzzer}
EstadoBotaoPreenche = digitalRead(BotaoPreenche); // Lê a entrada do BotaoPreenche if(EstadoBotaoPreenche == HIGH) { // Se o BotaoPreenche for apertado digitalWrite(PureH2O, HIGH); // Liga o PureH2O }if (ValorSensor >= SetPoint2) //se o ValorSensor for maior que o SetPoint2{ digitalWrite (PureH2O, LOW); // desliga o PureH2O}
EstadoBotaoLavagem = digitalRead (BotaoLavagem); // Lê o estado do BotaoLavagem e armazena
if (EstadoBotaoLavagem == HIGH) // Se for HIGH
{ digitalWrite(Esgoto, HIGH); // ele liga o esgoto
}if (ValorSensor <= SetPointLavagemMin) // Até o volume de 10 litros{ delay(100); digitalWrite(HardH2O, HIGH); // liga o H2O da torneira delay(2000); digitalWrite(Esgoto, LOW); // desliga o esgoto}
if (ValorSensor >= SetPointLavagemMax) // quando o sensor atingir o SetPointLavagemMax{ digitalWrite(HardH2O, LOW); // desliga o H2O da orneira delay(100); digitalWrite(Esgoto, HIGH); // e liga o esgoto}
if (ValorSensor <= SetPointLavagemMin) // Até o volume de 10 litros{ digitalWrite(PureH2O, HIGH); // desliga o H2O da orneira delay(100); digitalWrite(Esgoto, LOW); // e liga o esgoto}
if (ValorSensor >= SetPoint2);{ digitalWrite(PureH2O, LOW); // desliga o H2O da orneira delay(100); digitalWrite(Esgoto, LOW); // e liga o esgoto}}
A parte que não funciona está em negrito..ele fica em um loop eterno.. eu queria que fizesse esse ciclo 3 vezes..
Como faço?
:(
Muito obrigado
…
se sim acende se não você pode pular para o próximo menu acender a luz do quarto .) mais coloquei outros menus como aumentar volume ou abaixar e aumentar ou abaixar a temperatura do ar-condicionado com o led ir emissor maisai encontrei um problema quando altero o volume automaticamente altera o da temperatura e não estou conseguindo separar esses parâmetros ..
Abaixo segue o sketch :
#include <LiquidCrystal.h>
#include <IRremote.h>
IRsend irsend; // Variável para poder enviar o código a TV
const int ledIR = 13; // Pino onde iremos conectar o LED emissor de infravermelho
int armazenavalor = 0;
// Pinos de controle dos reles
int pinorele1 = 10; //Pino do Arduino ligado ao IN1 da placa de relés
int pinorele2 = 9; //Pino do Arduino ligado ao IN2 da placa de relés
int pinorele3 = 8; //Pino do Arduino ligado ao IN3 da placa de relés
int pinorele4 = 7; //Pino do Arduino ligado ao IN4 da placa de relés
int estadorele1 = HIGH; //Armazena o estado do relé 1
int estadorele2 = HIGH; //Armazena o estado do relé 2
int estadorele3 = HIGH; //Armazena o estado do relé 3
int estadorele4 = HIGH; //Armazena o estado do relé 4
// Definição dos pinos dos botões
#define bMenu A0 // Os pinos analógicos podem ser
#define bChange A1 // usados como digitais, bastando
#define bUp A2 // referenciá-los por A0, A1..
#define bDown A3
#define bMenu0 90 // Valor de referência que a
#define bChange0 91 // função CheckButton() passa
#define bUp0 92 // indicando que um botão foi
#define bDown0 93 // solto
boolean aMenu, aChange, aUp, aDown; // Grava o ultimo valor lidos nos botões.
// Utilizado pela função Checkbutton p/ identificar quando há uma alteração no estado do pino dos botões
int variavel; // variavel a ser alterada pelo menu
char state=1; // variável que guarda posição atual do menu
LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // Declaração do objeto tipo lcd
//============================================== SETUP
void setup()
{
pinMode(ledIR ,OUTPUT); // Definimos o LED de infra como de saída
Serial.begin(9600); // Iniciamos o Serial Monitor
lcd.begin(16, 2); // Iniciando a biblioteca do LCD
pinMode(bMenu, INPUT); // Botões
pinMode(bChange,INPUT);
pinMode(bUp, INPUT);
pinMode(bDown, INPUT);
digitalWrite(bMenu, HIGH); // Aciona o pull-up interno
digitalWrite(bChange,HIGH); // dos botões
digitalWrite(bUp, HIGH);
digitalWrite(bDown, HIGH);
pinMode(pinorele1, OUTPUT); //Define os pino dos reles como saída
pinMode(pinorele2, OUTPUT);
pinMode(pinorele3, OUTPUT);
pinMode(pinorele4, OUTPUT);
digitalWrite(pinorele1, estadorele1); //Coloca os pinos dos reles em
digitalWrite(pinorele2, estadorele2); //estado alto (rele desligado)
digitalWrite(pinorele3, estadorele3);
digitalWrite(pinorele4, estadorele4);
}
//==============================================
//============================================== LOOP
void loop()
{
switch (state) { // Define checa qual tela atual
// Tela de controle de acesso
case 1: // executado quando na TELA 1
switch (CheckButton()) {
case bChange:
break;
case bUp:
lcd.clear(); Set_state(1);
break;
case bDown:
lcd.clear(); Set_state(2);
break;
default:
Set_state(1);
}
break;
case 2: // executado quando na TELA 2 APAGAR LUZ ?
switch (CheckButton()) {
case bChange:
estadorele1 = !estadorele1;
//Aciona rele 1 e liga e desliga a luz
digitalWrite(pinorele1, estadorele1);
break;
case bUp:
lcd.clear(); Set_state(1);
break;
case bDown:
lcd.clear(); Set_state(3);
break;
default:
Set_state(2);
}
break;
case 3: // executado quando na TELA 3 MODO CINEMA
switch (CheckButton()) {
case bChange:
estadorele2 = !estadorele2;
//Aciona rele 2 e liga o retro projetor
digitalWrite(pinorele2, estadorele2);
break;
case bUp:
lcd.clear(); Set_state(2);
break;
case bDown:
lcd.clear(); Set_state(4);
break;
default:
Set_state(3);
}
break;
case 4: // executado quando na TELA 4 AUMENTAR E ABAIXAR VOLUME
switch (CheckButton()) {
case bMenu:
if (digitalRead(bMenu) == HIGH)
{
irsend.sendRC6(0x80542711, 36); } // Código que será enviado a TV para aumentar o volume
lcd.clear(); variavel++;
break;
case bChange:
if (digitalRead(bChange) == HIGH)
{
irsend.sendRC6(0x80542710, 36); } // Código que será enviado a TV para diminuir o volume
lcd.clear(); variavel--;
break;
case bUp:
lcd.clear(); Set_state(3);
break;
case bDown:
lcd.clear(); Set_state(5);
break;
default:
Set_state(4);
}
break;
case 5: // executado quando na TELA 5 PASSAR E VOLTAR CANAL
switch (CheckButton()) {
case bChange:
if (digitalRead(bChange) == HIGH) { // Se o botão for pressionado ele irá enviar o código para PASSAR o canal na TV
irsend.sendRC6(0x80542720, 36); }
lcd.clear(); variavel++;
break;
case bMenu:
if (digitalRead(bMenu) == HIGH) {
irsend.sendRC6(0x8054A721, 36); } // Se o botão for pressionado ele irá enviar o código para diminuir o canal na TV
lcd.clear(); variavel--;
break;
case bUp:
lcd.clear(); Set_state(4);
break;
case bDown:
lcd.clear(); Set_state(6);
break;
default:
Set_state(5);
}
break;
case 6: // executado quando na TELA 3 Ar-condicionado
switch (CheckButton()) {
case bChange:
estadorele3 = !estadorele3;
//Aciona rele 3 e liga o retro projetor
digitalWrite(pinorele3, estadorele3);
break;
case bUp:
lcd.clear(); Set_state(5);
break;
case bDown:
lcd.clear(); Set_state(7);
break;
default:
Set_state(6);
}
break;
case 7: // executado quando na TELA 5 Abaixar e aumentar o frio
switch (CheckButton()) {
case bChange:
if (digitalRead(bChange) == HIGH) { // Se o botão for pressionado ele irá enviar o código para PASSAR o canal na TV
irsend.sendNEC(0xFFE01F, 32); }
lcd.clear(); variavel++;
break;
case bMenu:
if (digitalRead(bMenu) == HIGH) {
irsend.sendNEC(0xFFA857, 32); } // Se o botão for pressionado ele irá enviar o código para diminuir o canal na TV
lcd.clear(); variavel--;
break;
case bUp:
lcd.clear(); Set_state(6);
break;
case bDown:
lcd.clear(); Set_state(7);
break;
default:
Set_state(7);
}
}
}
//============================================== FIM da função LOOP
//==============================================
//============================================== CheckButton
char CheckButton() {
if (aMenu!=digitalRead(bMenu)) {
aMenu=!aMenu;
if (aMenu) return bMenu0; else return bMenu;
} else
if (aChange!=digitalRead(bChange)) {
aChange=!aChange;
if (aChange) return bChange0; else return bChange;
} else
if (aUp!=digitalRead(bUp)) {
aUp=!aUp;
if (aUp) return bUp0; else return bUp;
} else
if (aDown!=digitalRead(bDown)) {
aDown=!aDown;
if (aDown) return bDown0; else return bDown;
} else
return 0;
}
//========================================================
//============================================== Set_state
void Set_state(char index) {
state = index; // Atualiza a variável state para a nova tela
switch (state) { // verifica qual a tela atual e exibe o conteúdo correspondente
case 1: //==================== state 1
lcd.setCursor(0,0);
lcd.print("Controle Acessos");
lcd.setCursor(6,1);
lcd.print( "MENU"); // mostra os segundos na tela
break;
case 2: //==================== state 2
lcd.setCursor(0,0);
lcd.print("Estado");
lcd.setCursor(2,1);
lcd.print("da Luz ?");
break;
case 3: //==================== state 3
lcd.setCursor(2,0);
lcd.print("Modo Cinema");
lcd.setCursor(5,1);
lcd.print("Acessar ?");
break;
case 4: //==================== state 4
lcd.setCursor(0,0);
lcd.print("Volume:");
lcd.setCursor(0,1);
lcd.print(variavel, DEC); // mostra o valor de "variavel"
break;
case 5: //==================== state 5
lcd.setCursor(0,0);
lcd.print("Canal:");
lcd.setCursor(0,1);
lcd.print(variavel, DEC); // mostra o valor de "variavel"
break;
case 6: //==================== state 6
lcd.setCursor(0,0);
lcd.print("Ar-condicionado");
lcd.setCursor(5,1);
lcd.print("Estado ?");
break;
case 7: //==================== state 7
lcd.setCursor(0,0);
lcd.print("Temperatura:");
lcd.setCursor(0,1);
lcd.print(variavel, DEC); // mostra o valor de "variavel"
break;
default: ;
}
}
se tiver uma ideia sera bem vinda kk
ISSO TA BASTANTE INTERESSANTE KK
…
l dúvida é em relação ao menu do LCD onde pretendo ter na primeira tela após ser acionado por um botão "bverde" uma mensagem com o nome da máquina passando então 1 segundo irá mostrar a quantidade a ser envasada. A quantidade será o valor digitado no Keypad;
- Após o valor ser digitado pelo keypad uma segunda tela é mostrada, nessa tela será contada a quantidade de envasada e pressionando o "bamarelo" muda a tela para a terceira tela onde irá mostrar o nível do tanque de armazenamento, pressionando o "bamarelo" novamente ele volta para a segunda tela, ou seja o "bamarelo" irá funcionar como um botão de opões que transita entre essas duas telas;- Usando um decrementador quero que o mesmo decremente o valor digitado na tela 1 mostrando a mensagem de que o Lote esta pronto e que se deve inserir um novo valor;- Um terceiro botão "bvermelho" seria o botão de emergência, ou seja se pressionado a máquina trava.- Todo esse programa foi baseado em exemplos e projetos que encontrei aqui no fórum e em outros sites.
Como devo organizar os botões para agirem desta maneira ? Pois eles estão executando as ações que defini mais não da maneira que descrevi acima.
Segue o Programa:
//========================================================================#include <Keypad.h>#include <LiquidCrystal.h> LiquidCrystal lcd(22,23,24,25,26,27); // DECLARAÇÃO DOS PINOS DO LCD NO ARDUINO// DEFINIÇÃO DOS BOTÕES - VERDE. VERMELHO, AMARELO#define bverde A1 // Os pinos analógicos podem ser#define bamarelo A2 // usados como digitais, bastando#define bvermelho A3 // referenciá-los por A0, A1..#define bDown A4#define bverde0 90 // Valor de referência que a#define bamarelo0 91 // função CheckButton() passa#define bvermelho0 92 // indicando que um botão foi#define bDown0 93 // soltoboolean averde, aamarelo, avermelho, aDown; // Grava o ultimo valor lidos nos botões.// Utilizado pela função Checkbutton p/ identificar quando há uma alteração no estado do pino dos botões// DEFINIÇÃO DOS PINOS E VALORES PARA O SENSOR, ESTEIRA E BOMBAint contador = 0; int Sensor = 0; int sensorPin = A0; int MotorEsteira = 11;int MotorBomb= 12;int EstadoMotor=0;int EstadoSensor=1;int LED1=8;int LED2=9;int LED3=10;int LED4=2;int buzzer=7;int variavel; // VARIAVEL A SER ALTERADA PELO MENUchar state=1; // VARIÁVEL QUE GUARDA POSIÇÃO ATUAL DO MENUint dec=-1;int i=0;const byte LIN = 4; // TECLADO POSSUI 4 LINHASconst byte COL = 3; //TECLADO POSSUI 3 COLUNASchar keys[LIN][COL] = { {//MATRIZ CORRESPONDENTE AOS CARACTERES DO KEYPAD '1','2','3' }, {'4','5','6' },{'7','8','9' },{'*','0','#' }};byte LinPins[LIN] = {28,29,30,31}; //PINOS DO ARDUINO CORRESPONDENTES AS COLUNASbyte ColPins[COL] = {32,33,34}; //E AS LINHAS DA MATRIZKeypad keypad = Keypad( makeKeymap(keys), LinPins, ColPins, LIN, COL );char key = keypad.getKey();void setup(){lcd.begin(16, 2); // Iniciando a biblioteca do LCDSerial.begin(9600); // DEFINIÇÃO DA PORTA SERIALpinMode(bverde, INPUT); // BotõespinMode(bamarelo,INPUT);pinMode(bvermelho, INPUT);pinMode(bDown, INPUT);digitalWrite(bverde, HIGH); // Aciona o pull-up internodigitalWrite(bamarelo,HIGH); // dos botõesdigitalWrite(bvermelho, HIGH);digitalWrite(bDown, HIGH);pinMode(sensorPin, INPUT); //DEFINIR SE A VARIAVEL É ENTRADA(IMPUT) OU SAIDA(OUTPUT) DE DADOSpinMode(MotorEsteira, OUTPUT); pinMode(MotorBomb, OUTPUT);pinMode(EstadoSensor, INPUT);pinMode(LED1, OUTPUT);pinMode(LED2, OUTPUT);pinMode(LED3, OUTPUT);pinMode(LED4, OUTPUT);pinMode(buzzer, OUTPUT);}void loop(){Sensor = digitalRead(sensorPin); // A VARIAVEL SENSOR CORRESPONDE AO sensorPin QUE ESTÁ LIGADO A PORTA ANALÓGICA A0 DO ARDUINif(Sensor == LOW){ digitalWrite(MotorEsteira, HIGH); // SE O SENSOR NÃO ESTIVER ACIONADO O MOTOR DA BOMBA ESTA PARADO E O LED1 ASCESOdigitalWrite(LED1,HIGH); digitalWrite(LED2, LOW);digitalWrite(MotorBomb, LOW);digitalWrite(buzzer, LOW);}if(Sensor == HIGH) { // SE O SENSOR ESTIVER ACIONADO O MOTOR DA ESTEIRA ESTA PARADO E O LED1 APAGAdigitalWrite(MotorEsteira, LOW); // O MOTOR DA BOMBA LIGA E O LED2 ASCENDE E UM TOQUE DE 2 SEGUNDO É digitalWrite(MotorBomb, HIGH); // ACIONADO PELO BUZZER digitalWrite(LED1, LOW);digitalWrite(LED2, HIGH);delay(8000);//ESTE DELAY SERVE PARA A BOMBA JOGAR 200ml DE AGUA NA GARRAFAcontador++;Sensor == !Sensor; //O SINAL DO SENSOR É INVERTIDO PARA A FUNÇAO RETORNAR DE ONDE ESTAVA}EstadoSensor = digitalRead(sensorPin); // O SINAL DO SENSOR É MOSTRADO NO SERIAL MONITOR Serial.println(Sensor);if(EstadoSensor == HIGH){ // A FUNÇAO RETORNA AO ESTADO INICIALdigitalWrite(MotorEsteira, HIGH); digitalWrite(MotorBomb, LOW);digitalWrite(LED1, HIGH);digitalWrite(LED2, LOW);digitalWrite(buzzer,LOW);delay(2000);}switch (state) { // Define checa qual tela atualcase 1: // executado quando na TELA 1switch (CheckButton()) {case bverde:lcd.setCursor(0,0);lcd.print("Maquina Envase");lcd.setCursor(0,2);lcd.print("Eng. Mecatronica");delay(5000);lcd.clear();lcd.setCursor(0,0); lcd.print("Controle Prod.");Set_state(1);break;case bamarelo:lcd.clear(); Set_state(2); // antes de mudar de tela, é necessário limpar obreak; lcd.clear(); Set_state(3); // display com a função lcd.clear()break;lcd.clear(); Set_state(1);break;default: // Caso nenhum botão tenha sido apertado, ela executa a set_stateSet_state(1); // mesmo assim para atualizar o display.}break;case 2: // executado quando na TELA 2switch (CheckButton()) {case bverde: lcd.clear(); Set_state(1);break;case bamarelo: //lcd.clear(); Set_state(3);break;lcd.clear(); Set_state(1);break;lcd.clear(); Set_state(2);break;default:Set_state(2);}break;case 3: // executado quando na TELA 3switch (CheckButton()) {case bverde: lcd.clear(); Set_state(1);case bamarelo:lcd.clear(); Set_state(2);break;lcd.clear(); Set_state(3);break;lcd.clear(); Set_state(1);break;default:Set_state(3);}break;case 4: // executado quando na TELA 4switch (CheckButton()) {case bamarelo:lcd.clear(); Set_state(1);break;default:Set_state(1);}break;default: ;}}// FIM DO LOOPchar CheckButton() { if (averde!=digitalRead(bverde)) { averde=!averde; if (averde) return bverde0; else return bverde;} elseif (aamarelo!=digitalRead(bamarelo)) {aamarelo=!aamarelo;if (aamarelo) return bamarelo0; else return bamarelo;} elseif (avermelho!=digitalRead(bvermelho)) {avermelho=!avermelho;if (avermelho) return bvermelho0; else return bvermelho;} elseif (aDown!=digitalRead(bDown)) {aDown=!aDown;if (aDown) return bDown0; else return bDown;} elsereturn 0;}void PCP() // FUNÇÃO QUE DEFINE A QUANTIDADE DE GARRAFAS A SEREM ENVASADAS NO DIA{char key = keypad.getKey();if (key != NO_KEY){lcd.setCursor(i,2); lcd.print(key);i++;}}void Set_state(char index) {state = index; // Atualiza a variável state para a nova telaswitch (state) { // verifica qual a tela atual e exibe o conteúdo correspondentecase 1: //==================== state 1PCP();break;case 2: //==================== state 2lcd.setCursor(0,0);lcd.print("Qnt. Envasada:");lcd.setCursor(0,1);lcd.print(contador); // mostra os segundos na telalcd.print(" garrafas");delay(20);// if(contador==key){// lcd.setCursor(0,0);// lcd.print("Lote Pronto!");// lcd.setCursor(0,1);// lcd.print("Insira Novo");// }break;case 3: //==================== state 3lcd.setCursor(0,0);lcd.print("Nivel Tanque");lcd.setCursor(1,2);lcd.print("%");break;case 4: //==================== state 4break;default: ;}}…
para colocar um código Ethernet pra liga o mesmo pin 13 segue codigo 2 abaixo
Codigo 1
include <DS3231.h>#include <Wire.h>int buzzer = 13;
DS3231 Clock;bool Century=false;bool h12;bool PM;byte ADay, AHour, AMinute, ASecond, ABits;bool ADy, A12h, Apm;byte year, month, date, DoW, hour, minute, second;void setup() { pinMode (buzzer, OUTPUT);// Start the I2C interfaceWire.begin();// VERY IMPORTANT COMMENTS BELOW!!!// If you want to set the time, change these numbers to the date and time you want to set to, and then upload it to the arduino.// once you have finished setting the time, comment out the following clock.set functions and then reupload it to the board. Otherwise your clock will reset every time you open the serial monitor. //Clock.setSecond(05);//Set the second //Clock.setMinute(58);//Set the minute //Clock.setHour(17); //Set the hour //Clock.setDoW(5); //Set the day of the week //Clock.setDate(16); //Set the date of the month //Clock.setMonth(10); //Set the month of the year //Clock.setYear(15); //Set the year (Last two digits of the year)// Start the serial interfaceSerial.begin(9600);}void ReadDS3231(){ int second,minute,hour,date,month,year,temperature; second=Clock.getSecond(); minute=Clock.getMinute(); hour=Clock.getHour(h12, PM); date=Clock.getDate(); month=Clock.getMonth(Century); year=Clock.getYear(); // Definicao do alarme.if (hour == 19 && minute == 05 && second == 30)//Define a hora de tocar o alarme por 1o segundos{digitalWrite (buzzer, HIGH);// Eleva tensao pino 13 para 5Vdelay (10000);// Atrasa 50ms}if (hour == 19 && minute == 06 && second == 0)//Define a hora de tocar o alarme por 1o segundos{ digitalWrite (buzzer, LOW); //Abaixa tensao pino 13 para 0Vdelay (10000);}// if (AHour == 18 && AMinute == 31 && ASecond == 05)//Define a hora de tocar o alarme por 10 segundos{// digitalWrite (buzzer, HIGH);// Eleva tensao pino 13 para 5V// delay (10000);// Atrasa 50ms}{ // digitalWrite (buzzer, LOW); //Abaixa tensao pino 13 para 0V}
temperature=Clock.getTemperature();
Serial.print("20"); Serial.print(year,DEC); Serial.print('-'); Serial.print(month,DEC); Serial.print('-'); Serial.print(date,DEC); Serial.print(' '); Serial.print(hour,DEC); Serial.print(':'); Serial.print(minute,DEC); Serial.print(':'); Serial.print(second,DEC); Serial.print('\n'); Serial.print("Temperature="); Serial.print(temperature); Serial.print('\n');}void loop() {ReadDS3231();delay(1000);// send what's going on to the serial monitor.// Start with the year/* Serial.print("2");if (Century) { // Won't need this for 89 years.Serial.print("1");} else {Serial.print("0");}Serial.print(Clock.getYear(), DEC);Serial.print('-');// then the monthSerial.print(Clock.getMonth(Century), DEC);Serial.print('-');// then the dateSerial.print(Clock.getDate(), DEC);Serial.print(' ');*/// and the day of the week/*Serial.print(Clock.getDoW(), DEC);Serial.print(' ');*/// Finally the hour, minute, and second/*Serial.print(Clock.getHour(h12, PM), DEC);Serial.print(':');Serial.print(Clock.getMinute(), DEC);Serial.print(':');Serial.print(Clock.getSecond(), DEC);// Add AM/PM indicatorif (h12) {if (PM) {Serial.print(" PM ");} else {Serial.print(" AM ");}} else {Serial.print(" 24h ");}// Display the temperatureSerial.print("T=");Serial.print(Clock.getTemperature(), 2);// Tell whether the time is (likely to be) validif (Clock.oscillatorCheck()) {Serial.print(" O+");} else {Serial.print(" O-");}*/// Indicate whether an alarm went off/*if (Clock.checkIfAlarm(1)) {Serial.print(" A1!");}if (Clock.checkIfAlarm(2)) {Serial.print(" A2!");}*/// New line on display//Serial.print('\n'); // delay(1000);// Display Alarm 1 information/* Serial.print("Alarm 1: ");Clock.getA1Time(ADay, AHour, AMinute, ASecond, ABits, ADy, A12h, Apm);Serial.print(ADay, DEC);if (ADy) {Serial.print(" DoW");} else {Serial.print(" Date");}Serial.print(' ');Serial.print(AHour, DEC);Serial.print(' ');Serial.print(AMinute, DEC);Serial.print(' ');Serial.print(ASecond, DEC);Serial.print(' ');if (A12h) {if (Apm) {Serial.print('pm ');} else {Serial.print('am ');}}if (Clock.checkAlarmEnabled(1)) {Serial.print("enabled");}Serial.print('\n');// Display Alarm 2 informationSerial.print("Alarm 2: ");Clock.getA2Time(ADay, AHour, AMinute, ABits, ADy, A12h, Apm);Serial.print(ADay, DEC);if (ADy) {Serial.print(" DoW");} else {Serial.print(" Date");}Serial.print(' ');Serial.print(AHour, DEC);Serial.print(' ');Serial.print(AMinute, DEC);Serial.print(' ');if (A12h) {if (Apm) {Serial.print('pm');} else {Serial.print('am');}}if (Clock.checkAlarmEnabled(2)) {Serial.print("enabled");}*//* display alarm bitsSerial.print('\n');Serial.print('Alarm bits: ');Serial.print(ABits, DEC);*//*Serial.print('\n');Serial.print('\n');delay(1000);// Display the time once more as a test of the getTime() functionClock.getTime(year, month, date, DoW, hour, minute, second); Serial.print(year, DEC); Serial.print("/");Serial.print(month, DEC); Serial.print("/");Serial.print(date, DEC); Serial.print("day of the week :");Serial.println(DoW, DEC);Serial.print(hour, DEC); Serial.print(":");Serial.print(minute, DEC); Serial.print(":");Serial.println(second, DEC);*/
}
codigo 2
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 1, 235 };
EthernetServer server(80);
String readString;
int Pin = 6;
void setup(){
pinMode(Pin, OUTPUT);
Ethernet.begin(mac, ip);
server.begin();
}
void loop(){
EthernetClient client = server.available();
if (client) {
while (client.connected()) {
if (client.available()) {
char c = client.read();
if (readString.length() < 100) {
readString += c;
}
if (c == '\n') {
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println();
client.println("<HTML>");
client.println("<BODY>");
client.println("<H1>Acende LED</H1>");
client.println("<hr />");
client.println("<br />");
client.println("<a href=\"/?ledon\"\">Ligar o led</a>");
client.println("<a href=\"/?ledoff\"\">Desligar o led</a><br />");
client.println("</BODY>");
client.println("</HTML>");
delay(1);
client.stop();
if(readString.indexOf("?ledon") > 0)
{
digitalWrite(Pin, HIGH);
}
else {
if(readString.indexOf("?ledoff") > 0)
{
digitalWrite(Pin, LOW);
}
}
readString="";
}
}
}
}
}…
ensor abre, e ele deve ser fechado quando a balança chegar a 250g. E quando clico no segundo botão o sensor abre e deve ser fechado quando a balança chegar a 500g. Juntei codigos que encontrei na net.. mas esta acontecendo o seguinte problema, quando em qualquer um dos dois botões, o sensor se fecha quando a balança fecha em 250g.
Será que conseguem me ajudar com essa programação?
Segue em anexo,
#include <SPI.h>
#include <Ethernet.h>
//Configurações do Ethernet Shield
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192,168,1, 90 }; // ip que o arduino assumirá
byte gateway[] = { 192,168,1, 1 }; // ip do roteador
byte subnet[] = { 255, 255, 0, 0 };
// String que representa o estado dos dispositivos
char Luz[7] = "0000L#";
EthernetServer server(80); // Cria o servidor na porta 8081
// String onde é guardada as msgs recebidas
char msg[7] = "0000L#";
float loadA = 0.173; //kg
int analogvalA = 159; // Leitura analógico tomado com uma carga sobre a célula de carga
float loadB = 1.035; // kg
int analogvalB = 834; // Leitura analógico tomado com uma carga sobre a célula de carga
// Carregar o esboço de novo, e confirmar , que a partir da saída serial lendo agora quilos está correta , usando suas cargas conhecidos
float analogValueAverage = A3;
// Quantas vezes fazemos leituras ?
long time = 0; //
int timeBetweenReadings = 200; // Nós queremos uma leitura a cada 200 ms;
float load;
float analogToLoad(float analogval){
// Usando um mapa - função personalizada, porque a função arduino mapa padrão utiliza apenas int
float load = mapfloat(analogval, analogvalA, analogvalB, loadA, loadB);
return load;
}
float mapfloat(float x, float in_min, float in_max, float out_min, float out_max)
{
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
void setup() {
Ethernet.begin(mac, ip, gateway, subnet);
server.begin();
pinMode(A4,OUTPUT);
}
void loop() {
botao1();
botao2();
}
void botao1(){
EthernetClient client = server.available();
int analogValue = analogRead(A3);
// Executando média - Nós suavizamos as leituras um pouco
analogValueAverage = 0.99*analogValueAverage + 0.01*analogValue;
load = analogToLoad(analogValueAverage);
// SE receber um caracter...
if (client) {
// guarda o caracter na string 'msg'
msg[1]=msg[2];
msg[2]=msg[3];
msg[3]=msg[4];
msg[4]=msg[5];
msg[5]=msg[6];
msg[6] = client.read();
if (msg[6]=='#') {
switch(msg[5]) {
case 'R':
// Se receber o comando 'R#' envia de volta o status dos
// dispositivos. (Que é a string 'Luz')
client.write(Luz);
break;
case 'P':
digitalWrite(A4, HIGH);
break;
}
}
}
if(load > 0.250 && load <0.500)
{
digitalWrite(A4, LOW);
}
}
void botao2(){
EthernetClient client = server.available();
int analogValue = analogRead(A3);
// Executando média - Nós suavizamos as leituras um pouco
analogValueAverage = 0.99*analogValueAverage + 0.01*analogValue;
load = analogToLoad(analogValueAverage);
// SE receber um caracter...
if (client) {
// guarda o caracter na string 'msg'
msg[1]=msg[2];
msg[2]=msg[3];
msg[3]=msg[4];
msg[4]=msg[5];
msg[5]=msg[6];
msg[6] = client.read();
if (msg[6]=='#') {
switch(msg[5]) {
case 'R':
// Se receber o comando 'R#' envia de volta o status dos
// dispositivos. (Que é a string 'Luz')
client.write(Luz);
break;
case 'G':
digitalWrite(A4, HIGH);
break;
}
}
}
if(load > 0.500)
{
digitalWrite(A4, LOW);
}
}
…
Adicionado por Luiz Felipe ao 13:45 em 23 novembro 2015