conseguimos achar a solução neste site e venho pedir ajuda... ao incluir a nova rotina alarme utilizando sensor ultrassonico segue o codigo abaixo da erro de compilçao e alem do mais... nao consigo nem mesmo "incluir a rotina" sendo que tenho mais uma que eh o motor que vo utilizar para o portao da garagem
segue o codigo abaixo em anexo o arquivo ino... e pra quem nao tem o arduino irei postar no corpo desta mensagem, o motor da garagem nao esta incluido pois a primeira dificuldade veio o ultrassonico simulando o alarme e incluindo na minha rotina do programa principal é o que estou tendo problemas
#include <SPI.h>
#include <String.h>
#include <Ethernet.h>
#include <Ultrasonic.h>
byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0x9B, 0x36};// Endereço Macbyte ip[] = {192, 168, 1, 177 };// Endereço de Ip ArduinoEthernetServer server(8090);// Porta de serviço
int cozinha = 7; // wifi
int sala = 3; // wifi
int quarto2 = 6;
int quarto = 2;
int cooler1 = 5;
int cooler2 = 4;
int portao = 8;
Ultrasonic ultrasonic(9, 10);const int alarme1 = 11;const int alarme2 = 12;long microsec = 0;float distanciaCM = 0;
String readString = String(30);// string para buscar dados de endereço
boolean statusQuarto = false;
boolean statusSala = false;
boolean statusQuarto2 = false;
boolean statusCozinha = false;
boolean statusCooler1 = false;
boolean statusCooler2 = false;
boolean statusPortao = false;
boolean statusAlarme = false;
// Variável para o status do portão
void setup(){
// Inicia o Ethernet
Ethernet.begin(mac, ip);
// Define os pinos como saída
pinMode(quarto, OUTPUT);
pinMode(sala, OUTPUT);
pinMode(quarto2, OUTPUT);
pinMode(cozinha, OUTPUT);
pinMode(cooler1, OUTPUT);
pinMode(cooler2, OUTPUT);
pinMode(portao, OUTPUT);
pinMode(alarme1, OUTPUT);
pinMode(alarme2, OUTPUT);
// Inicia a comunicação Serial
Serial.begin(9600); BuzzerDistancia();}
void loop(){ microsec = ultrasonic.timing(); distanciaCM = ultrasonic.convert(microsec, Ultrasonic::CM);
BuzzerDistancia();
Serial.print(distanciaCM); Serial.println(" cm"); delay(1);}
void BuzzerDistancia(){
digitalWrite(alarme1, LOW); digitalWrite(alarme2, LOW);}
// 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')
{
// vamos verificar se a lâmpada da área deve ser ligada
// Se a string possui o texto L=Ligar
{
// vamos verificar se a lâmpada da sala deve ser ligada
// Se a string possui o texto L=Ligar
if (readString.indexOf("LigarSala") >= 0)
{
// A lâmpada vai ser ligada
digitalWrite(sala, HIGH);
statusSala = true;
}
// Se a string possui o texto L=Desligar
if (readString.indexOf("DesligarSala") >= 0)
{ // A lâmpada vai ser desligada
digitalWrite(sala, LOW);
statusSala = false;
}
{
// vamos verificar se a lâmpada do quarto2 deve ser ligada
// Se a string possui o texto L=Ligar
if (readString.indexOf("LigarQuarto2") >= 0)
{
// A lâmpada vai ser ligada
digitalWrite(quarto2, HIGH);
statusQuarto2 = true;
}
// Se a string possui o texto L=Desligar
if (readString.indexOf("DesligarQuarto2") >= 0)
{
// A lâmpada vai ser desligada
digitalWrite(quarto2, LOW);
statusQuarto2 = false;
}
if (readString.indexOf("LigarQuarto") >= 0)
{
// A lâmpada vai ser ligada
digitalWrite(quarto, HIGH);
statusQuarto = true;
}
// Se a string possui o texto L=Desligar
if (readString.indexOf("DesligarQuarto") >= 0)
{
// A lâmpada vai ser desligada
digitalWrite(quarto, LOW);
statusQuarto = false;
}
{
// vamos verificar se a lâmpada da cozinha deve ser ligada
// Se a string possui o texto L=Ligar
if (readString.indexOf("LigarCozinha") >= 0)
{
// A lâmpada vai ser ligada
digitalWrite(cozinha, HIGH);
}
// Se a string possui o texto L=Desligar
if (readString.indexOf("DesligarCozinha") >= 0)
{
// A lâmpada vai ser desligada
digitalWrite(cozinha, LOW);
statusCozinha = false; }
{
if (readString.indexOf("LigarCooler1") >= 0)
{
// A lâmpada vai ser ligada
digitalWrite(cooler1, HIGH);
statusCooler1 = true;
}
// Se a string possui o texto L=Desligar
if (readString.indexOf("DesligarCooler1") >= 0)
{ // A lâmpada vai ser desligada
digitalWrite(cooler1, LOW);
statusCooler1 = false;
}
{
if (readString.indexOf("LigarCooler2") >= 0)
{
// A lâmpada vai ser ligada
digitalWrite(cooler2, HIGH);
statusCooler2 = true;
}
// Se a string possui o texto L=Desligar
if (readString.indexOf("DesligarCooler2") >= 0)
{ // A lâmpada vai ser desligada
digitalWrite(cooler2, LOW);
statusCooler2 = false;
}
{
if (readString.indexOf("LigarPortao") >= 0)
{
// A lâmpada vai ser ligada
digitalWrite(portao, HIGH);
statusPortao = true;
}
// Se a string possui o texto L=Desligar
if (readString.indexOf("DesligarPortao") >= 0)
{ // A lâmpada vai ser desligada
digitalWrite(portao, LOW);
statusPortao = false;
}
{ if (readString.indexOf("LigarAlarme") >= 0)
{
if (distanciaCM < 100) { digitalWrite(alarme1, HIGH); digitalWrite(alarme2, HIGH); statusAlarme = true; } }
{ if (readString.indexOf("DesligarAlarme") >= 0)
{ void BuzzerDistancia() { digitalWrite(alarme1, LOW); digitalWrite(alarme2, LOW); statusAlarme = 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.println("<font size='20'>");
if (statusQuarto) {
client.print("lampada quarto ligada");
} else {
client.print("lampada quarto desligada");
}
//limpa string para a próxima leitura
readString = "";
// parar cliente
client.stop();
} } } } } } } } } } }}}…
Adicionado por Lucas Ascêncio ao 14:53 em 8 outubro 2014
as vendo no servidor nada, estou usando um arquivo arquivo.php para gravar no servidor, mas nada.
Alguem teria como me mostrar como poderia fazer?
segue codigo:
/*************************************************** This is a sketch to use the CC3000 WiFi chip & Dweet.io Written by Marco Schwartz for Open Home Automation ****************************************************/
// Libraries#include <Adafruit_CC3000.h>//#include <ccspi.h>#include <SPI.h>#include <DS1307.h>//#include "DHT.h"//#include <avr/wdt.h>//#include "utility/debug.h"//#include "utility/socket.h"
// Define CC3000 chip pins#define ADAFRUIT_CC3000_IRQ 3#define ADAFRUIT_CC3000_VBAT 5#define ADAFRUIT_CC3000_CS 10
// DHT sensor//#define DHTPIN 7//#define DHTTYPE DHT11
// Create CC3000 instancesAdafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT, SPI_CLOCK_DIV2); // you can change this clock speed // DHT instance//DHT dht(DHTPIN, DHTTYPE);
// WLAN parameters#define WLAN_SSID "Rede Vale"#define WLAN_PASS "valeinfo!11"#define WLAN_SECURITY WLAN_SEC_WPA2
// Dweet parameters#define thing_name "pedrofilipe_x9521ss5dsa9"
float vazao; //Variável para armazenar o valor em L/minfloat soma=0; //Variável para tirar a média a cada 1 minutofloat media=0; //Variável para tirar a média a cada 1 minutoint contaPulso; //Variável para a quantidade de pulsosint i=0; //Variável para contagemDS1307 rtc(A14, A15);// Variables to be sent//int temperature;//int humidity;//int light;//int t=1200;
uint32_t ip;void incpulso (){ contaPulso++; //Incrementa a variável de contagem dos pulsos} void setup(void){ //rtc.halt(false); // rtc.setDOW(FRIDAY); //Define o dia da semana // rtc.setTime(11, 49, 15); //Define o horario // rtc.setDate(24, 4, 2015); //Define o dia, mes e ano // rtc.setSQWRate(SQW_RATE_1); // rtc.enableSQW(true); // Initialize Serial.begin(115200); pinMode(2, INPUT); attachInterrupt(0, incpulso, RISING); Serial.println(F("\nInitializing...")); if (!cc3000.begin()) { Serial.println(F("Couldn't begin()! Check your wiring?")); while(1); } /* Optional: Set a static IP address instead of using DHCP. Note that the setStaticIPAddress function will save its state in the CC3000's internal non-volatile memory and the details will be used the next time the CC3000 connects to a network. This means you only need to call the function once and the CC3000 will remember the connection details. To switch back to using DHCP, call the setDHCP() function (again only needs to be called once). */ uint32_t ipAddress = cc3000.IP2U32(192, 168, 0, 11); uint32_t netMask = cc3000.IP2U32(255, 255, 255, 0); uint32_t defaultGateway = cc3000.IP2U32(192, 168, 0, 1); uint32_t dns = cc3000.IP2U32(8, 8, 8, 8); if (!cc3000.setStaticIPAddress(ipAddress, netMask, defaultGateway, dns)) { Serial.println(F("Failed to set static IP!")); while(1); } /* Optional: Revert back from static IP addres to use DHCP. See note for setStaticIPAddress above, this only needs to be called once and will be remembered afterwards by the CC3000. */ /* if (!cc3000.setDHCP()) { Serial.println(F("Failed to set DHCP!")); while(1); } */
/* Attempt to connect to an access point */ char *ssid = WLAN_SSID; /* Max 32 chars */ Serial.print(F("\nAttempting to connect to ")); Serial.println(ssid); /* NOTE: Secure connections are not available in 'Tiny' mode! By default connectToAP will retry indefinitely, however you can pass an optional maximum number of retries (greater than zero) as the fourth parameter. ALSO NOTE: By default connectToAP will retry forever until it can connect to the access point. This means if the access point doesn't exist the call will _never_ return! You can however put in an optional maximum retry count by passing a 4th parameter to the connectToAP function below. This should be a number of retries to make before giving up, for example 5 would retry 5 times and then fail if a connection couldn't be made. */ if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) { Serial.println(F("Failed!")); while(1); } Serial.println(F("Connected!")); /* Wait for DHCP to complete */ Serial.println(F("Request DHCP")); while (!cc3000.checkDHCP()) { delay(100); // ToDo: Insert a DHCP timeout! }
/* Display the IP address DNS, Gateway, etc. */ while (! displayConnectionDetails()) { delay(1000); } /* Wait for DHCP to complete */ /* Serial.println(F("Request DHCP")); while (!cc3000.checkDHCP()) { delay(100); } */}
void loop(void){ contaPulso = 0; //Zera a variável para contar os giros por segundos sei(); //Habilita interrupção delay (1000); //Aguarda 1 segundo cli(); //Desabilita interrupção vazao = contaPulso / 5.5; //Converte para L/min soma=soma+vazao; //Soma a vazão para o calculo da media i++; Serial.print(vazao); //Imprime na serial o valor da vazão Serial.print(" L/min - "); //Imprime L/min Serial.print(i); Serial.print(" segundos - "); // Measure from DHT// float t = dht.readTemperature();// float h = dht.readHumidity(); // temperature = (int)t;// humidity = (int)h;//t++;//temperature = (int)t;//humidity = (int)t;
// Measure light level // float sensor_reading = analogRead(A0); // light = (int)(sensor_reading/1024*100); //light = 133; Serial.println(F("Measurements done")); // Start watchdog // wdt_enable(WDTO_8S); //54.236.224.164
media=soma; Serial.print("\nMedia por minuto = "); //Imprime a frase Media por minuto = Serial.print(media); uint32_t ipdweet = cc3000.IP2U32(45, 55, 164, 40);
// Get IP /* uint32_t ip = 0; Serial.print(F("www.dweet.io -> ")); while (ip == 0) { if (! cc3000.getHostByName("www.dweet.io", &ip)) { Serial.println(F("Couldn't resolve!")); } delay(500); } cc3000.printIPdotsRev(ip); Serial.println(F("")); */ // Reset watchdog //wdt_reset(); // Check connection to WiFi Serial.print(F("\nChecking WiFi connection ...")); if(!cc3000.checkConnected()){while(1){}} Serial.println(F("done.")); //wdt_reset(); // Send requestAdafruit_CC3000_Client client = cc3000.connectTCP(ipdweet, 80);if (client.connected()) {Serial.print("Sending request... ");
/*String dado;dado += "GET /arduino/";dado += "pedro.php?vazao=";dado += media;dado += " HTTP/1.1";*/
client.print("GET /arduino/pedro.php?vazao="+(String)media +" HTPP/1.1");//client.fastrprint(F("GET /dweet/for/"));//client.print(thing_name);//client.print(media);
client.println("Host: 45.55.164.40");client.println("Connection: close");client.println("");
media=0;i=0;soma=0;
/////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
Serial.println("OK.");} else {Serial.println("Connection failed"); return;} // Reset watchdog // wdt_reset(); Serial.println("Reading answer..."); while (client.connected()) { while (client.available()) { char c = client.read(); Serial.print(c); } } Serial.println(""); // Reset watchdog // wdt_reset(); // Close connection and disconnect client.close(); Serial.println("Closing connection"); Serial.println(""); // Reset watchdog & disable // wdt_reset(); // wdt_disable(); // Wait 60 seconds until next update //wait(1000); Serial.println("\n\n Recomecar\n\n"); }
// Wait for a given time using the watchdog/*void wait(int total_delay) { int number_steps = (int)(total_delay/5000); wdt_enable(WDTO_8S); for (int i = 0; i < number_steps; i++){ //Serial.println(F("Waiting for 5 seconds ...")); delay(5000); wdt_reset(); } wdt_disable();}*/bool displayConnectionDetails(void){ uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv; if(!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv, &dnsserv)) { Serial.println(F("Unable to retrieve the IP Address!\r\n")); return false; } else { Serial.print(F("\nIP Addr: ")); cc3000.printIPdotsRev(ipAddress); Serial.print(F("\nNetmask: ")); cc3000.printIPdotsRev(netmask); Serial.print(F("\nGateway: ")); cc3000.printIPdotsRev(gateway); Serial.print(F("\nDHCPsrv: ")); cc3000.printIPdotsRev(dhcpserv); Serial.print(F("\nDNSserv: ")); cc3000.printIPdotsRev(dnsserv); Serial.println(); return true; }}…
as vendo no servidor nada, estou usando um arquivo arquivo.php para gravar no servidor, mas nada.
Alguem teria como me mostrar como poderia fazer?
segue codigo:
/*************************************************** This is a sketch to use the CC3000 WiFi chip & Dweet.ioWritten by Marco Schwartz for Open Home Automation****************************************************/
// Libraries#include <Adafruit_CC3000.h>//#include <ccspi.h>#include <SPI.h>#include <DS1307.h>//#include "DHT.h"//#include <avr/wdt.h>//#include "utility/debug.h"//#include "utility/socket.h"
// Define CC3000 chip pins#define ADAFRUIT_CC3000_IRQ 3#define ADAFRUIT_CC3000_VBAT 5#define ADAFRUIT_CC3000_CS 10
// DHT sensor//#define DHTPIN 7//#define DHTTYPE DHT11
// Create CC3000 instancesAdafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,SPI_CLOCK_DIV2); // you can change this clock speed// DHT instance//DHT dht(DHTPIN, DHTTYPE);
// WLAN parameters#define WLAN_SSID "Rede Vale"#define WLAN_PASS "valeinfo!11"#define WLAN_SECURITY WLAN_SEC_WPA2
// Dweet parameters#define thing_name "pedrofilipe_x9521ss5dsa9"
float vazao; //Variável para armazenar o valor em L/minfloat soma=0; //Variável para tirar a média a cada 1 minutofloat media=0; //Variável para tirar a média a cada 1 minutoint contaPulso; //Variável para a quantidade de pulsosint i=0; //Variável para contagemDS1307 rtc(A14, A15);// Variables to be sent//int temperature;//int humidity;//int light;//int t=1200;
uint32_t ip;void incpulso (){ contaPulso++; //Incrementa a variável de contagem dos pulsos} void setup(void){//rtc.halt(false);// rtc.setDOW(FRIDAY); //Define o dia da semana// rtc.setTime(11, 49, 15); //Define o horario// rtc.setDate(24, 4, 2015); //Define o dia, mes e ano// rtc.setSQWRate(SQW_RATE_1);// rtc.enableSQW(true);// InitializeSerial.begin(115200);pinMode(2, INPUT);attachInterrupt(0, incpulso, RISING);Serial.println(F("\nInitializing..."));if (!cc3000.begin()){Serial.println(F("Couldn't begin()! Check your wiring?"));while(1);}/* Optional: Set a static IP address instead of using DHCP.Note that the setStaticIPAddress function will save its statein the CC3000's internal non-volatile memory and the detailswill be used the next time the CC3000 connects to a network.This means you only need to call the function once and theCC3000 will remember the connection details. To switch backto using DHCP, call the setDHCP() function (again only needsto be called once).*/uint32_t ipAddress = cc3000.IP2U32(192, 168, 0, 11);uint32_t netMask = cc3000.IP2U32(255, 255, 255, 0);uint32_t defaultGateway = cc3000.IP2U32(192, 168, 0, 1);uint32_t dns = cc3000.IP2U32(8, 8, 8, 8);if (!cc3000.setStaticIPAddress(ipAddress, netMask, defaultGateway, dns)) {Serial.println(F("Failed to set static IP!"));while(1);}/* Optional: Revert back from static IP addres to use DHCP.See note for setStaticIPAddress above, this only needs to becalled once and will be remembered afterwards by the CC3000.*//*if (!cc3000.setDHCP()) {Serial.println(F("Failed to set DHCP!"));while(1);}*/
/* Attempt to connect to an access point */char *ssid = WLAN_SSID; /* Max 32 chars */Serial.print(F("\nAttempting to connect to ")); Serial.println(ssid);/* NOTE: Secure connections are not available in 'Tiny' mode!By default connectToAP will retry indefinitely, however you can pass anoptional maximum number of retries (greater than zero) as the fourth parameter.ALSO NOTE: By default connectToAP will retry forever until it can connect tothe access point. This means if the access point doesn't exist the callwill _never_ return! You can however put in an optional maximum retry countby passing a 4th parameter to the connectToAP function below. This shouldbe a number of retries to make before giving up, for example 5 would retry5 times and then fail if a connection couldn't be made.*/if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {Serial.println(F("Failed!"));while(1);}Serial.println(F("Connected!"));/* Wait for DHCP to complete */Serial.println(F("Request DHCP"));while (!cc3000.checkDHCP()){delay(100); // ToDo: Insert a DHCP timeout!}
/* Display the IP address DNS, Gateway, etc. */ while (! displayConnectionDetails()) {delay(1000);}/* Wait for DHCP to complete *//* Serial.println(F("Request DHCP"));while (!cc3000.checkDHCP()){delay(100);} */}
void loop(void){ contaPulso = 0; //Zera a variável para contar os giros por segundossei(); //Habilita interrupçãodelay (1000); //Aguarda 1 segundocli(); //Desabilita interrupçãovazao = contaPulso / 5.5; //Converte para L/minsoma=soma+vazao; //Soma a vazão para o calculo da mediai++;Serial.print(vazao); //Imprime na serial o valor da vazãoSerial.print(" L/min - "); //Imprime L/minSerial.print(i);Serial.print(" segundos - ");// Measure from DHT// float t = dht.readTemperature();// float h = dht.readHumidity();// temperature = (int)t;// humidity = (int)h;//t++;//temperature = (int)t;//humidity = (int)t;
// Measure light level// float sensor_reading = analogRead(A0);// light = (int)(sensor_reading/1024*100);//light = 133;Serial.println(F("Measurements done"));// Start watchdog // wdt_enable(WDTO_8S); //54.236.224.164
media=soma;Serial.print("\nMedia por minuto = "); //Imprime a frase Media por minuto =Serial.print(media);uint32_t ipdweet = cc3000.IP2U32(45, 55, 164, 40);
// Get IP/* uint32_t ip = 0;Serial.print(F("www.dweet.io -> "));while (ip == 0) {if (! cc3000.getHostByName("www.dweet.io", &ip)) {Serial.println(F("Couldn't resolve!"));}delay(500);} cc3000.printIPdotsRev(ip);Serial.println(F(""));*/// Reset watchdog//wdt_reset();// Check connection to WiFiSerial.print(F("\nChecking WiFi connection ..."));if(!cc3000.checkConnected()){while(1){}}Serial.println(F("done."));//wdt_reset();// Send requestAdafruit_CC3000_Client client = cc3000.connectTCP(ipdweet, 80);if (client.connected()) {Serial.print("Sending request... ");
/*String dado;dado += "GET /arduino/";dado += "pedro.php?vazao=";dado += media;dado += " HTTP/1.1";*/
client.print("GET /arduino/pedro.php?vazao="+(String)media +" HTPP/1.1");//client.fastrprint(F("GET /dweet/for/"));//client.print(thing_name);//client.print(media);
client.println("Host: 45.55.164.40");client.println("Connection: close");client.println("");
media=0;i=0;soma=0;
/////////////////////////////////////////////////////////
////////////////////////////////////////////////////////
Serial.println("OK.");} else {Serial.println("Connection failed"); return;}// Reset watchdog// wdt_reset();Serial.println("Reading answer...");while (client.connected()) {while (client.available()) {char c = client.read();Serial.print(c);}}Serial.println("");// Reset watchdog// wdt_reset();// Close connection and disconnectclient.close();Serial.println("Closing connection");Serial.println("");// Reset watchdog & disable// wdt_reset();// wdt_disable();// Wait 60 seconds until next update//wait(1000);Serial.println("\n\n Recomecar\n\n");}
// Wait for a given time using the watchdog/*void wait(int total_delay) {int number_steps = (int)(total_delay/5000);wdt_enable(WDTO_8S);for (int i = 0; i < number_steps; i++){//Serial.println(F("Waiting for 5 seconds ..."));delay(5000);wdt_reset();}wdt_disable();}*/bool displayConnectionDetails(void){uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv;if(!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv, &dnsserv)){Serial.println(F("Unable to retrieve the IP Address!\r\n"));return false;}else{Serial.print(F("\nIP Addr: ")); cc3000.printIPdotsRev(ipAddress);Serial.print(F("\nNetmask: ")); cc3000.printIPdotsRev(netmask);Serial.print(F("\nGateway: ")); cc3000.printIPdotsRev(gateway);Serial.print(F("\nDHCPsrv: ")); cc3000.printIPdotsRev(dhcpserv);Serial.print(F("\nDNSserv: ")); cc3000.printIPdotsRev(dnsserv);Serial.println();return true;}}…
de litros gastos. também marcara a temperatura da agua e o tempo de banho.
agora estou tentando acrescenta o consumo de energia em kWh.
para que eu acrescento essa esse consumo a minha ideia de raciocino básico é aperta um botão, quando esse botao for apertado ele limpara a minha tela do display, desligara a minha válvula e imprimira o resultado na tela. so que não to conseguindo encaixa essa parte da programação, sempre que faço da error.
só para constar é a primeira vez que mexo com Arduino e programação e tbm é o primeiro protejo que to desenvolvendo. só tenho 20 dias que to mexendo com isso e nesse tempo estudando e desenvolvendo o protejo vou deixa aqui o código do que fiz ate agora . se alguém poder ajudar com termina a programação de acrescenta o kWh eu fico agradecido.
++++++++++++++++++++++++++++++++++++++++
#include <LiquidCrystal.h> //incluir o lcd para o reconhecimento do Arduino #define sensor 0 //Define o pino A0 como “sensor de Tempreratura" //Declarar a variavel controle de vazão (sensor Ultrasonico HC-SR04) int valvula = 11; //Configura o pino 11 da Arduino para conexão do valvula solenoide int trig = 9; //Configura o pino 9 do Arduino para conexão do Trig do sonar int echo = 10; //Configura o pino 10 (PWM) do Arduino para conexão do Echo do sonar
//Declarar a variavel de Temperatura (Sensor LM35) float Temp; // Variável que recebe o valor convertido para temperatura. int Tempentrada; // Variável para ler o sinal do pino do Arduino "A0"
// Declarar a variavel do Medidor (Nivel de Vazão 1/2) float vazao; //Variável para armazenar o valor em L/min float media = 0; //Variável para fazer a média int contaPulso; //Variável para a quantidade de pulsos int s = 0; //Variável para segundos int Min = 00; //Variável para minutos int Hor=00; float Litros = 0; //Variável para Quantidade de agua float MiliLitros = 0; //Variavel para Conversão //Declara a variavel do Alarme Sonoro int buzzer = 12 ; //Configura o alarme no pino 12 do arduino
//Declara a variavel da Energia Gasta const int botao = 13; //Configura o botão no pino 1 int estadobotao = 0; // variavel que conterá os estados do botão ( 0 low, 1 HIGH)
LiquidCrystal lcd(8, 7, 6, 5, 4, 3);//Esta função acima declara quais os pinos do Arduino serão utilizados para o controle do LCD void setup() { Serial.begin(9600); lcd.begin(16, 2); // Diz para o Arduino que o display é 16x2. lcd.setCursor( 0, 0); lcd.print(" PROJETO "); // Manda o texto para a tela do display lcd.setCursor( 0, 1); lcd.print(" Wellyson Souza"); // Manda o texto para a tela do display delay(1000); //Aguarda 6 segundo para efetuar a leitura do texto acima lcd.clear(); /* lcd.print(" CHUVEIRO "); // Manda o texto para a tela do display lcd.setCursor( 0, 1); lcd.print(" ELETRONICO "); // Manda o texto para a tela do display delay(1000); //Aguarda 3 segundo para efetuar a leitura do texto acima lcd.clear(); lcd.print("Controlador de"); // Manda o texto para a tela do display lcd.setCursor( 0, 1); lcd.print(" Temperatura "); // Manda o texto para a tela do display delay(1000); //Aguarda 3 segundo para efetuar a leitura do texto acima lcd.clear(); lcd.print("Controlador de"); // Manda o texto para a tela do display lcd.setCursor( 0, 1); lcd.print(" Vazao e Tempo"); // Manda o texto para a tela do display delay(1000); //Aguarda 3 segundo para efetuar a leitura do texto acima lcd.clear(); */// Declarando entrada PinMode Para sensor Ultrasonico Abaixo: pinMode(trig, OUTPUT); //define o pino 9 como um output (envia sinal do sensor) pinMode(echo, INPUT); //define o pino 10 como um input (recebe sinal do sensor) pinMode(valvula, OUTPUT); //define o pino 11 como um output (aciona a valvula solenoide) // Declarando entrada no PinMode para o sensor de Nivel d'agua Abaixo: pinMode(2, INPUT); attachInterrupt(0, incpulso, RISING); //Configura o pino 2(Interrupção 0) interrupção
//Declarando a entrada no PinMode do Alarme Sonoro Abaixo: pinMode (buzzer, OUTPUT); // define o pino 12 como output (enviar o alarme "BUZZER")
//Declarando a entrada no PinMode da Energia Gasta Abaixo: pinMode(botao,INPUT); //define o pino 1 com input para o botão.
} void loop (){ //Abaixo a configuração do sensor ultrasonico HC-SR04 (Calculos ncessarios) float tempo, cm; //comandos para enviar um pulso do sonar e armazenar o tempo de resposta digitalWrite(trig, LOW); //seta o pino 9 com pulso BAIXO "zero" delayMicroseconds(2); // Tempo de 2 microssegundos digitalWrite(trig, HIGH); //Seta o pino 9 com pulso ALTO ou em "1" delayMicroseconds(10); // Tempo de 10 microssegundos digitalWrite(trig, LOW); // Seta novamento o pino 9 pulso BAIXO "zero" delayMicroseconds(2); // Tempo de 2 microssegundos tempo = pulseIn(echo, HIGH);// tempo, recebe o tempo de ida e volta do sinal cm = tempo/29/2; //converte duration em centímetros Serial.println(cm); // escrever a distancia no serial obs: usso para teste do sensor HC-SR04 if (cm <= 30) { // Se a distancia for menor ou igual a 30cm o acionar a valvula selenoide. digitalWrite(valvula, HIGH); //Pino que aciona a valvula solenoide
//Abaixo a Configuração do sensor de nivel de vazão (Calculos necessarios) contaPulso = 0;//Zera a variável sei(); //Habilita interrupção delay (1000);//Aguarda 1 segundo cli(); //Desabilita interrupção vazao = contaPulso / 5.5; //Converte para L/min media = media + vazao; //Soma a vazão para o calculo da media s++; // encrementando a variavel "SEGUNDO" lcd.setCursor(0, 0); lcd.print(vazao); //Escreve no display o valor da vazão lcd.print("L/min "); //Escreve no display a unidade L/min MiliLitros = vazao / 60; //Calculos para achar o valor de Mililitros Litros = Litros + MiliLitros; // Calculos para achar o valor de Litros lcd.print(Litros); //Escreve no display o valor de Litros lcd.print("L "); //Escreve no display a unidade L lcd.setCursor(0, 1); lcd.print(Hor); //Escrever no display o valor de horas lcd.print (":"); //Escreve ":" lcd.print(Min); //Escreve no display o valor da mimutos lcd.print(":"); //Escreve ":" lcd.print(s); //Escreve a contagem s (segundos) lcd.print("Min ");//Escreve no display a unidade Min //Abaixo as Configuração do sensor de Temperatura LM35 (Calculos necessarios) Tempentrada = analogRead (sensor); // Manda o Arduino ler o pino e armazena o valor em “entrada”. Temp=(500*Tempentrada)/1023; //Converte o valor de tensão em temperatura e armazena na variável “Temperatura” lcd.print(Temp); // Exibe o valor de temperatura no display. lcd.print("C"); //Neste conjunto de linhas foram feitas a média das leituras da vazão obtidas a cada 1 minuto if (s >= 60){ // se 1 segund for menor ou igal a 60 milisegundo Min++; // encrementar minuto if (Min >= 60){ // se 1 minuto for menor ou igaul a 60 segundo Min = 0; // minuto igal a zero Hor++; // encrementar horas if (Hor >=60){ //se 1 horas for menor ou igaul a 60 minutos Hor = 0; } } } }
else{ // Se a distancia não for menor ou igual a 30cm a valvula mantera fechada. digitalWrite(valvula, LOW); //Pino que mantém a valvula solenoide desligado } //Abaixo as configuraçoes do Alarme Sonoro if (s == 10){ digitalWrite(buzzer, HIGH); lcd.clear (); lcd.print("kisuk"); delay (1000); }
estadobotao = digitalRead(botao); if (estadobotao == LOW) {lcd.clear();lcd.print ("nosss");} //else { // digitalWrite(valvula,LOW); //Botão não pressionado, apaga o led. //} }
void incpulso (){ contaPulso++; //Incrementa a variável de pulsos}…
ay-control-over-i2c/
Então decidi testar este projeto acima, para depois adaptar o meu (ao invés de 3 relés em cada Attiny85, apenas 1 por Attiny, e serão 7 deles).
O problema é que eu não estou conseguindo controlar os relés. Quando dou o comando através do Serial Monitor, o led RX do Uno pisca, porém não aciona o relé correspondente.
Estou utilizando dois resistores pull up (4.7k Ohm). Testei IDE 1.0.1, 1.6.6 e 1.6.7.
Gostaria da ajuda de vocês, se possível.
Grato desde já.
Código do Arduino:
#include <Wire.h>
int selection=0;
int ATtinyAddress=0x26;
void setup(){
Wire.begin();
Serial.begin(9600);
PrintMenu();
}
void loop(){
if (Serial.available() > 0){
selection = Serial.read()-48;
RelaySwitch(ATtinyAddress,selection);
}
}
void PrintMenu(){
Serial.println("--- Relay Menu ---");
Serial.println("1: Switch Relay 1");
Serial.println("2: Switch Relay 2");
Serial.println("3: Switch Relay 3");
}
void RelaySwitch(byte device,byte data){
Wire.beginTransmission(device);
Wire.write(data);
Wire.endTransmission();
}
Código do Attiny85
#include "TinyWireS.h"
#define I2C_SLAVE_ADDR 0x26
#define Relay1_PIN 1
#define Relay2_PIN 4
#define Relay3_PIN 3
void setup(){
pinMode(Relay1_PIN,OUTPUT);
pinMode(Relay2_PIN,OUTPUT);
pinMode(Relay3_PIN,OUTPUT);
TinyWireS.begin(I2C_SLAVE_ADDR);
}
void loop(){
byte byteRcvd = 0;
if (TinyWireS.available()){
byteRcvd = TinyWireS.receive();
switch (byteRcvd) {
case 0x01:
Switch(Relay1_PIN);
break;
case 0x02:
Switch(Relay2_PIN);
break;
case 0x03:
Switch(Relay3_PIN);
break;
}
}
}
void Switch(int relay){
if (digitalRead(relay) == HIGH){ digitalWrite(relay,LOW);}
else {digitalWrite(relay,HIGH);}
}
…
=============>
#include <SPI.h>
#include <Ethernet.h>#include <SD.h>#include <RelayBoard.h>// size of buffer used to capture HTTP requests#define REQ_BUF_SZ 60#define date 6#define strobe 3#define clock 2#define numberboards 1
RelayBoard 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,99); // IP address, may need to change depending on networkEthernetServer server(80); // create a server at port 80File 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 LEDs
void 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); }}
// 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;}
<==================================================>
<==================================================>
Quero adicionar esses dois arquivos que ficaram junto com o index no micro sd
"jquery.accordion.js"
"jquery.easing.1.3"…
um modulo, que esta ligado ao motor.
O Primeiro código, é apenas um contador, que se der para adaptar esse, eu não precisaria mudar os outros abaixo.
Esse código abaixo, ele apresenta apenas no monitor serial, o numero de pulsos, que no meu caso, ( mas vou modificar para apenas um pulso por volta ) são 4 pulsos, se eu puder modificar esse código, para que o motor pare em 700 voltas, ele teria que parar o motor, 2800 pulsos.( sendo 4 pulsos ) é isso que eu preciso fazer, como faze-lo parar, quando o monitor serial apresentar 2800 pulsos?
CODIGO 1 - contador de pulsos
boolean anterior = 0;
boolean actual = 0;
int contador = 0;
void setup()
{
Serial.begin(9600);
pinMode(2,INPUT);
}
boolean debounce(boolean dato_anterior)
{
boolean dato_actual = digitalRead(2);
if (dato_anterior != dato_actual)
{
delay(10);
dato_actual = digitalRead(2);
}
return dato_actual;
}
void loop()
{
actual = debounce(anterior);
if ( anterior == 0 && actual == 1)
{
contador++;
delay (100);
Serial.println(contador);
}
anterior = actual;
}
Esse código abaixo, é do Rui, daqui do fórum, ele foi muito gentil e o fez para mim, mas tenho que acrescentar o relé. O motor vai diminuindo aos poucos a velocidade ate parar, mas tenho duvidas.
Onde conectar o Relé? e testei o código sem o rele, e era para o motor ir diminuindo a velocidade, mas isso não aconteceu,
CODIGO 2 - do Rui com Relé
//Programa: Sensor de velocidade Arduino LM393
//http://www.arduinoecia.com.br/2016/02/sensor-de-velocidade-lm393-arduino.html
//Autor: Arduino e Cia Modificado por Rui
#define sensor 2 //Pino ligado ao pino D0 do sensor
#define motor 6 //Pino de saída para controle do motor ( nao ligar ditero no motor, use driver)
#define rele 7 //Pino de saída para o rele
volatile byte pulsos = 0;
unsigned int pulsos_por_volta = 63; //Altere o numero abaixo de acordo com o seu disco encoder
unsigned int voltas = 12; //Numero de voltas
unsigned int Fase = 0;
//------------------------------
void contador()
{
pulsos++; //Incrementa contador
}
//------------------------------
void setup()
{
Serial.begin(9600);
pinMode(motor, OUTPUT); //Pino do motor como saida (PWM)
pinMode(rele, OUTPUT); //Pino do rele HIGH desligado LOW ligado
pinMode(sensor, INPUT); //Pino do sensor como entrada
attachInterrupt(0, contador, FALLING); //Interrupcao 0 - pino digital 2 Aciona o contador a cada pulso
}
//------------------------------
void loop()
{
Fase = (pulsos / pulsos_por_volta); //Calculo de voltas
if (Fase >= 6) //Se faltam + q 6 voltas
{
digitalWrite(rele, HIGH); //Libera o motor
analogWrite(motor, 255); //Velocidade máxima
}
if (Fase < 6 & Fase > 3) //Se faltam 6 voltas
{
digitalWrite(rele, HIGH); //Libera o motor
analogWrite(motor, 127); //Reduz Velocidade para 1/2
}
if (Fase < 3) //Se faltam 3 voltas
{
digitalWrite(rele, HIGH); //Libera o motor
analogWrite(motor, 63); //Reduz Velocidade para 1/4
}
if (F
ase = 0) //Se terminaram as voltas
{
digitalWrite(rele, LOW); //Freia o motor
}
}
E Por fim, vem o código 3, que peguei de um tutorial de uma Bobinadora, no tutorial, ele dá poucas explicações,
#include AQUI eu preciso mudar para i2c, isso eu fiz
#include Esse LCDKeypad é um modulo, e eu tenho que trocar por um LCD que ja vem com o i2c, tenho que trocar os nomes? mas esse modulo vem com botões, ai preciso implementar os botões separados, como?
#define MODE_MENU 0 - Aqui o 0 é a porta A0 ? seria um botão?
#define MODE_WIND 1 - Aqui, é mais um botão que eu teria que implementar? como localizar e ele no restante do programa.?
#define PIN_MOTOR 2 - Aqui o A2 é a porta? seria + um botão?
#define PIN_SENSOR 3 - Aqui o A3 + um botão? esse é do ENCODER
#define INTER_SENSOR 1 - E esse, é mais um encoder, pois ele colocou dois, um do lado do outro.
MAS, não adianta aquele amigo daqui, me diga, faça isso ou aquilo, eu preciso que alguem modifique o codigo e me entregue ele pronto, talvez eu saiba modificar, talvez não.
CODIGO 3 - Bobinadora
#include
#include
#define MODE_MENU 0
#define MODE_WIND 1
#define PIN_MOTOR 2
#define PIN_SENSOR 3
#define INTER_SENSOR 1
#define MAX_SPEED 255
#define MIN_SPEED 127
#define SPEED_RANGE (MAX_SPEED - MIN_SPEED)
/** should have been 8 but 3 works ?? **/
#define TICKS_PER_REV 3
LCDKeypad lcd;
int numberOfWindings = 100;
int windingsLeft = 0;
int decimal = 1;
int ticks = 0;
char speed = 125;
int mode = MODE_MENU;
/**
* react on coil revolution
*/
void pinChangeInt() {
if (mode == MODE_WIND) {
ticks++;
if (ticks == TICKS_PER_REV) {
windingsLeft--;
ticks = 0;
if (windingsLeft == 0) {
lcd.clear();
digitalWrite(PIN_MOTOR, LOW);
mode = MODE_MENU;
speed = 0;
}
}
}
}
/**
* wait until button has been pressed
* returns the button number
*/
int waitButton(){
int buttonPressed;
lcd.blink();
while(lcd.button()!=KEYPAD_NONE); // wait for button release
delay(50);
while((buttonPressed=lcd.button())==KEYPAD_NONE); // wait for button hit
delay(50);
lcd.noBlink();
while(lcd.button()!=KEYPAD_NONE); // and wait until released again
return buttonPressed;
}
/**
* make digits from decimal places
*/
void makeDigits(int number, int *m, int *c, int *x, int *i) {
int a = number;
(*m) = a / 1000;
a = a % 1000;
(*c) = a / 100;
a = a % 100;
(*x) = a / 10;
a = a % 10;
(*i) = a;
}
/**
* fazer uma série de quatro casas decimais
*/
void makeNumber(int *number, int m, int c, int x, int i) {
(*number) = 1000 * m + 100 * c + 10 * x + i;
}
/**
* increment a digit until it's zero
*/
void incDigit(int *x, int max) {
int m = *x;
m ++;
if (m > max) {
m = max;
}
(*x) = m;
}
/**
* decrement a digit until it's zero
*/
void decDigit(int *x) {
int m = *x;
m --;
if (m < 0) {
m = 0;
}
(*x) = m;
}
/**
* increment the number at position "decimals"
*/
void incWindings(int decimals) {
int m, c, x, i;
makeDigits(numberOfWindings, &m, &c, &x, &i);
switch (decimals) {
case 3:
incDigit(&m, 9);
break;
case 2:
incDigit(&c, 9);
break;
case 1:
incDigit(&x, 9);
break;
case 0:
incDigit(&i, 9);
break;
default:
break;
}
makeNumber(&numberOfWindings, m, c, x, i);
}
/**
* decrement the number at position "decimals"
*/
void decWindings(int decimals) {
int m, c, x, i;
makeDigits(numberOfWindings, &m, &c, &x, &i);
switch (decimals) {
case 3:
decDigit(&m);
break;
case 2:
decDigit(&c);
break;
case 1:
decDigit(&x);
break;
case 0:
decDigit(&i);
break;
default:
break;
}
makeNumber(&numberOfWindings, m, c, x, i);
}
/*
* setup the system
*/
void setup() {
// show splash
lcd.begin(16,2);
lcd.clear();
lcd.print("TecDroiD's");
lcd.setCursor(0,1);
lcd.print(" Coil Winder");
// setup sensor pin
pinMode(PIN_SENSOR, INPUT);
attachInterrupt(INTER_SENSOR, pinChangeInt, RISING);
// setup motor pin
pinMode(PIN_MOTOR, OUTPUT);
//analogWrite(PIN_MOTOR,0);
digitalWrite(PIN_MOTOR, LOW);
// delay splash and clear
delay(1000);
lcd.clear();
}
void show_number(int number) {
int m,c,x,i;
makeDigits(number, &m, &c, &x, &i);
lcd.print(m,DEC);
lcd.print(c,DEC);
lcd.print(x,DEC);
lcd.print(i,DEC);
}
/**
* menu para selecionar os enrolamentos da bobina
*/
void loop_menu() {
// int m,c,x,i;
int buttonPressed;
/* show text */
lcd.setCursor(0,0);
lcd.print("Windings: ");
/* show number of windings */
lcd.setCursor(0,1);
show_number(numberOfWindings);
lcd.setCursor(3-decimal,1);
lcd.cursor();
buttonPressed = waitButton();
switch(buttonPressed) {
case KEYPAD_SELECT:
windingsLeft = numberOfWindings;
mode = MODE_WIND;
lcd.clear();
break;
case KEYPAD_LEFT:
incDigit(&decimal, 3);
break;
case KEYPAD_RIGHT:
decDigit(&decimal);
break;
case KEYPAD_UP:
/* number increase */
incWindings(decimal);
break;
case KEYPAD_DOWN:
decWindings(decimal);
break;
default:
break;
}
}
/**
* wind the coil - enrolar a bobina
*/
void loop_wind() {
int buttonPressed;
/* set motor speed */
//analogWrite(PIN_MOTOR, speed);
digitalWrite(PIN_MOTOR,HIGH);
lcd.setCursor(0,0);
lcd.print("Windings: ");
lcd.print(numberOfWindings, DEC);
lcd.setCursor(0,1);
lcd.print("To Do: ");
show_number(windingsLeft);
//lcd.print(windingsLeft, DEC);
buttonPressed = lcd.button();
if (buttonPressed == KEYPAD_SELECT) {
lcd.clear();
digitalWrite(PIN_MOTOR, LOW);
mode = MODE_MENU;
}
}
/**
* Select looping mode
*/
void loop() {
switch(mode) {
case MODE_MENU:
loop_menu();
break;
case MODE_WIND:
loop_wind();
break;
default:
lcd.print("Mode ERROR!? ");
lcd.print(mode, DEC);
break;
}
}
enrolador de bobina automática - Abaixo, tem o link dos arquivos. Esse é o de cima.
por tecdroid , publicada 21 de março de 2016
http://www.thingiverse.com/thing:1431330
Muito obrigado…