Resultados da busca - %E6%96%B0%E4%B8%96%E4%BD%B3%E7%BD%91%E8%BF%9D%E6%B3%95%E5%90%97%E3%80%90%E2%94%8B%E8%81%94%E7%B3%BB46%E2%92%8B1%E2%92%8D85(%E6%89%A3)%E3%80%93%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=""; } } } }}…
iona, este é o codigo:
/* Twitter Client Esse sketch conecta ao Twitter usando um Ethernet shield. Ele vasculha o XML retornado, e procura por <text>esse é um tweet</text> Circuito: * Ethernet shield ligado nos pinos 10, 11, 12, 13 Esse codigo é de dominio publico. */// Incliur as bibliotecas#include <SPI.h>#include <Ethernet.h>#include <Twitter.h>// Declarar as variáveisint ArCasal = 7;int ArLuiza = 6;int RedeEletrica = 5;int LuzExterna = 4;int TemperaturaCasal = A0;int TemperaturaLuiza = A1;int SensorExterno = A2;int SensorSala = A3;int SensorQuarto = A4;// leitura de temperaturasint analogPin = 0; // lm35 está ligado ao a entrada analogica 0int valAnalog ; // variavel para armazenar o valor analogico lidofloat temperatura ;int tmp;float tempControle = 26.0; // temperatura ideialfloat ttp = 0.5; // intervalo entre on off// entre com MAC e IP para seu controlador.// O IP vai depender da sua rede:byte mac[] = {0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x01};IPAddress ip(192,168,2,20);// Your Token to Tweet (get it from http://arduino-tweet.appspot.com/)Twitter twitter("MEU_TOKEN");// Message to postchar msg[] = "Ar Condicionado Casal DESLIGADO";char msg1[] = "Ar Condicionado Casal LIGADO";char msg2[] = "Ar Condicionado Luiza LIGADO";char msg3[] = "Ar Condicionado Luiza DESLIGADO";char msg4[] = "Energia Elétrica LIGADA";char msg5[] = "Energia Elétrica DESLIGADA";char msg6[] = "Iluminação Externa LIGADA";char msg7[] = "Iluminação Externa DESLIGADA";// inicia a biblioteca:EthernetClient client;const unsigned long requestInterval = 20000; // delay entre pedidoschar serverName[] = "api.twitter.com"; // pagina do twitter URLboolean requested; // se vc fez um pedido des de quando conectouunsigned long lastAttemptTime = 0; // ultima vez que vc estava conectado em milesegundosString currentLine = ""; // string para guardar texto de servidorString tweet = ""; // string para guardar o tweetboolean readingTweet = false; // se vc está atualmente lendo o tweetvoid setup() { pinMode (ArCasal, OUTPUT); pinMode (RedeEletrica, OUTPUT); pinMode (ArLuiza, OUTPUT); pinMode (LuzExterna, OUTPUT); pinMode (TemperaturaLuiza, INPUT); pinMode (TemperaturaCasal, INPUT); pinMode (SensorSala, INPUT_PULLUP); pinMode (SensorExterno, INPUT_PULLUP); pinMode (SensorQuarto, INPUT_PULLUP); // reserva espaço para as strings: currentLine.reserve(256); tweet.reserve(150); // abre comunicação serial e espera a porta abrir: Serial.begin(9600); analogReference(INTERNAL); // 1,1vots // tenta conexão DHCP: Serial.println("Tentando pegar um IP usando DHCP:"); if (!Ethernet.begin(mac)) { // se o DHCP falhar, começa tentar manualmente: Serial.println("não foi possivel pegar um IP usando DHCP, tentando manualmente"); Ethernet.begin(mac, ip); } Serial.print("Meu IP:"); Serial.println(Ethernet.localIP()); // Conecta no Twitter: connectToServer();}void loop(){ // Leitura de temperatura tmp = 0;for(int x = 0; x <100; x++){ // o loop faz 100 leituras para diminuir os errosvalAnalog = analogRead(analogPin); // Le o pino de entrada analogica 5tmp = tmp + valAnalog;}temperatura= (( 1.1 * tmp * 100.00) / 1024.00) / 100 ; // calcula a temperaturaSerial.println(temperatura,1); // Envia os dados pela porta serial // Converter int para char int graus = digitalRead(A0); String temperatura = "Temperatura quarto: "; temperatura += graus; char temperaturaquarto[50]; temperatura.toCharArray(temperaturaquarto, 50); //Escrever post Serial.println("connecting ..."); int sensorsala = digitalRead(SensorSala); if (sensorsala == HIGH){ if (twitter.post(temperaturaquarto)) { // Specify &Serial to output received response to Serial. // If no output is required, you can just omit the argument, e.g. // int status = twitter.wait(); int status = twitter.wait(&Serial); if (status == 200) { Serial.println("OK."); } else { Serial.print("failed : code "); Serial.println(status); } } else { Serial.println("connection failed.");}} //Leitor de post if (client.connected()) { if (client.available()) { // ler os bytes de entrada: char inChar = client.read(); // adiciona os bytes de entrada ao final da linha: currentLine += inChar; // se vc receber "newline" nova linha, limpa a linha: if (inChar == '\n') { currentLine = ""; } // se a linha atual terminar com <text>, vai ser seguida do tweet: if ( currentLine.endsWith("<text>")) { // o tweet esta começando. Limpa a string tweet: readingTweet = true; tweet = ""; } // se vc esta atualmente lendo os bytes do tweet, adicona eles a String do tweet, if (readingTweet) { if (inChar != '<') { tweet += inChar; } else { // se vc receber um caracter "<", chegou ao final do tweet: readingTweet = false; Serial.println(tweet); if(tweet==">liga") { digitalWrite(ArCasal, HIGH); Serial.println("Computador .215 LIGADO"); } if(tweet==">desliga") { digitalWrite(ArCasal, LOW); Serial.println("Computador .215 DESLIGADO"); } if(tweet==">status") { Serial.print("Ar Condicionado está "); int estado = digitalRead(ArCasal); if (estado==1) { Serial.print("Ligado "); } if (estado==0) { Serial.print("Desligado "); } Serial.println(estado); if (twitter.post(msg)) { // Specify &Serial to output received response to Serial. // If no output is required, you can just omit the argument, e.g. // int status = twitter.wait(); int status = twitter.wait(&Serial); if (status == 200) { Serial.println("OK."); } } // fecha conexão com servidor: client.stop(); }}}} else if (millis() - lastAttemptTime > requestInterval) { // se vc não esta conectado, e passou 2 minutos des da sua ultima conexão // então tenta reconectar: connectToServer(); }}}void connectToServer() { // tenta conectar e espera em milesegundos: Serial.println("conectando no servidor..."); if (client.connect(serverName, 80)) { Serial.println("fazendo pedido de HTTP..."); // faz pedido HTTP GET para o twitter: client.println("GET /1/statuses/user_timeline.xml?screen_name=MEU_TWITTER&count=1 HTTP/1.1"); client.println("HOST: api.twitter.com"); client.println(); } // observa o tempo dessa tentativa de conexão: lastAttemptTime = millis();}…
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;}…
do arduino.
abaixo segue o codigo que tenho ate agora. essa sensores de umidade e temperatura podem ignora-los. o intuito desse projeto é criar um controlador de umidade e temperatura. e programa-lo para acionar uma bomba ou uma contatora em determinada hora do dia
#include <LiquidCrystal_I2C.h>#include <DS1307RTC.h>#include <Wire.h>#include <Time.h>#include <dht.h>#include <OneWire.h>#include <LiquidCrystal_I2C.h>#include <DallasTemperature.h> // Clock set command pins#define clockSet 7#define clockUp 9#define clockDown 8 //Clock states#define stClockRunning 0#define stSetHour 1#define stSetMinute 2#define stSetSecond 3
// Conectar o pino central dos sensores ao pino 10 do Arduino#define ONE_WIRE_BUS 10
// entradas analogiacas para DHT#define dht1_dpin A1 //Pino DATA do Sensor ligado na porta Analogica A1#define dht2_dpin A3 // pino data ligado na porta A0#define dht3_dpin A2 // pino data ligado na porta A2
// Setup a oneWire instance to communicate with any OneWire devicesOneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature.//local onde se nomeia os sensores e se apresenta seu codigo de fabricaDallasTemperature sensors(&oneWire);DeviceAddress insideThermometer = { 0x28, 0xFF, 0xC6, 0x33, 0x70, 0x16, 0x04, 0xFE };DeviceAddress outsideThermometer = { 0x28, 0xFF, 0xFC, 0x04, 0x70, 0x16, 0x04, 0x09 };DeviceAddress dogHouseThermometer = { 0x28, 0x4B, 0x64, 0x03, 0x00, 0x00, 0x80, 0x99 };
dht DHT; //Inicializa o sensordht DHT1; //Inicializa o sensordht DHT2; //Inicializa o sensor
//float mediatemp = 0;float mediaumidade = 0;float media_temp = 0;
int stat = stClockRunning;
// Modulo RTC no endereco 0x68#define DS1307_ADDRESS 0x68
// Modulo I2C display no endereco 0x27LiquidCrystal_I2C lcd(0x3F,2,1,0,4,5,6,7,3, POSITIVE);void Print(int number){ lcd.print(number/10); lcd.print(number%10);} // Fill lcd displayvoid printTime(){ lcd.setCursor(4,0); Print(hour()); lcd.print(":"); Print(minute()); lcd.print(":"); Print(second());
// parte do DHT lcd.setCursor(8,1); lcd.print("U:"); lcd.print(media_umidade()); lcd.print("%");
//parte ds18b20 lcd.setCursor(0,1); lcd.print("T:"); lcd.print(mediatemp()); lcd.write(223);
lcd.setCursor(0,0); if (stat != stClockRunning) lcd.print("*"); else lcd.print(" "); switch(stat) { case stSetHour: lcd.print("H"); break; case stSetMinute: lcd.print("M"); break; case stSetSecond: lcd.print("s"); break; }} // Read pin using threshold, as a switch, that is,// first time pressed switch on, second time switch offint readPinSwitch(int pin, int threshold){ if (digitalRead(pin)) { unsigned long tt = millis(); while (digitalRead(pin)); if ((millis() - tt) > threshold) return 1; else return 0; } else return 0;} //Read pin using thresholdint readPin(int pin, int threshold){ if (digitalRead(pin)) { unsigned long tt = millis(); while ((digitalRead(pin) && (millis() - tt) <= threshold)); if (digitalRead(pin)) return 1; else return 0; } else return 0;} // Get new status, if anyint getStat(){ if (readPinSwitch(clockSet,100)) if (stat == stSetSecond) return stClockRunning; else return stat+1; else return stat; } // set Arduino and RTC time
void setRTCTime(int hour, int minute, int second, int day, int month, int year){// set Arduino time
setTime(hour,minute,second,day,month,year); time_t t = now(); // set RTC time RTC.set(t);} void setup(){ pinMode(clockUp,INPUT); pinMode(clockDown,INPUT); pinMode(clockSet,INPUT);
// start serial port Serial.begin(9600); // Start up the library sensors.begin(); // esses sensores serao renomeados // set the resolution to 10 bit (good enough?) sensors.setResolution(insideThermometer, 10); sensors.setResolution(outsideThermometer, 10); sensors.setResolution(dogHouseThermometer, 10); Wire.begin();
//pinMode(22,OUTPUT);// define pino 22 como saida lcd.begin(16, 2); // Set the display to 16 columns and 2 rows setSyncProvider(RTC.get); // the function to get the time from the RTC if(timeStatus()!= timeSet) { lcd.setCursor(0,0); lcd.print("Erro RTC"); }}
float media_umidade(){ DHT.read11(dht1_dpin); //Lê as informações do sensor DHT1.read11(dht2_dpin); //Lê as informações do sensor DHT2.read11(dht3_dpin); //Lê as informações do sensor
mediaumidade =((DHT.humidity + DHT1.humidity + DHT2.humidity )/3); //mostra a media da temperatura n da umidade //delay(2000); return mediaumidade;}
float mediatemp(){ sensors.requestTemperatures(); media_temp = (sensors.getTempC(insideThermometer)+sensors.getTempC(outsideThermometer)+sensors.getTempC(dogHouseThermometer))/3; return media_temp;} int oldStat = stat;unsigned long t=millis(); void loop(){
int value = 0; printTime(); delay(80); stat=getStat(); if (stat != oldStat) { t=millis(); oldStat = stat; } else if ((stat != stClockRunning) && ((millis() - t) > 60000)) stat=stClockRunning; switch(stat) { case stClockRunning: break;
case stSetHour: value=hour(); while(readPin(clockUp,80)) { value++; if (value > 23) value=0; setRTCTime(value,minute(),second(),day(),month(),year()); printTime(); } while(readPin(clockDown,80)) { value--; if (value < 1) value=24; setRTCTime(value,minute(),second(),day(),month(),year()); printTime(); } break; case stSetMinute: value=minute(); while(readPin(clockUp,80)) { value++; if (value > 59) value=0; setRTCTime(hour(),value,second(),day(),month(),year()); printTime(); } while(readPin(clockDown,80)) { value--; if (value < 0) value=59; setRTCTime(hour(),value,second(),day(),month(),year()); printTime(); } break; case stSetSecond: value=minute(); while(readPin(clockUp,80)) { value++; if (value > 59) value=0; setRTCTime(hour(),minute(),value,day(),month(),year()); printTime(); } while(readPin(clockDown,80)) { value--; if (value < 0) value=59; setRTCTime(hour(),minute(),value,day(),month(),year()); printTime(); } } }
…
o codigo aqui, se alguem puder me ajudar agradeço muito. Obrigado.
#include <SPI.h>#include <String.h>#include <Ethernet.h>//-------------------------------------------------------------------byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };//MAC padrão;IPAddress ip(192, 168, 1, 50);//Define o endereco IPv4(trocar final);IPAddress gateway(192, 168, 1, 1); //Define o gatewayIPAddress subnet(255, 255, 255, 0); //Define a máscara de redeEthernetServer server(80); // Porta de serviço//-------------------------------------------------------------------int AA0 = A0;//Arduino analogica A0;int AA1 = A1;//Arduino analogica A1;int AA2 = A2;//Arduino analogica A2;int AA3 = A3;//Arduino analogica A3;int AA4 = A4;//Arduino analogica A4;//-------------------------------------------------------------------int D2 = 2;//Arduino digital D2;int D3 = 3;//Arduino digital D3;int D4 = 4;//Arduino digital D4;int D5 = 5;//Arduino digital D5;int D6 = 6;//Arduino digital D6;//-------------------------------------------------------------------String readString = String(30); // string para buscar dados de endereçoboolean statusA0 = false; // Variável para o status do led boolean statusA1 = false; // Variável para o status do led boolean statusA2 = false; // Variável para o status do led boolean statusA3 = false; // Variável para o status do led boolean statusA4 = false; // Variável para o status do led boolean statusD2 = false; // Variável para o status do led boolean statusD3 = false; // Variável para o status do led boolean statusD4 = false; // Variável para o status do led boolean statusD5 = false; // Variável para o status do led boolean statusD6 = false; // Variável para o status do led //--------------------------------------------------------------------void setup(){ // Inicia o Ethernet //Ethernet.begin(mac, ip); Ethernet.begin(mac, ip, gateway, subnet); server.begin();//-----------------------Define pino como saída----------------------- pinMode(AA0, OUTPUT); pinMode(AA1, OUTPUT); pinMode(AA2, OUTPUT); pinMode(AA3, OUTPUT); pinMode(AA4, OUTPUT); pinMode(D2, OUTPUT); pinMode(D3, OUTPUT); pinMode(D4, OUTPUT); pinMode(D5, OUTPUT); pinMode(D6, OUTPUT);//--------------------------------------------------------------------- // Inicia a comunicação Serial Serial.begin(9600); }void loop(){ // Criar uma conexão de cliente EthernetClient client = server.available(); if (client) { while (client.connected()) { if (client.available()) { char c = client.read(); // ler caractere por caractere vindo do HTTP if (readString.length() < 30) { // armazena os caracteres para string readString += (c); } //se o pedido HTTP terminou if (c == '\n') {//------------------------------------------------------------------ if(readString.indexOf("a0high")>=0)//Recebido do Android; { // O Led vai ser ligado digitalWrite(AA0, HIGH);//Arduino porta digital D2=5V; statusA0 = true; } // Se a string possui o texto L=Desligar if(readString.indexOf("a0low")>=0)//Recebido do Android; { // O Led vai ser desligado digitalWrite(AA0, LOW);//Arduino porta digital D2=0V; statusA0 = false; }//------------------------------------------------------------------ if(readString.indexOf("a1high")>=0)//Recebido do Android; { // O Led vai ser ligado digitalWrite(AA1, HIGH);//Arduino porta digital D2=5V; statusA1 = true; } // Se a string possui o texto L=Desligar if(readString.indexOf("a1low")>=0)//Recebido do Android; { // O Led vai ser desligado digitalWrite(AA1, LOW);//Arduino porta digital D2=0V; statusA1 = false; }//------------------------------------------------------------------ if(readString.indexOf("a2high")>=0)//Recebido do Android; { // O Led vai ser ligado digitalWrite(AA2, HIGH);//Arduino porta digital D2=5V; statusA2 = true; } // Se a string possui o texto L=Desligar if(readString.indexOf("a2low")>=0)//Recebido do Android; { // O Led vai ser desligado digitalWrite(AA2, LOW);//Arduino porta digital D2=0V; statusA2 = false; }//------------------------------------------------------------------ if(readString.indexOf("a3high")>=0)//Recebido do Android; { // O Led vai ser ligado digitalWrite(AA3, HIGH);//Arduino porta digital D2=5V; statusA3 = true; } // Se a string possui o texto L=Desligar if(readString.indexOf("a3low")>=0)//Recebido do Android; { // O Led vai ser desligado digitalWrite(AA3, LOW);//Arduino porta digital D2=0V; statusA3 = false; }//------------------------------------------------------------------ if(readString.indexOf("a4high")>=0)//Recebido do Android; { // O Led vai ser ligado digitalWrite(AA4, HIGH);//Arduino porta digital D2=5V; statusA4 = true; } // Se a string possui o texto L=Desligar if(readString.indexOf("a4low")>=0)//Recebido do Android; { // O Led vai ser desligado digitalWrite(AA4, LOW);//Arduino porta digital D2=0V; statusA4 = false; }//------------------------------------------------------------------ if(readString.indexOf("d2high")>=0)//Recebido do Android; { // O Led vai ser ligado digitalWrite(D2, HIGH);//Arduino porta digital D2=5V; statusD2 = true; } // Se a string possui o texto L=Desligar if(readString.indexOf("d2low")>=0)//Recebido do Android; { // O Led vai ser desligado digitalWrite(D2, LOW);//Arduino porta digital D2=0V; statusD2 = false; }//------------------------------------------------------------------ if(readString.indexOf("d3high")>=0)//Recebido do Android; { // O Led vai ser ligado digitalWrite(D3, HIGH);//Arduino porta digital D2=5V; statusD3 = true; } // Se a string possui o texto L=Desligar if(readString.indexOf("d3low")>=0)//Recebido do Android; { // O Led vai ser desligado digitalWrite(D3, LOW);//Arduino porta digital D2=0V; statusD3 = false; }//------------------------------------------------------------------ if(readString.indexOf("d4high")>=0)//Recebido do Android; { // O Led vai ser ligado digitalWrite(D4, HIGH);//Arduino porta digital D2=5V; statusD4 = true; } // Se a string possui o texto L=Desligar if(readString.indexOf("d4low")>=0)//Recebido do Android; { // O Led vai ser desligado digitalWrite(D4, LOW);//Arduino porta digital D2=0V; statusD4 = false; }//------------------------------------------------------------------ if(readString.indexOf("d5high")>=0)//Recebido do Android; { // O Led vai ser ligado digitalWrite(D5, HIGH);//Arduino porta digital D2=5V; statusD5 = true; } // Se a string possui o texto L=Desligar if(readString.indexOf("d5low")>=0)//Recebido do Android; { // O Led vai ser desligado digitalWrite(D5, LOW);//Arduino porta digital D2=0V; statusD5 = false; }//------------------------------------------------------------------ if(readString.indexOf("d6high")>=0)//Recebido do Android; { // O Led vai ser ligado digitalWrite(D6, HIGH);//Arduino porta digital D2=5V; statusD6 = true; } // Se a string possui o texto L=Desligar if(readString.indexOf("d6low")>=0)//Recebido do Android; { // O Led vai ser desligado digitalWrite(D6, LOW);//Arduino porta digital D2=0V; statusD6 = false; } //------------------------------------------------------------------ // dados HTML de saída começando com cabeçalho padrão client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println(); client.print("<font size='20'>");//------------------------------------------------------------------ if (statusA0) { client.print("azeroon");//Ethernet envia para Android; //String apenas letras; } else { client.print("azerooff");//Ethernet envia string para Android; //String apenas letras; }//------------------------------------------------------------------ if (statusA1) { client.print("aoneon");//Ethernet envia para Android; //String apenas letras; } else { client.print("aoneoff");//Ethernet envia string para Android; //String apenas letras; }//------------------------------------------------------------------ if (statusA2) { client.print("atwoon");//Ethernet envia para Android; //String apenas letras; } else { client.print("atwooff");//Ethernet envia string para Android; //String apenas letras; }//------------------------------------------------------------------ if (statusA3) { client.print("athreeon");//Ethernet envia para Android; //String apenas letras; } else { client.print("athreeoff");//Ethernet envia string para Android; //String apenas letras; }//------------------------------------------------------------------ if (statusA4) { client.print("afouron");//Ethernet envia para Android; //String apenas letras; } else { client.print("afouroff");//Ethernet envia string para Android; //String apenas letras; }//------------------------------------------------------------------ if (statusD2) { client.print("dtwoon");//Ethernet envia para Android; //String apenas letras; } else { client.print("dtwooff");//Ethernet envia string para Android; //String apenas letras; }//------------------------------------------------------------------ if (statusD3) { client.print("dthreeon");//Ethernet envia para Android; //String apenas letras; } else { client.print("dthreeoff");//Ethernet envia string para Android; //String apenas letras; }//------------------------------------------------------------------ if (statusD4) { client.print("dfouron");//Ethernet envia para Android; //String apenas letras; } else { client.print("dfouroff");//Ethernet envia string para Android; //String apenas letras; }//------------------------------------------------------------------ if (statusD5) { client.print("dfiveon");//Ethernet envia para Android; //String apenas letras; } else { client.print("dfiveoff");//Ethernet envia string para Android; //String apenas letras; }//------------------------------------------------------------------ if (statusD6) { client.print("dsixon");//Ethernet envia para Android; //String apenas letras; } else { client.print("dsixoff");//Ethernet envia string para Android; //String apenas letras; }//------------------------------------------------------------------ //limpa string para a próxima leitura readString=""; // parar cliente client.stop(); } } } }}//--------------------------------------------------------------------------------------------------------//…
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
…
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