Precisa de conectividade em seus projetos? Então experimente a Gboard. Seguramente não é a melhor placa do mercado, mas é um excelente custo-benefício. Ao preço de um pouco mais de R$ 40,00 (sem o frete), temos um Arduino com Atmega 328p e um módulo GSM/GPRS, denominado SIM900, na mesma placa. Pronto, a propaganda acabou (e de graça!). Mas não vão faltar críticas ao produto: manual e sketch de exemplo fornecidos no site do fabricante são muito ruins e ainda por cima não funcionam sem as correções pinçadas em outros sites e blogs na internet. Outro problema: alto consumo de energia.Por último, para programar o Arduino e acessar o SIM900 é preciso adquirir um módulo FT232(Foca).
Obs: O projeto foi atualizado após quase três anos e infelizmente os preços subiram. Mesmo assim, a Gboard ainda é um bom negócio, saindo por um pouco mais de $50,00.
O Solucionática adquiriu uma Gboard e fizemos alguns testes bem sucedidos. O difícil foi encontrar o link certo para o melhor site com informações sobre essa placa. Após alguma pesquisa chegamos a este: http://www.cooking-hacks.com/index.php/documentation/tutorials/arduino-gprs-gsm-quadband-sim900. O Cooking Hacks é um site excelente. Tudo que fazem é muito bem explicado e documentado, ao contrário do fornecedor Itead Studio. São os contratempos de se comprar produtos mais baratos (os clones).
Outro link importante é da biblioteca GSMSHIELD que pode ser baixada nessa página: http://www.cooking-hacks.com/index.php/let-s-cook/fritzing-libraries. Mesmo desenvolvido para um shield fabricado por eles (custa a bagatela de R$ 180,00 !!!), os sketch funcionam perfeitamente (Arduino IDE 1.0.5, Ubuntu Linux).
Para instalar a biblioteca, basta fazer o download e descompactar nas pasta onde o IDE do Arduino está instalado. Procure a pasta libraries e dê o ok. Note que a biblioteca ficará disponível somente depois de fechar e reabrir o IDE. Outro problema frequente é quanto ao nome da biblioteca, pois em geral vem com alguns caracteres inválidos ou muito extenso, então renomeie para GSMSHIELD e tudo vai dar certo.
Agora é só testar...não! É preciso configurar os straps da placa. No manual da Gboard há explicações um pouco confusas, pelo menos para nós da Solucionática. De todo modo, conseguimos - assim qualquer um pode também! Antes, uma dica: Há dois conjuntos de pinos que são usados na configuração das portas seriais de acesso. O sketch usa os pinos 0, 1 (D0 e D1) para a serial física (hardware) e 2, 3 (D2 e D3) para a serial lógica (software).
Na figura acima temos ST e SR (serial Tx e RX) que serão conectados a D0 e D1, respectivamente. E XT e XR (são TX e RX do serial via software, onde o x significa xbee) devem ser ligados a D2 e D3, respectivamente. Esse é um dos cuidados que devem ser tomados. o outro é quanto à fonte de alimentação externa que deve ser ligada, mesmo que o módulo esteja sendo alimentado pela usb do micro. Como dissemos antes, o consumo do módulo é alto e em algumas funções, como GPRS, há picos que derrubam a conexão. Recomendamos uma fonte de 12V , 1A. Ou usar baterias recarregáveis de 3,7 V, em série. O módulo aceita de 7V até 20V em sua entrada, mas esquenta muito o regulador de tensão (5V e 3,3V) quando alimentado com tensões maiores que 12V. O barramento, por sua vez, trabalha com 3,3 V.
De início, testamos a Gboardcom com o sketch GSMSHIELD AT commands. E como tudo deu certo, passamos para outros testes. Notamos que às vezes foi preciso desconectar o cabo usb e reiniciar a Gboard (reset rústico), desligando sua alimentação, pois travou após o upload do novo sketch.
Nos sketches (CLIENT, p. ex) que acessam páginas da internet, o endereço fornecido é www.google.com. No entanto, tivemos melhores resultados modificando a página para www.google.com.br.
O sistema operacional que você usa pode influenciar na compilação do sketch. Nós usamos Linux (experimente você também!) o que nos dá mais controle sobre a máquina. No Windows deve funcionar perfeitamente, usando a IDE 1.0. Essa observação diz respeito diretamente aos problemas observados com o uso da biblioteca SoftSerial, utilizada nos sketches de teste.
Finalmente: é possível construir um telefone celular completo com a Gboard? Sim900!
NOVO - Após alguns anos, finalmente atualizamos o projeto! Primeiramente, vamos indicar a forma correta de configurar os estrapes da Gboard. Usaremos como base a biblioteca GSMSHIELD, que pode ser encontrada nas IDE's acima da versão 1.0.4. O primeiro programa de teste é o GSMSHIELD_TEST. Observe que o sketch usa a biblioteca SoftwareSerial e já estão definidos os pinos 2 e 3. Se por um acaso seu módulo GSM é de um modelo novo, aquele que pode escolher qual pino usar como TX/RX é obrigatório alterar o arquivo GSM.cpp e trocar os referidos pinos.
Assim, os estrapes devem ser conectados assim: ST->D0 , SR->D1, XT->D2, XR->D3. O quê isso significa? Estamos usando a porta serial física da Gboard (pinos D0 e D1) para a comunicação entre a FOCA (lembrem-se que a Gboard precisa de um conversor serial/usb para se comunicar com o pc e ser programada) e D2 e D3 para prover a comunicação entre a Gboard e o SIM900.
#include "SIM900.h"
#include <SoftwareSerial.h>
#include "inetGSM.h"
//#include "sms.h"
//#include "call.h"
//To change pins for Software Serial, use the two lines in GSM.cpp.
//GSM Shield for Arduino
//www.open-electronics.org
//this code is based on the example of Arduino Labs.
//Simple sketch to start a connection as client.
InetGSM inet;
//CallGSM call;
//SMSGSM sms;
char msg[50];
int numdata;
char inSerial[50];
int i=0;
boolean started=false;
void setup()
{
//Serial connection.
Serial.begin(9600);
Serial.println("GSM Shield testing.");
//Start configuration of shield with baudrate.
//For http uses is raccomanded to use 4800 or slower.
if (gsm.begin(4800)){
Serial.println("\nstatus=READY");
started=true;
gsm.forceON();
}
else Serial.println("\nstatus=IDLE");
if(started){
//GPRS attach, put in order APN, username and password.
//If no needed auth let them blank.
if (inet.attachGPRS("internet.wind", "", ""))
Serial.println("status=ATTACHED");
else Serial.println("status=ERROR");
delay(1000);
//Read IP address.
gsm.SimpleWriteln("AT+CIFSR");
delay(5000);
//Read until serial buffer is empty.
gsm.WhileSimpleRead();
//TCP Client GET, send a GET request to the server and
//save the reply.
numdata=inet.httpGET("www.google.com", 80, "/", msg, 50);
//Print the results.
Serial.println("\nNumber of data received:");
Serial.println(numdata);
Serial.println("\nData received:");
Serial.println(msg);
}
};
void loop()
{
//Read for new byte on serial hardware,
//and write them on NewSoftSerial.
serialhwread();
//Read for new byte on NewSoftSerial.
serialswread();
};
void serialhwread(){
i=0;
if (Serial.available() > 0){
while (Serial.available() > 0) {
inSerial[i]=(Serial.read());
delay(10);
i++;
}
inSerial[i]='\0';
if(!strcmp(inSerial,"/END")){
Serial.println("_");
inSerial[0]=0x1a;
inSerial[1]='\0';
gsm.SimpleWriteln(inSerial);
}
//Send a saved AT command using serial port.
if(!strcmp(inSerial,"TEST")){
Serial.println("SIGNAL QUALITY");
gsm.SimpleWriteln("AT+CSQ");
}
//Read last message saved.
if(!strcmp(inSerial,"MSG")){
Serial.println(msg);
}
else{
Serial.println(inSerial);
gsm.SimpleWriteln(inSerial);
}
inSerial[0]='\0';
}
}
void serialswread(){
gsm.SimpleRead();
}
APLICAÇÃO: Alarme residencial com sensor de presença
Com um sensor de presença e algumas modificações em nosso sketch, podemos construir um verdadeiro alarme residencial que avisa enviando um sms caso alguém passe no raio de ação do sensor:
#include "SIM900.h"
#include <SoftwareSerial.h>
//We don't need the http functions. So we can disable the next line.
//#include "inetGSM.h"
#include "sms.h"
#include "call.h"
//To change pins for Software Serial, use the two lines in GSM.cpp.
//GSM Shield for Arduino
//www.open-electronics.org
//this code is based on the example of Arduino Labs.
//Simple sketch to check if an incoming call is from an authorized
//number and in this case, send to this number an SMS with the value
//of a digital input.
//We have to create the classes for SMSs and calls.
CallGSM call;
SMSGSM sms;
char number[20];
byte stat=0;
int value=0;
int pin=1;
char value_str[5];
void setup()
{
pinMode(pin,INPUT);
//Serial connection.
Serial.begin(9600);
Serial.println("GSM Shield testing.");
//Start configuration of shield with baudrate.
//For http uses is raccomanded to use 4800 or slower.
if (gsm.begin(2400))
Serial.println("\nstatus=READY");
else Serial.println("\nstatus=IDLE");
};
void loop()
{
//Chekcs status of call
stat=call.CallStatusWithAuth(number,0,0);
//If the incoming call is from an authorized number
//saved on SIM in the positions range from 1 to 3.
if(stat==CALL_INCOM_VOICE_AUTH){
//Hang up the call.
call.HangUp();
delay(2000);
do
{
delay(50);
//Check the value of the input.
value=analogRead(A0);
//Convert the int to a string.
itoa(value,value_str,10);
//if(value>0){
}
while (value==0);
//Send an SMS to the previous number with
//the value read previously.
sms.SendSMS(number,"Perimeter Warning System: alarm ativated");//(number,value_str);
Serial.print("SMS sent to :");
Serial.println(number);
}
delay(1000);
};
ESTAÇÃO METEOROLÓGICA
Com mais algumas modificações, transformamos nosso projeto em uma estação de monitoramento ambiental via sms!
double Fahrenheit(double celsius)
{
return 1.8 * celsius + 32;
}
//Celsius to Kelvin conversion
double Kelvin(double celsius)
{
return celsius + 273.15;
}
// dewPoint function NOAA
// reference: http://wahiduddin.net/calc/density_algorithms.htm
double dewPoint(double celsius, double humidity)
{
double A0= 373.15/(273.15 + celsius);
double SUM =-7.90298 * (A0-1);
SUM += 5.02808 * log10(A0);
SUM +=-1.3816e-7 * (pow(10, (11.344*(1-1/A0)))-1) ;
SUM += 8.1328e-3 * (pow(10,(-3.49149*(A0-1)))-1) ;
SUM += log10(1013.246);
double VP = pow(10, SUM-3) * humidity;
double T = log(VP/0.61078); // temp var
return (241.88 * T) / (17.558-T);
}
// delta max = 0.6544 wrt dewPoint()
// 5x faster than dewPoint()
// reference: http://en.wikipedia.org/wiki/Dew_point
double dewPointFast(double celsius, double humidity)
{
double a = 17.271;
double b = 237.7;
double temp = (a * celsius) / (b + celsius) + log(humidity/100);
double Td = (b * temp) / (a-temp);
return Td;
}
#include <dht11.h>
dht11 DHT11;
#define DHT11PIN A2
#include "SIM900.h"
#include <SoftwareSerial.h>
//We don't need the http functions. So we can disable the next line.
//#include "inetGSM.h"
#include "sms.h"
#include "call.h"
//To change pins for Software Serial, use the two lines in GSM.cpp.
//GSM Shield for Arduino
//www.open-electronics.org
//this code is based on the example of Arduino Labs.
//Simple sketch to check if an incoming call is from an authorized
//number and in this case, send to this number an SMS with the value
//of a digital input.
//We have to create the classes for SMSs and calls.
CallGSM call;
SMSGSM sms;
char number[20];
byte stat=0;
int value;
int pin=1;
char value_str[5];
void setup()
{
pinMode(pin,INPUT);
//Serial connection.
Serial.begin(9600);
Serial.println("DHT11 TEST PROGRAM ");
Serial.print("LIBRARY VERSION: ");
Serial.println(DHT11LIB_VERSION);
int chk = DHT11.read(DHT11PIN);
Serial.print("Read sensor: ");
Serial.println("GSM Shield testing.");
//Start configuration of shield with baudrate.
//For http uses is raccomanded to use 4800 or slower.
if (gsm.begin(2400))
Serial.println("\nstatus=READY");
else Serial.println("\nstatus=IDLE");
};
void loop()
{
//Chekcs status of call
stat=call.CallStatusWithAuth(number,0,0);
//If the incoming call is from an authorized number
//saved on SIM in the positions range from 1 to 3.
if(stat==CALL_INCOM_VOICE_AUTH){
//Hang up the call.
call.HangUp();
delay(2000);
//do
//{
//delay(50);
//Check the value of the input.
value=DHT11.temperature;
//Convert the int to a string.
itoa(value,value_str,10);
//if(value>0){
// }
//while (value==0);
//Send an SMS to the previous number with
//the value read previously.
sms.SendSMS(number,value_str);//"Perimeter Warning System: alarm ativated");//(number,value_str);
Serial.print("SMS sent to :");
Serial.println(number);
// }
delay(2000);
}
};
VERSÃO TEMPERATURA e UMIDADE
double Fahrenheit(double celsius)
{
return 1.8 * celsius + 32;
}
//Celsius to Kelvin conversion
double Kelvin(double celsius)
{
return celsius + 273.15;
}
// dewPoint function NOAA
// reference: http://wahiduddin.net/calc/density_algorithms.htm
double dewPoint(double celsius, double humidity)
{
double A0= 373.15/(273.15 + celsius);
double SUM =-7.90298 * (A0-1);
SUM += 5.02808 * log10(A0);
SUM +=-1.3816e-7 * (pow(10, (11.344*(1-1/A0)))-1) ;
SUM += 8.1328e-3 * (pow(10,(-3.49149*(A0-1)))-1) ;
SUM += log10(1013.246);
double VP = pow(10, SUM-3) * humidity;
double T = log(VP/0.61078); // temp var
return (241.88 * T) / (17.558-T);
}
// delta max = 0.6544 wrt dewPoint()
// 5x faster than dewPoint()
// reference: http://en.wikipedia.org/wiki/Dew_point
double dewPointFast(double celsius, double humidity)
{
double a = 17.271;
double b = 237.7;
double temp = (a * celsius) / (b + celsius) + log(humidity/100);
double Td = (b * temp) / (a-temp);
return Td;
}
#include <dht11.h>
dht11 DHT11;
#define DHT11PIN A2
#include "SIM900.h"
#include <SoftwareSerial.h>
//We don't need the http functions. So we can disable the next line.
//#include "inetGSM.h"
#include "sms.h"
#include "call.h"
//To change pins for Software Serial, use the two lines in GSM.cpp.
//GSM Shield for Arduino
//www.open-electronics.org
//this code is based on the example of Arduino Labs.
//Simple sketch to check if an incoming call is from an authorized
//number and in this case, send to this number an SMS with the value
//of a digital input.
//We have to create the classes for SMSs and calls.
CallGSM call;
SMSGSM sms;
char number[20];
byte stat=0;
int value;
int pin=1;
char value_str[43];
int chk;
String umi=" Umidade relativa= ";
String temper="Temperatura= ";
String texto=" ";
void setup()
{
pinMode(pin,INPUT);
//Serial connection.
Serial.begin(9600);
Serial.println("DHT11 TEST PROGRAM ");
Serial.print("LIBRARY VERSION: ");
Serial.println(DHT11LIB_VERSION);
//int chk = DHT11.read(DHT11PIN);
Serial.print("Read sensor: ");
Serial.println("GSM Shield testing.");
//Start configuration of shield with baudrate.
//For http uses is raccomanded to use 4800 or slower.
if (gsm.begin(2400))
Serial.println("\nstatus=READY");
else Serial.println("\nstatus=IDLE");
}
void loop()
{
//Chekcs status of call
stat=call.CallStatusWithAuth(number,0,0);
//If the incoming call is from an authorized number
//saved on SIM in the positions range from 1 to 3. If not put 0,0.
chk = DHT11.read(DHT11PIN);
//Check the value of the input.
value=DHT11.temperature;
temper+=value;
delay(50);
value = DHT11.humidity;
umi+=value;
texto=temper+umi;
texto.toCharArray(value_str, 43);
if(stat==CALL_INCOM_VOICE_AUTH){
//Hang up the call.
call.HangUp();
delay(2000);
//Send an SMS to the previous number with
//the value read previously and conveniently converted from int to string and so to char array.
if(sms.SendSMS(number,value_str)) //"Perimeter Warning System: alarm ativated");//(number,value_str);
{
Serial.print("SMS sent to :");
Serial.println(number);
}
delay(500);
}
umi=" Umidade relativa= ";
temper="Temperatura= ";
texto="";
texto.toCharArray(value_str, 43);
}