Resultados da busca - %E6%81%92%E8%BE%BE%E7%99%BB%E5%BD%95%E7%94%A8%E6%88%B7%E5%90%8D%E6%98%AF%E4%BB%80%E4%B9%88%E6%84%8F%E6%80%9D%E3%80%90%E2%94%83%E5%A5%BD%E8%AE%A1%E5%88%922%E2%92%8F7%E2%92%8F01705%7B%EF%BC%B1%E3%80%91%E3%80%91
um mouse, e não é detectável em jogos online nem muda os drivers, com um simples Arduíno mini é possível reproduzir o projeto em um mouse comum.
Componentes necessários(para teste):
1x Arduino uno ou mini...
1x protoboard
x Jumpers
5x transistores PNP BC558 //para fazer o teste correto quando inseri-lo ao mouse
5x resistores de 1k //para base dos transistores
5x resistores de 220r //para os leds
5x Leds //para testar os terminais que vão para a placa do mouse
6 Push-Button //para acionaras funçoes
Componentes necessários(para uso no dispositivo):
1x Arduino mini
1x mouse comum
5x transistores PNP BC558 //para ativar o sinal do mouse conforme o Arduíno ordenar
5x resistores de 1k //para base dos transistores
Bom como perceberam,apesar de eu não ter tirado muitas fotos (pretendo corrigir isso ao final do projeto) o esquema de ligaçao é simples, pois o circuito foi adaptado para funcionar como push-buttons visto que o mouse para comandar suas funções utiliza o GND para acionamento dos botoes então é ae que entra o BC558, sabendo que o Arduíno só tem saída + em suas portas era necessário um transistor PNP para converter o sinal em GND.
Assim ligamos as saídas do Arduíno nos resistores de 1k que por sua vez são ligados a base do transistor, tendo seus coletores ligados ao GND os pinos Emissores serão ligados as trilhas do circuito que receberia o sinal dos botoes, o Arduíno mini sera alimentado pela própria usb do dispositivo e as trilhas originais dos botoes devem ser cortadas./*para mais proteção recomenda-se o uso de um regulador de tensão 5v , o mini pode ser programado com um Arduíno uno ou placa usb-serial*/
Uma das vantagens é que o código é simples e de fácil entendimento para criação de novos perfis de macro, então crie seu próprio macro!
vamos ao sketch:
//projeto Macro mouse genericoint botDIR=13;//entrada botao direito int botdir=12;//saida transistor PNP BC558 direitaint botESQ=11;//entrdada botao esquerdo int botesq=10;//saida transistor PNP BC558 esquerdaint botCTR=9;//entrada botao central(roda do mouse) int botctr=8;//saida botao transistor PNP BC558 central(roda do mouse)int bot1LTR=7;//entrada 1 botao lateral int botltr1=6;//saida de transistor PNP BC558 botao lateralint bot2LTR=5;//entrada 2 botao lateral int botltr2=4;//saida botao transistor PNP BC558 lateralint botMODE=3;//entrada botao Mode gamming (CPI) int mode=0;//variavel inicial do menu//tempo de precionamento#define t_500 delay(500);#define t_300 delay(300);#define t_200 delay(200);#define t_100 delay(100);//ativa e desativa os botoes//valores de ligado e desligado foram invertidos por causa do transistor#define ligEsq digitalWrite(botesq, LOW); ;//liga o esquerdo #define desEsq digitalWrite(botesq, HIGH);//desliga----^#define ligDir digitalWrite(botdir, LOW); ;//liga o direito #define desDir digitalWrite(botdir, HIGH); //desliga--^#define ligLtr1 digitalWrite(botltr1, LOW); ;//liga o lateral 1 #define desLtr1 digitalWrite(botltr1, HIGH);//desliga---^#define ligLtr2 digitalWrite(botltr2, LOW); ;//liga o lateral 2 #define desLtr2 digitalWrite(botltr2, HIGH);//desliga--^#define ligCtr digitalWrite(botctr, LOW); ;//liga o central #define desCtr digitalWrite(botctr, HIGH);//desliga--^//Principais Skills do Macro-------------------------------------------------------------------------------------------------------------------------------------------------------------#define Pressed_Dir int botDIR1 =digitalRead(botDIR); if(botDIR1 == LOW){ligDir;}else{desDir;}//precionamento direito normal #define Pressed_Esq int botESQ1 =digitalRead(botESQ); if(botESQ1 == LOW){ligEsq;}else{desEsq;}//precionamento esquerdo normal#define Pressed_1Ltr int botLTR1 =digitalRead(bot1LTR); if(botLTR1 == LOW){ligLtr1;}else{desLtr1;}//precionamento lateral 1 normal#define Pressed_2Ltr int botLTR2 =digitalRead(bot2LTR); if(botLTR2 == LOW){ligLtr2;}else{desLtr2;}//precionamento lateral 2 normal#define Pressed_Ctr int botCTR1 =digitalRead(botCTR); if(botCTR1 == LOW){ligCtr;}else{desCtr;}//precionamento roda do mouse normal#define Pressed_Esq_3kill int botESQ1 =digitalRead(botESQ); if(botESQ1 == LOW){for(int ct=0; ct < 3; ct++){ligEsq; t_200; desEsq; t_100;}}else{desEsq;}//triplo precionamento direito#define Pressed_Ctr_3 int botCTR1 =digitalRead(botCTR); if(botCTR1 == LOW){for(int ct=0; ct < 3; ct++){ligCtr; t_200; desCtr; t_100;}}else{desCtr;}//triplo precionamento roda do mouse#define Pressed_Esq_Scope int botESQ1 =digitalRead(botESQ); if(botESQ1 == LOW){ligDir; t_300; ligEsq; t_300; desEsq; desDir;}//scope "direita">>"esuqerda"|"direita"#define Pressed_Mode int botMODE1 =digitalRead(botMODE); if(botMODE1 == LOW){mode++; t_500;}if(mode == 5){mode=0;}//seleciona o n max de perfis que atualmente é 6//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^void setup(){//PULLUP PERMITE LIGAR UM BOTAO AO TERRA DIRETAMENTE//Serial.begin(9600); pinMode(botDIR,INPUT_PULLUP);//Entrada direita pinMode(botdir,OUTPUT);//saida direita pinMode(botESQ,INPUT_PULLUP);//Entrada esquerda pinMode(botesq,OUTPUT);//saida esquerda pinMode(botCTR,INPUT_PULLUP); //Entrada do botao da roda do mouse pinMode(botctr,OUTPUT);//saida do botao da roda do mouse pinMode(bot1LTR,INPUT_PULLUP);//Entrada do botao lateral 1 pinMode(botltr1,OUTPUT);//saida botao lateral 1 pinMode(bot2LTR,INPUT_PULLUP);// Entrada do botao lateral 2 pinMode(botltr2,OUTPUT);//saida botao lateral 2 pinMode(botMODE,INPUT_PULLUP);// Entrada do botao CPI do mouse}//fim do void setupvoid loop(){Pressed_Mode;//perfil normalif(mode == 0){//Serial.println("normal"); Pressed_Dir; Pressed_Esq; Pressed_1Ltr; Pressed_2Ltr; Pressed_Ctr; }//perfil sniperif(mode == 1){//Serial.println("sniper"); Pressed_Esq_Scope; Pressed_Dir; Pressed_1Ltr; Pressed_2Ltr; Pressed_Ctr; }//perfil 3balas por vezif(mode == 2){//Serial.println("3balas"); Pressed_Dir; Pressed_Esq_3kill; Pressed_1Ltr; Pressed_2Ltr; Pressed_Ctr; }//perfil baionetaif(mode == 3){//Serial.println("baioneta"); Pressed_Dir; Pressed_Esq; Pressed_Ctr_3; Pressed_1Ltr; Pressed_2Ltr; }//perfil misto scope+baionetaif(mode == 4){// Serial.println("scope e baioneta"); Pressed_Esq_Scope; Pressed_Dir; Pressed_Ctr_3; Pressed_1Ltr; Pressed_2Ltr; }}//fim do void loop
Em anexo segue fotos de esquema e sketch, bom projeto!…
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
tar mas estou sim com dificuldades. Preciso de ajuda.
Segue o código sem a função autotune.
Gostaria de ajuda para implementar ela aqui.
//********** 17/11/15 ******* 12:35 *******************//=========================================================////---- Programa de Controle para Elementos Peltier ----////=========================================================
// Por Max Anderson 11/2015// Ligue os pinos do lcd dessa maneira:// SCK - Pin 12// MOSI - Pin 11// DC - Pin 8// RST - Pin 5// CS - Pin 7
#include <LCD5110_Graph.h> // inclui a biblioteca do display 5110#include <SoftwareSerial.h> //FAZ IMPORTAÇÃO DA BIBLIOTECA -#include <Bounce.h> // biblioteca utilizada para delay de botões#include <dht.h>
SoftwareSerial mySerial( 01, 02); // DEFINE OS PINOS A SEREM UTILIZADOS: RX, TX. RESPECTIVAMENTE - Porta virtual para o arduino nanochar buffer[30];// Tamanho do buffer de dados recebidos pela porta 1byte GetData [7] = {0x01, 0x00, 0x00, 0x00, 0x08, 0x02, 0x03};//Pacote de dados de solicitação enviado ao densímetroLCD5110 myGLCD(12, 11, 8, 5, 7); // define a sequência de ligação do displayextern unsigned char SmallFont[]; // define tamanho da fonteextern unsigned char TinyFont[];char tenstring [6]; // define tamanho da stringString str;dht DHT;String Temp_Ap; // String para concaternar Temperatura de aparelhofloat Temp_Full = 20; // Variavel float para guardar temperatura de aparelho
#define AUMENTAR_PIN 10//7 sem display#define DIMINUIR_PIN 6//8 sem display#define CENTER_PIN 9 // botão para ajuste fino da temperatura#define DEBOUNCE_TIME 5 // tempo em ms#define DHT22_PIN A1 //Sensor de Umidade#define pinoSensor A0 //Sensor externo de Temperatura (via circuito eletrônico com o AD 590)long lastDebounceTime = 0; //Ultimo estado do botãolong debounceDelay = 50; //Atraso em delayint buttonState = 0; // variavel para leitura do estado do botãoBounce aumentar = Bounce(AUMENTAR_PIN, DEBOUNCE_TIME);Bounce diminuir = Bounce(DIMINUIR_PIN, DEBOUNCE_TIME);Bounce center = Bounce(CENTER_PIN, DEBOUNCE_TIME);double count, count2 = 0; // Contadores dos botões
int direcaoA = 4;int brakeA = 1;int pwmA = 3;int correnteA = 14;int direcaoB = 4;int brakeB = 1;int pwmB = 3;int k;// Variáveis que guardam a temperatura máxima e mínimaint maxtemp = -100, mintemp = 100;// Variáveis que guardam a umidade máxima e mínimaint maxhum = -100, minhum = 100;int umidade;
int Val_05; // variavel para valor do buffer 6int Val_06; // variavel para valor do buffer 7int Val_08; // variavel para valor do buffer 9int Val_09; // variavel para valor do buffer 10
double valorPot = 0; // registra o valor do potenciometrodouble valorTemp = 0; // registra o valor da temperaturadouble valorPelt = 0; // registra a potencia enviada para a Peltierint valorPelt2 = 0;int iniciar = 0;
unsigned long lastTime;double Input, Output;double errSum, lastInput;float DifTemp, DifTemp2;
const int relePin = 4; // Pino de reversão do releint releState = LOW; // Inicializa o aparelho com rele desligadoint Buzz = 13; // Pino do Buzzer 13// PARAMETROS PID
double kp = 0.7;//2 ----- 1 ----0.03double ki = 0.1;//0.3 ------ 0.05 ---0.02double kd = 0.05;//0.1 ------ 0.01 ---0.01
// Limites da potencia Peltier
int potMax = 255;int potMin = -255;int tempMax = 50;int tempMin = 15;
//==============================================================================// ********** Logica do Controle de Variação Brusca de Temperatura *********long previousMillis1 = 0;long Time1 = 1000;
float MinTemp = 0.5;//Graus Celsiusfloat MaxTemp = 0.5;//Graus Celsiusfloat Diferenca = 0;
//==============================================================================// ------ Valor inicial para o Setpoint
double Setpoint = 20.0;//==============================================================================// ------ Valor inicial para a Umidade
int Umid = 20;//==============================================================================
double iTerm;int SampleTime = 0; // intervalo de tempo da funcao PIDint i, j;int tempo;//double pinoSensor = A0;// Pino analogico de entrada do LM 35double valorLido = 0;double temperatura = 0;double temperatura2 = 0;double temperatura3 = 0;double tempData = 0x0000;
float soma = 0; // variavel que soma os valores obtidosfloat media = 0; // variavel que calcula a mediafloat soma2 = 0;float media2 = 0;//------------------------------------------//
void setup() {
myGLCD.InitLCD(); myGLCD.setFont(SmallFont); //Habilitação da serial Serial.begin(19200);//Inicializa a porta Serial.flush(); // pinMode(12, OUTPUT);//Para acender o Led de teste no pino 10 mySerial.begin(19200); //VELOCIDADE DE COMUNICAÇÃO DA SERIAL VIRTUAL -
pinMode(direcaoA, OUTPUT); pinMode(pwmA, OUTPUT); pinMode(brakeA, OUTPUT); pinMode(correnteA, INPUT);
pinMode(direcaoB, OUTPUT); pinMode(pwmB, OUTPUT); pinMode(brakeB, OUTPUT);
pinMode(AUMENTAR_PIN, INPUT_PULLUP); pinMode(DIMINUIR_PIN, INPUT_PULLUP); pinMode(CENTER_PIN, INPUT_PULLUP); digitalWrite(direcaoB, HIGH); digitalWrite(brakeB, HIGH); analogWrite(pwmB, 0);
pinMode(Buzz, OUTPUT);//Buzzer digitalWrite(brakeA, LOW); myGLCD.clrScr(); // Limpa o LCD de lixo
}//------------------------------------------//
void loop(){
count = 1; DHT.read22(DHT22_PIN); //Lê as informações do sensor umidade = DHT.humidity; str.toCharArray(tenstring, 6); // define o tamanho da string d voltagem
// myGLCD.clrScr(); // Limpa o LCD de lixo myGLCD.update(); // atualiza lcd
//------------------------------------------------------- //----- BOTÃO AUMENTAR -------------------------------
if (aumentar.update() ) { count = 0 ; if (aumentar.read() == LOW && center.read() == HIGH) { count++; aumentar.rebounce(10); if (Setpoint < 50) Setpoint = Setpoint + 1;//Define qual o tamanho do salto digitalWrite(Buzz, HIGH); delay(100); digitalWrite(Buzz, LOW); } } //----------------------------------------------------- //----- BOTÃO DIMINUIR ---------------------------- if (diminuir.update() ) { count = 0 ; if (diminuir.read() == LOW && center.read() == HIGH) { count2++; diminuir.rebounce(10); if (Setpoint > 15) Setpoint = Setpoint - 1;//Define qual o tamanho do salto digitalWrite(Buzz, HIGH); delay(100); digitalWrite(Buzz, LOW); } }
//----------------------------------------------------------- //----- BOTÃO CENTRAL ------------------------------- if (center.update()) { count = 0 ; if ( diminuir.read() == LOW && aumentar.read() == LOW) { digitalWrite(Buzz, HIGH); delay(100); digitalWrite(Buzz, LOW); } } //-----------------------------------------------
if (center.read() == LOW && diminuir.read() == LOW && aumentar.read() == HIGH) { count2++; center.rebounce(10); if (Setpoint > 0) Setpoint = Setpoint - 0.1;//Define qual o tamanho do salto digitalWrite(Buzz, HIGH); delay(100); digitalWrite(Buzz, LOW); }
//---------------------------------------------------- if (center.read() == LOW && aumentar.read() == LOW && diminuir.read() == HIGH) { count2++; center.rebounce(10); if (Setpoint < 255) Setpoint = Setpoint + 0.1;//Define qual o tamanho do salto digitalWrite(Buzz, HIGH); delay(100); digitalWrite(Buzz, LOW); } //---------------------------------------------------- // if (diminuir.update() && aumentar.update()){ // count = 0 ; if ( diminuir.read() == LOW && aumentar.read() == LOW) { center.rebounce(10); Setpoint = 20.0;//Define qual o tamanho do salto digitalWrite(Buzz, HIGH); delay(100); digitalWrite(Buzz, LOW); } // }
//------------------------------------------------------------------------------------- //-------------- Tratamento da Inicialização do Instrumento ----------------------- valorPot = ((Setpoint)); // Determina que o valor da peltier seja o Setpoint quando o aparelho é ligado //valorTemp = getTemp(); //Original if (Serial.available () == 0) { iniciar = 0; valorTemp = Setpoint; temperatura3 = Setpoint; // digitalWrite(Buzz, HIGH); myGLCD.clrScr(); // Limpa o LCD de lixo } else { valorTemp = Temp_Full; iniciar = 1; // digitalWrite(Buzz, LOW); temperatura3 = Temp_Full;//Temperatura enviada diretamente pelo Densímetro (via serial TTL)<<<<<<<<<<<<< myGLCD.clrScr(); // Limpa o LCD de lixo } DifTemp = (temperatura3 - Setpoint); DifTemp2 = abs (DifTemp); // SampleTime = (DifTemp2*DifTemp2*(-0.00476)+DifTemp2*0.3381 + 0.5) * 1000;//Para 500 ms de time final SampleTime = (DifTemp2*DifTemp2*(-0.007)+DifTemp2*0.4 + 0.1) * 1000; //Para 100 ms de time final
//-------------------------------------------------------// ---- TRATAMENTO DAS FUNÇÕES PID --------------------unsigned long now = millis();int timeChange = (now - lastTime);if (timeChange >= SampleTime) { double error = valorPot - valorTemp; errSum += error; double dInput = (Input - lastInput);
iTerm += (ki * error); if (iTerm > potMax) iTerm = potMax; else if (iTerm < potMin) iTerm = potMin;
valorPelt = kp * error + ITerm- kd * dInput; if (valorPelt > potMax) valorPelt = potMax; else if (valorPelt < potMin) valorPelt = potMin;
lastInput = Input; lastTime = now;}
if (valorPelt > potMax) { valorPelt = potMax;}else if (valorPelt < potMin) { valorPelt = potMin;}
//--------------------------------------------------------------------------------------// ----------- Envio de informações para a Ponte H e direção de acionamento -----------
if (valorPelt >= 0 && umidade < Umid) { digitalWrite(direcaoA, HIGH); digitalWrite(relePin, LOW); // Desliga o rele de reversão da Peltier(Aquecer) analogWrite(pwmA, valorPelt); // myGLCD.update(); // atualiza lcd myGLCD.printNumF(valorPelt2, 0, 50, 24); myGLCD.print("Aquecer", LEFT, 24); valorPelt2 = valorPelt;}else if (valorPelt < 0 && umidade < Umid) { digitalWrite(direcaoA, LOW); digitalWrite(relePin, HIGH);// Liga o rele de reversão da Peltier(Esfriar) analogWrite(pwmA, -valorPelt); myGLCD.printNumF(-valorPelt2, 0, 50, 24); myGLCD.print("Esfriar", LEFT, 24); valorPelt2 = valorPelt;
}
if (valorPelt >= 0 && umidade >= Umid) {// Caso a humidade esteja alta e temperatura menor que 10 graus desligar peltier valorPelt = 0; analogWrite(pwmA, valorPelt); myGLCD.printNumF(valorPelt2, 0, 50, 24); myGLCD.print("Desl. ", LEFT, 24); valorPelt2 = valorPelt;}else if (valorPelt <= 0 && umidade >= Umid) { valorPelt = 0; analogWrite(pwmA, valorPelt); myGLCD.printNumF(valorPelt2, 1, 50, 24); myGLCD.print("Desl. ", LEFT, 24); valorPelt2 = valorPelt;}
//*************************************************//********* IMPRIME NO DISPLAY ********************if (iniciar == 0) { myGLCD.print("Iniciando..", CENTER, 1); //posição da escrita "Temperatura" no display myGLCD.print("Humid. ", LEFT, 12); //posição da escrita "Temperatura" no display myGLCD.printNumF(umidade, 0, 51, 12); //Posição do valor da Humidade no display myGLCD.print("% ", RIGHT, 12); //posição da escrita "%" no display // myGLCD.print("STime. ", LEFT, 12); // myGLCD.printNumF(SampleTime, 0, 51, 12); myGLCD.print("SetPoint", LEFT, 36); myGLCD.printNumF(valorPot, 1, 55, 36 ); myGLCD.update(); // atualiza lcd}if (iniciar == 1) { myGLCD.print("Temp.", LEFT, 1); //posição da escrita "Temperatura" no display myGLCD.printNumF(temperatura3, 2, 40, 1); //Posição do valor da temperatura no display _ Para o DHT11 -- o primeiro "1" descreve o numero de casas decimais myGLCD.print("C ", RIGHT, 1); //posição da escrita "Graus Temperatura" no display myGLCD.print("Humid. ", LEFT, 12); //posição da escrita "Temperatura" no display myGLCD.printNumF(umidade, 0, 51, 12); //Posição do valor da Humidade no display myGLCD.print("% ", RIGHT, 12); //posição da escrita "%" no display// myGLCD.print("STime. ", LEFT, 12); // myGLCD.printNumF(SampleTime, 0, 51, 12); myGLCD.print("SetPoint", LEFT, 36); myGLCD.printNumF(valorPot, 1, 55, 36 ); myGLCD.update(); // atualiza lcd}//*************************************************//*************************************************valorPot = Setpoint; // Ajusta o valorPot para o Setpoint desejado.soma = 0;i = 0;//--------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------while (Serial.available() > 0){ int index = 0; delay(100); // permite o buffer encher int numChar = Serial.available(); if (numChar > 27) { numChar = 27; } while (numChar--) { buffer[index++] = Serial.read(); } splitString(buffer);}
mySerial.write(GetData, sizeof(GetData)); //Envia o pacote de solicitação de transmissão para o Densímetro pelo pino de transmissão escolhido (02delay(100);//-----------------------------------------------------------------------------------------unsigned long currentMillis1 = millis(); //Tempo atual em msunsigned long changeTime;if (currentMillis1 - previousMillis1 > Time1){ previousMillis1 = currentMillis1;//Salva o tempo atual if (temperatura3 <= MinTemp && (millis() - changeTime) > previousMillis1){ valorPelt2 = valorPelt2; digitalWrite(Buzz, HIGH); delay(100); digitalWrite(Buzz, LOW);} }
}//Void
//***************************************** FIM DO VOID LOOP *********************************************************************
//-----------------------------------------------------------------------//---------- Tratamento dos caracteres recebidos -----------------------void splitString(char* data){ char* parameter; parameter = strtok (data, " ,"); while (parameter != NULL) { setLED(parameter); parameter = strtok (NULL, " ,"); }
// Limpa os textos e o buffer serial for (int x = 0; x < 27; x++) { buffer[x] = '\0'; } Serial.flush();}//-----------------------------------------------------------------------//-------- Identificação dos pacotes que chegam pela serial ------------void setLED(char* data) { if ((data[0] == '@') && (data[13] == '!')) { if ((data[18] != 'N') && (data[19] != 'o') || (data[18] != 'D') && (data[19] != 'e'))// Caso o densímetro envie para a serial os // caracteres 'N' e 'o' nas posições 18 ou 19 ou os caracteres 'D' e 'o' nas posições 18 ou 19 { Temp_Ap = String(Val_05) + String(Val_06) + String(Val_08) + String(Val_09); // Concaterna strings Temp_Full = Temp_Ap.toInt(); // transforma strint]g em int Temp_Full = Temp_Full / 100;
/* Serial.println("Temperatura ");//Envia a temperatura para a saida serial monitor Serial.println(Temp_Full); Serial.println(); delay(100); */
} // Variavel float para guardar densidade e temperatura Val_05 = data[6] & 0x0F; // Remove parte alta do byte buffer 6 Val_06 = data[7] & 0x0F; // Remove parte alta do byte buffer 7 Val_08 = data[9] & 0x0F; // Remove parte alta do byte buffer 9 Val_09 = data[10] & 0x0F; // Remove parte alta do byte buffer 10
}
//---------------------------------------------------------------------------------------
} //Fim do programa !!!
…
Adicionado por Max Anderson ao 7:30 em 25 janeiro 2016
mosa “luzinha azul”
No mundo do IoT e da automação em geral, é muito comum deparar-nos com controles remotos via celulares utilizando tecnologia BT. Isso é devido a 3 componentes básicos mas muito importantes:
Plataforma de desenvolvimento para Android
Módulos BT baratos e acessíveis (Como por exemplo o HC-06)
E claro, o velho e bom Arduino....
Neste tutorial, vou desenvolver algumas idéias de como controlar as saídas de um Arduíno através de um celular de maneira a mover um Robot, acionar lâmpadas em uma casa, etc.
No mercado é comum encontrar módulos de BT 3.0 “Master-Slave” como o HC-05 e “Slaves” como o HC-06. Já mais recentemente, apareceram os HC-08 e HC-10 que trabalham com tecnologia BT 4.0 ou BLE (“Bluetooth Low Energy”). Os módulos BLE são os únicos que podem ser conectados a um Iphone, pois infelizmente a Apple não fornece suporte a ao BT 3.0.
Para os projetos discutidos aqui, usarei um HC-06 que é bem popular e barato (Bye, bye, Iphone, vamos de Android!). O Módulo é alimentado com 5V o que faz com que ele seja facilmente conectado a um Arduino UNO por exemplo, para receber e transmitir informações a outros dispositivos como um PC ou um telefone celular. Seus pinos de transmissão e recepção podem ser conectados diretamente ao UNO, não havendo a necessidade de se utilizar divisores de tensão como vimos no caso do ESP8266.
Na prática, o HC-06 deve ser ligado diretamente aos pinos 0 e 1 do Arduino (Serial):
HC06-Tx ao Arduino pin 0 (Rx)
HC06-Rx ao Arduino pin 1 (Tx)
Ao se usar a entrada serial por HW do UNO é muito importante lembrar-se que o HC-06 não pode estar fisicamente conectado aos pinos 0 e 1 durante a carga do programa, isso porque o USB também usa essa mesma serial. Uma maneira simples de se contornar esse probleminha (se seu projeto não utiliza muitos GPIOs do UNO) é usar uma porta serial por SW através da library SoftwareSerial (a mesma que usamos no caso do ESP8266). Em nosso caso aqui, usaremos os pinos 10 e 11 do UNO (Tx, Rx respectivamente).
O passo seguinte será escrever um codigo bem simples para se poder testar, programar e inicializar o HC-o6:
Para iniciar, incluir a Library Software Serial, definindo a variável “BT” como a nova porta serial.
#include <SoftwareSerial.h> SoftwareSerial BT(10, 11); // RX, TX String command = ""; // Stores response of bluetooth device
void setup() { Serial.begin(9600); Serial.println("Type AT commands!"); BT.begin(9600); // HC-06 usually default baud-rate }
Em seguida vem o corpo principal do código que simplesmente espera por dados vindos do BT e uma vez que eles chegem, os mesmos são escritos no Serial Monitor. Da mesma maneira, se podem enviar comandos AT desde o monitor serial até o módulo HC-06.
void loop() { if (BT.available()) // Read device output if available. { while(BT.available()) // While there is more to be read, keep reading. { delay(10); //Delay added to make thing stable char c = BT.read(); //Conduct a serial read command += c; //build the string. } Serial.println(command); command = ""; // No repeats } if (Serial.available()) { delay(10); // The DELAY! ********** VERY IMPORTANT ******* BT.write(Serial.read()); } }
Uma vez carregado o programa, faça alguns testes básicos. Por exemplo:,
Envie “AT“, o módulo deverá responder “OK“.
Pergunte a versão do Firmware: “AT+VERSION”, o módulo deverá responser, por exemplo: “linvorV1.8“.
Com o HC-06 é possível definir um nome para o módulo por exemplo: “AT+NAMEMJRoBot_BT_HC06“. Mas diferente de outros módulos, voce não conseguirá saber qual é o nome que está definido para o módulo. Ao se enviar o comando anterior, o HC-06 responderá simplesmente: “OKsetname”.
Em geral, o HC-o6 vem de fábrica com o password (ou PIN): 1234. Voce poderá definir um novo com o comando AT: AT+PINxxxx onde ‘xxxx‘ serão 4 números.
OK! Módulo conectado ao UNO e funcionando. Hora de lançar mão do velho e bom celular Android!!!
Existem muitas apps na loja da Google que podem ser utilizadas. Vou sugerir duas delas, por serem as que usarei em meus tutoriais. Essas apps foram desenvolvidas por mim utilizando o MIT Application2 tool (ver projeto aqui) e estão disponíveis sem custo na loja da Google:
MJRoBoT II BT Control
MJRoBot BT Digital Analog Voice Control
O App MJR0Bot II foi desenvolvido para comandar Robots. Ele basicamente envia um caracter para cada comando de direção, modos AUTO/MANUAL, velocidade + e velocidade-. Alem de permitir o envio de mensagens em modo texto.
O App. MJRoBot Digital Analog Voice Control, envia comandos para acionamento digitais (ligar/desligar) tanto por botões como por voz e comandos numéricos para controle de PWMs (0-255).
Faça o Download de qualquer uma das duas Apps, vá ao set-up do celular e procure o modulo BT fazendo a conexão (entre com o PIN 1234 ou algum outro definido por você). Isso deverá ser feito uma única vez, pois o celular guardará os dados de conexão. Uma vez que o celular e o HC-06 estão conversando, é só usar as APPs.
A partir da segunda vez, ao lançar-se a app, o modulo BT estará desconectado.
Acione o botão de BT, para que o app informe dos modulos disponíveis:
Selecione o nome do módulo (No caso é esse com o HC-06 ao final).
O App então mostrará “CONNECTED”, informando que está “pared” com o HC-06
A partir daí, é só ir acionando os botões do APP e observar no Monitor Serial, o que é que o APP está enviando.
Por exemplo, acionando “ON” e “OFF” sequencialmente para os 4 devices, no caso da APP MJRoBot Digital Analog Voice Control, o resultado seria:
dev1on dev1off dev2on dev2off dev3on dev3off dev4on dev4off
Agora que já temos um App para o Android e sabemos como funciona um modulo BT, vamos colocar a mão na massa e criar algo de util!
Controlando as saídas do Arduino.
Vamos construir o circuito abaixo:
A idéia será usar o App MJRoBot Digi/Ana/Voice Ctrl para acender e apagar os LEDS e também controlar a intensidade dos mesmos usando PWM.
Estaremos relacionando:
Device 1: "dev1on/dev1off" ==> LED Red ==> Pin 3 do UNO
Device 2: "dev2on/dev2off" ==> LED Yellow ==> Pin 5 do UNO
Device 3: "dev3on/dev3off" ==> LED Green==> Pin 6 do UNO
Device 4: "dev4on/dev4off" ==> LED Blue==> Pin 9 do UNO
Ou seja, ao acionar o botão “ON” relacionado ao “Device 1”, a mensagem de texto “dev1on”será enviada ao Arduino. Ao receber essa mensagem, o LED vermelho deverá acender e assim por diante.
Observe que os 4 pinos são pinos com capacidade de gerar PWM. Isso é importante para a utilização dos “sliders” da App, que enviarão valores para controlar a intensidade dos LEDs via PWM:
Dev A0: "r/ 0-255" ==> LED Red ==> Pin 3 do UNO
Dev A1: "y/ 0-255" ==> LED Yellow ==> Pin 5 do UNO
Dev A2: "g/ 0-255" ==> LED Green==> Pin 6 do UNO
Dev A3: "b/ 0-255" ==> LED Blue==> Pin 9do UNO
No caso dos controles deslizantes (“sliders”), antes dos valores para controle do PWM (0 a 255), um caracter será enviado para que o Arduino saiba de que “slider” estará chegando o comando.
O Código:
Setup inicial:
#include <SoftwareSerial.h>
SoftwareSerial BT(10, 11); //TX, RX respectively String device;
const int dev1 = 3; //PWM const int dev2 = 5; //PWM const int dev3 = 6; //PWM const int dev4 = 9; //PWM
void setup() { BT.begin(9600); Serial.begin(9600);
pinMode(dev1, OUTPUT); pinMode(dev2, OUTPUT); pinMode(dev3, OUTPUT); pinMode(dev4, OUTPUT); }
Podemos dividir a parte principal do programa em 4 blocos:
Espera dos comandos BT e construção da variável “device”
Acionamento dos LEDS a partir dos botões
Acionamento dos LEDS a partir de comandos de voz
Controle do intensidade dos LEDs via Sliders
void loop() { while (BT.available()) //Check if there is an available byte to read { delay(10); //Delay added to make thing stable char c = BT.read(); //Conduct a serial read device += c; //build the string. } if (device.length() > 0) { Serial.println(device); // Button control: if (device == "dev1on") {digitalWrite(dev1, HIGH);} else if (device == "dev1off") {digitalWrite(dev1, LOW);} else if (device == "dev2on") {digitalWrite(dev2, HIGH);} else if (device == "dev2off") {digitalWrite(dev2, LOW);} else if (device == "dev3on") {digitalWrite(dev3, HIGH);} else if (device == "dev3off") {digitalWrite(dev3, LOW);} else if (device == "dev4on") {digitalWrite(dev4, HIGH);} else if (device == "dev4off") {digitalWrite(dev4, LOW);}
// Voice control: else if (device == "ligar um" || device == "Ligar 1") {digitalWrite(dev1, HIGH);} else if (device == "desligar um" || device == "desligar 1") {digitalWrite(dev1, LOW);} else if (device == "ligar som" || device == "Ligar som") {digitalWrite(dev2, HIGH);} else if (device == "desligar som" || device == "Desligar som") {digitalWrite(dev2, LOW);} else if (device == "ligar TV" || device == "Ligar TV") {digitalWrite(dev3, HIGH);} else if (device == "desligar TV" || device == "Desligar TV") {digitalWrite(dev3, LOW);} else if (device == "ligar quarto" || device == "Ligar quarto") {digitalWrite(dev4, HIGH);} else if (device == "desligar quarto" || device == "Desligar quarto") {digitalWrite(dev4, LOW);}
// Slider control: char colour = device[0]; int value = device[2]; Serial.print(" "); Serial.println(value); if ( colour == 'r') { analogWrite(dev1, value); // use value to set PWM for LED brightness } if ( colour == 'y') { analogWrite(dev2, value); // use value to set PWM for LED brightness } if ( colour == 'g') { analogWrite(dev3, value); // use value to set PWM for LED brightness } if ( colour == 'b') { analogWrite(dev4, value); } device=""; //Reset the variable } }
Deixo aqui o link para os códigos usados neste tutorial:
Link para os códigos Arduino
No vídeo abaixo, uma demonstração da porção programa acima (botões & Slider):
Vídeo demo comando por botões e Slider
O controle de dispositivos IoT por voz é uma tendência nos dias de hoje. Conseguir este tipo de controle com o conjunto Arduino/HC-06/Android é extremamente simples. Os dispositivos Android já possuem essa característica “de fábrica”. No App que desenvolvi, apenas acrescentei um botão que faz com que o Android “escute” um comando e o envie em formato texto para o Arduino. O codigo se encarrega de “ler” a string que chega.
Em vermelho, ressalto no código alguns possíveis comandos de voz. Ao receber por “Ligar TV” por exemplo, o LED verde (correspondente ao device 3) acenderá (em vez do LED podíamos ter uma relé que ligaria a TV).
No vídeo abaixo, uma pequena demonstração do controle por voz:
Vídeo demo de comandos por voz.
Bom, acredito que já é possível ver o enorme potencial do controle de “coisas” usando BT/Android/Arduino. Em meus próximos posts estarei desenvolvendo Robots que poderão ser controlados remotamente como vimos aqui.
Para mais tutoriais, demos, vídeos, etc. visite meu blog:
MJRoBot.org
Um abraço e até mais!
…
Adicionado por Marcelo Rovai ao 19:45 em 31 janeiro 2016
amente segue resposta obtida na software serial.
Starting ProcessGprsMsg();AT+CMGF=1 ProcessGprsMsg();ProcessGprsMsg(); OK ProcessGprsMsg();ProcessGprsMsg(); +CMTI: "SM",6
Si alguem poder me da uma força agradeço..
segue esbolso usado.
ch = strstr((char *)comm_buf, compare_string); if (ch != NULL) { ret_val = 1; } else { /*#ifdef DEBUG_PRINT DebugPrint("\r\nDEBUG: expected string was NOT received\r\n", 0); #endif */ } }
return (ret_val); }
byte WaitResp(uint16_t start_comm_tmout, uint16_t max_interchar_tmout) { byte status;//programmer gudjon@undri.com
//todo:sorry about the messy coding (not enough time to fix)
#include <SoftwareSerial.h>
//FOR MEGA decomment line below. On the EFCom shield DIS-connect the jumpers and put jumperwires from SHIELD RX to MEGA 51 and from SHIELD TX to MEGA 50SoftwareSerial mySerial(50, 51);
//FOR UNO decomment line below. On the EFCom shield connect the jumers, TX to D2 and RX to D3.//SoftwareSerial mySerial(2, 3);
/*EFcom/GPRS Shield Light meaning.------------------------------------------------------------------------| LED STATUS DESCRIPTION || --- ----------------- ---------------------------------------------|| PWR ON Power on the EFcom || PWR OFF Power off the EFcom || STA ON Power on the SIM900 OFF Power Off the SIM900 || NET OFF SIM900 is not running || NET 64ms ON/800ms OFF SIM900 not register the Network || NET 64ms ON/3000ms OFF SIM900 registered to the network || NET 64ms ON/300ms OFF GPRS communication is established |--- -------------------------------------------------------------------*/
///////////////////////////////////////////////////////////////////////////////////////
//SELECT HERE WICH PINS YOU WANT TO CONTROL ON THE ARDUINO (THEY must be in sequence)#define OPIN_FIRST 30#define OPIN_LAST 33//when program starts turn all pins on or off. allowed values are either HIGH or LOW#define OPIN_STARTSTATE LOW//The controlling phonenumber;#define PHONENUMBER "meu numero"
///////////////////////////////////////////////////////////////////////////////////////
String msg = String("");int SmsContentFlag = 0;
#define GSM_POWER 6 /*EFCom power pin*/#define GSM_RESET 5 /*EFCom reset pin**/
// S T A R T S T A R T Borrowed from GSMSHIELD Library S T A R T S T A R T //// some constants for the IsRxFinished() method// length for the internal communication buffer#define COMM_BUF_LEN 300#define RX_NOT_STARTED 0#define RX_ALREADY_STARTED 1
// variables connected with communication bufferbyte *p_comm_buf; // pointer to the communication bufferbyte comm_buf_len; // num. of characters in the bufferbyte rx_state; // internal state of rx state machine uint16_t start_reception_tmout; // max tmout for starting receptionuint16_t interchar_tmout; // previous time in msec.unsigned long prev_time; // previous time in msec.byte comm_buf[COMM_BUF_LEN+1]; // communication buffer +1 for 0x00 termination enum rx_state_enum {RX_NOT_FINISHED = 0, // not finished yetRX_FINISHED, // finished, some character was receivedRX_FINISHED_STR_RECV, // finished and expected string receivedRX_FINISHED_STR_NOT_RECV, // finished, but expected string not receivedRX_TMOUT_ERR, // finished, no character received // initial communication tmout occurredRX_LAST_ITEM};void RxInit(uint16_t start_comm_tmout, uint16_t max_interchar_tmout){rx_state = RX_NOT_STARTED;start_reception_tmout = start_comm_tmout;interchar_tmout = max_interchar_tmout;prev_time = millis();comm_buf[0] = 0x00; // end of stringp_comm_buf = &comm_buf[0];comm_buf_len = 0;mySerial.flush(); // erase rx circular buffer}
byte IsRxFinished(void){byte num_of_bytes;byte ret_val = RX_NOT_FINISHED; // default not finished
if (rx_state == RX_NOT_STARTED) {// Reception is not started yet - check tmoutif (!mySerial.available()) {// still no character received => check timeout
if ((unsigned long)(millis() - prev_time) >= start_reception_tmout) {// timeout elapsed => GSM module didn't start with response// so communication is takes as finishedcomm_buf[comm_buf_len] = 0x00;ret_val = RX_TMOUT_ERR;}}else {// at least one character received => so init inter-character // counting process again and go to the next stateprev_time = millis(); // init tmout for inter-character spacerx_state = RX_ALREADY_STARTED;}}
if (rx_state == RX_ALREADY_STARTED) {// Reception already started// check new received bytes// only in case we have place in the buffernum_of_bytes = mySerial.available();// if there are some received bytes postpone the timeoutif (num_of_bytes) prev_time = millis();// read all received bytes while (num_of_bytes) {num_of_bytes--;if (comm_buf_len < COMM_BUF_LEN) {// we have still place in the GSM internal comm. buffer =>// move available bytes from circular buffer // to the rx buffer*p_comm_buf = mySerial.read();
p_comm_buf++;comm_buf_len++;comm_buf[comm_buf_len] = 0x00; // and finish currently received characters// so after each character we have// valid string finished by the 0x00}else {mySerial.read();}}if ((unsigned long)(millis() - prev_time) >= interchar_tmout) {comm_buf[comm_buf_len] = 0x00; // for sure finish string again// but it is not necessaryret_val = RX_FINISHED;}}return (ret_val);}
/**********************************************************Method checks received bytes
compare_string - pointer to the string which should be find
return: 0 - string was NOT received1 - string was received**********************************************************/byte IsStringReceived(char const *compare_string){char *ch;byte ret_val = 0;
if(comm_buf_len) {#ifdef DEBUG_ONSerial.println("ATT: ");Serial.print(compare_string);Serial.print("RIC: ");Serial.println((char *)comm_buf);#endif
RxInit(start_comm_tmout, max_interchar_tmout); // wait until response is not finished do { status = IsRxFinished(); } while (status == RX_NOT_FINISHED); return (status); }
///////////////þarf eþtta kannski ekki sjá fyrir ofan byte WaitResp(uint16_t start_comm_tmout, uint16_t max_interchar_tmout, char const *expected_resp_string) { byte status; byte ret_val;
RxInit(start_comm_tmout, max_interchar_tmout); // wait until response is not finished do { status = IsRxFinished(); } while (status == RX_NOT_FINISHED);
if (status == RX_FINISHED) { // something was received but what was received? // --------------------------------------------- if(IsStringReceived(expected_resp_string)) { // expected string was received // ---------------------------- ret_val = RX_FINISHED_STR_RECV; } else { ret_val = RX_FINISHED_STR_NOT_RECV; } } else { // nothing was received // -------------------- ret_val = RX_TMOUT_ERR; } return (ret_val); } ///////////////þarf eþtta kannski ekki endir
/********************************************************** Method sends AT command and waits for response
return: -1, // no response received 0, // response_string is different from the response 1, // response_string was included in the response **********************************************************/ char SendATCmdWaitResp(char const *AT_cmd_string, uint16_t start_comm_tmout, uint16_t max_interchar_tmout, char const *response_string, byte no_of_attempts) { byte status; char ret_val = -1; byte i;
for (i = 0; i < no_of_attempts; i++) { // delay 500 msec. before sending next repeated AT command // so if we have no_of_attempts=1 tmout will not occurred if (i > 0) delay(500);
mySerial.println(AT_cmd_string); status = WaitResp(start_comm_tmout, max_interchar_tmout); if (status == RX_FINISHED) { // something was received but what was received? // --------------------------------------------- if(IsStringReceived(response_string)) { ret_val = 1; break; // response is OK => finish } else ret_val = 0; } else { // nothing was received // -------------------- ret_val = -1; } } return (ret_val);
}//char SendATCmdWaitRes
/********************************************************** Method sends SMS
number_str: pointer to the phone number string message_str: pointer to the SMS text string
return: ERROR ret. val: --------------- -1 - comm. line to the GSM module is not free -2 - GSM module didn't answer in timeout -3 - GSM module has answered "ERROR" string
OK ret val: ----------- 0 - SMS was not sent 1 - SMS was sent
an example of usage: GSM gsm; gsm.SendSMS("00XXXYYYYYYYYY", "SMS text"); **********************************************************/ char SendSMS(char *number_str, char *message_str) { char end[2]; end[0]=0x1a; end[1]='\0';/* Ctrl+Z */ mySerial.print("\r"); delay(1000); //Wait for a second while the modem sends an "OK" mySerial.print("AT+CMGF=1\r"); //Because we want to send the SMS in text mode delay(1000); //mySerial.print("AT+CSCA=\"+919032055002\"\r"); //Setting for the SMS Message center number, //delay(1000); //uncomment only if required and replace with //the message center number obtained from //your GSM service provider. //Note that when specifying a tring of characters // " is entered as \" mySerial.print("AT+CMGS=\"");mySerial.print(number_str); mySerial.print("\"\r"); //Start accepting the text for the message //to be sent to the number specified. //Replace this number with the target mobile number. delay(1000); mySerial.print(message_str); mySerial.print("\r"); //The text for the message delay(1000); mySerial.print(end); }
//// E N D E N D Borrowed from GSMSHIELD Library E N D E N D // //// //// S E T U P S E T U P S E T U P S E T U P S E T U P S E T U P S E T U P S E T U P S E T U P S E T U P S E T U P //// S E T U P S E T U P S E T U P S E T U P S E T U P S E T U P S E T U P S E T U P S E T U P S E T U P S E T U P //// S E T U P S E T U P S E T U P S E T U P S E T U P S E T U P S E T U P S E T U P S E T U P S E T U P S E T U P void setup() { mySerial.begin(9600); Serial.begin(9600); if (-1 == SendATCmdWaitResp("AT", 500, 100, "OK", 5)) { digitalWrite(GSM_POWER, HIGH);delay(3000); digitalWrite(GSM_POWER, LOW);delay(2000); } for(int i=OPIN_FIRST;i<OPIN_LAST+1;i++) { pinMode(i, OUTPUT); digitalWrite(i,OPIN_STARTSTATE); } Serial.println( "Starting" ); mySerial.println( "AT+CMGF=1" ); delay(200); } boolean bFoundMSGandNumber=false; void loop() { char SerialInByte; if(mySerial.available()) { SerialInByte = (unsigned char)mySerial.read(); delay(5);
if( SerialInByte == 13 ){ ProcessGprsMsg(); } if( SerialInByte == 10 ){ } else { msg += String(SerialInByte); } }
}
void ProcessSms( String sms ){ Serial.print("ProcessSms:");Serial.println(sms); String finna = String("xxxxx"); for(int i=OPIN_FIRST;i<OPIN_LAST+1;i++) { finna=String("Off");finna+=i; if( sms.indexOf(finna) >= 0 || sms.indexOf("Offall") >= 0 ){digitalWrite(i, LOW); Serial.println(finna);} } for(int i=OPIN_FIRST;i<OPIN_LAST+1;i++) { finna=String("On");finna+=i; if( sms.indexOf(finna) >= 0 || sms.indexOf("Onall") >= 0){digitalWrite(i, HIGH); Serial.println(finna);} } if( sms.indexOf("List") >= 0 ) { finna="stada"; for(int i=OPIN_FIRST;i<OPIN_LAST+1;i++) { finna+=" ";finna+=i;finna+="=";finna+=digitalRead(i); } int iSize=finna.length()+1; char charBuf[iSize]; finna.toCharArray(charBuf, iSize); SendSMS(PHONENUMBER, charBuf); } mySerial.println( "AT+CMGDA=\"DEL ALL\"" ); delay(200); } // EN: Request Text Mode for SMS messaging void GprsTextModeSMS(){ mySerial.println( "AT+CMGF=1" ); }
void GprsReadSmsStore( String SmsStorePos ){ mySerial.print( "AT+CMGR=" ); mySerial.println( SmsStorePos ); }
// EN: Clear the GPRS shield message buffer void ClearGprsMsg(){ msg = ""; }
// EN: interpret the GPRS shield message and act appropiately void ProcessGprsMsg() { Serial.print( "ProcessGprsMsg();");Serial.println(msg); if( msg.indexOf( "Call Ready" ) >= 0 ){ Serial.println( "*** GPRS Shield registered on Mobile Network ***" ); GprsTextModeSMS(); } //todo: búa til define string úr PHONENUMBER char findMe[strlen(PHONENUMBER)+2];strcpy(findMe,PHONENUMBER);strcat(findMe,"\""); if( (msg.indexOf( "+CMT" ) >= 0) && (msg.indexOf( findMe )>0) ){ Serial.println( "*** SMS Received ***" ); bFoundMSGandNumber=true; } else { if(bFoundMSGandNumber==true) { ProcessSms( msg ); } bFoundMSGandNumber=false; } ClearGprsMsg(); SmsContentFlag = 0; }
int getValidPin(char *pNum) { int iNum=strlen(pNum); if (iNum<1 || iNum>2) return false;//pin must be from 0..99 iNum = atoi (pNum); if ((iNum < OPIN_FIRST) || (iNum > OPIN_LAST)) return false;//num must be equal or between OPIN_FIRST and OPIN_FIRST
return iNum; }…
Adicionado por Paulo souza ao 21:39 em 8 setembro 2014