someone know how i can do a correct comunication with esp8266 and apk (tcp server<->tcp client)
Here is the problem:
I send values and esp8266 dont read it well sometime;
arduino bauidio:115200
esp8266 baudio:115200
apk: send msg like 5;del;45 (speed,state,servo_position)
this is my car code (tcp server):
#include <SoftwareSerial.h>
#include <Servo.h>
#define M_ATRAS 4
#define M_ADELANTE 5
#define M_VELOCIDAD 6
Servo servo; // Crea un Objeto servo
SoftwareSerial ESP8266(3,2); //1)RX-> Azul, 2)TX->Amarillo
String mar;
int vel;
int rot;
void setup()
{
Serial.begin(9600);
ESP8266.begin(115200);
Serial.println("Iniciando...");
comandoESP("AT+RST"); // reset module
comandoESP("AT+CWMODE=3"); // configure as access point
//comandoESP("AT+CWSAP=\"ESP\",\"1234567890\",3,3"); //SSID,PASSWORD,CHANNEL,PASSWORD-ENCRYPATION(0=NO PASSWORD) //0 is encryption type like 0 = Open, 2 =WPA_PSK, 3 = WPA2_PSK, 4 = WPA_WPA2_PSK
comandoESP("AT+CWJAP=\"tfh\",\"fggrtfdfgdtg\"");
comandoESP("AT+CIPMUX=1"); // configure for multiple connections
comandoESP("AT+CIPSERVER=1,400"); // turn on server on port x
Serial.println("Servidor TCP ON...");
pinMode(M_VELOCIDAD, OUTPUT);
pinMode(M_ATRAS,OUTPUT);
pinMode(M_ADELANTE,OUTPUT);
velocidad(0);
servo.attach(7); // Selecionamos el pinde control para el servo Rango: 0<->155
Serial.println("Posicion delservo: "+String(servo.read()));
}
void loop()
{
if(ESP8266.available())
{
if(ESP8266.findUntil("+IPD,","."))
{
vel=ESP8266.readStringUntil(';').toInt();
mar=ESP8266.readStringUntil(';');
rot=ESP8266.readStringUntil(';').toInt();
velocidad( vel);
marcha(mar);
rotacion(rot);
Serial.println(String(vel)+"-"+mar+"-"+String(rot));
}
}
}
void marcha(String tipo){
if(tipo == "del")
{
//Serial.println("Adelante?");
digitalWrite(M_ATRAS,LOW);
digitalWrite(M_ADELANTE,HIGH);
}
else if(tipo == "tra")
{
//Serial.println("Atras?");
digitalWrite(M_ATRAS,HIGH);
digitalWrite(M_ADELANTE,LOW);
}
}
void velocidad(int v){
//Serial.println("Velocidad: "+String(v));
analogWrite(M_VELOCIDAD, v);
}
void rotacion(int r){
int rot =map(r,-10, 10, 125, 0); //mapeamos los valores que puede tener el acelerometro a los valores que puede tener el servo
//Serial.println("Acelerometro: "+String(r)+" Servo: "+String(rot));
servo.write(rot);
}
void comandoESP(String cmd)
{
ESP8266.println(cmd);
if(ESP8266.available())
Serial.println(ESP8266.readStringUntil(14));
delay(1000*3); //3seg
}
Instead of writing your own AT Commands, use a library and use Virtual Serial.
WeeESP8266 is a nice library. See my post on how to put all together.
Related
I have a problem with my Bluetooth module on my Arduino, I am trying to do a door that opens with a button in an application in the phone but when I press the button in the app the door doesn't move.
#include <SoftwareSerial.h>
#include <Servo.h>
int mover;
int mover2;
Servo servoMotor1;
Servo servoMotor2;
char rxChar;
SoftwareSerial BTserial(10, 11);
void setup(){
Serial.begin(9600);
Serial.println("Bluetooth test program");
pinMode (4,INPUT);//Fin de carrera 1
pinMode (2,INPUT);//Fin de carrera 2
mover=90; //0 Abrir 180 Cerrar 60-120 Velocidades
mover2=150;//motor Cerradura
servoMotor1.attach(8);//Motor Pin8
servoMotor2.attach(9);//Motor Pin9
BTserial.begin(9600);
BTserial.println("Bluetooth test program");
}
void loop() {
int lectura;
int lectura2;
servoMotor1.write(mover);
servoMotor2.write(mover2);
lectura=digitalRead(4);//fin de carrera
lectura2=digitalRead(2);//fin de carrera
if (Serial.available())
{
BTserial.write(Serial.read());
}
if (BTserial.available())
{
Serial.write(BTserial.read());
char rxChar = BTserial.read();
}
if(rxChar=='a'){
Serial.print("60 Grados");
mover=60;
}
if(rxChar=='b'){
Serial.print("120 Grados");
mover=120;
}
if (lectura==LOW and mover==120){
mover=90;//motor frena
mover2=30;//Motor Cerradura Cerrado
}
if (lectura2==LOW and mover==60){
mover=90;//motor frena
}
}
when I press the button the console returns "⸮"
This line is wrong: char rxChar = BTserial.read(); because you are declaring a local rxChar and assigning the read character to it. But, because it is local (inside { } ) its value will be lost. And because you also have a global rxChar (line 7: char rxChar;) that is unassigned, you will be using that value everywhere else.
Also, as mentioned you are reading from BTSerial twice.
You can fix the problem by simply removing "char" in the line mentioned, so rxChar will refer to the global declaration, and
perform only one read: rxChar = BTserial.read(); Serial.write(rxChar);
I'm developing a program in Arduino Ide (v. 1.8.13) which takes brightness values and send them to ESP32 Web Server. Also, I want to add the posibility of seeing the data via Telegram. At the moment I just want to send '/start' to the Telegram bot and Arduino program answer with a welcome message. However, the bot doesn't receive my messages. I read this is a versions issue between ArduinoJson, Universal Telegram Bot, Arduino Ide and ESP32 Core version. Could someone tell me what versions work fine in ESP32? I'm getting crazy.
I add my actual code.
These are the versions I'm using: Arduino Ide:1.8.13, Arduino Json:6.18, Universal Telegram Bot:1.3.0, Wifi Client Secure:1.0, ESP32:1.04.
Thanks in advance :)
// Import required libraries
#include <WiFi.h>
#include <Wire.h>
#include <ESPAsyncWebServer.h>
#include <SPIFFS.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_TSL2561_U.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>
#include <TimeAlarms.h>
#include <Time.h>
#include <TimeLib.h>
const char* ssid_STA = "XXXXXX";
const char* password_STA = "XXXXXX";
IPAddress ip(192,168,1,44);
IPAddress gateway(192,168,1,1);
IPAddress subnet(255,255,255,0);
#define BOTtoken "XXXXXX"
#define CHAT_ID "XXXXXXX"
WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);
time_t fecha;
int botRequestDelay = 1000;
unsigned long lastTimeBotRan;
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);
Adafruit_TSL2561_Unified tsl = Adafruit_TSL2561_Unified(TSL2561_ADDR_FLOAT, 12345);
void configureSensor(void)
{
/* You can also manually set the gain or enable auto-gain support */
// tsl.setGain(TSL2561_GAIN_1X); /* No gain ... use in bright light to avoid sensor saturation */
// tsl.setGain(TSL2561_GAIN_16X); /* 16x gain ... use in low light to boost sensitivity */
tsl.enableAutoRange(true); /* Auto-gain ... switches automatically between 1x and 16x */
/* Changing the integration time gives you better sensor resolution (402ms = 16-bit data) */
tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_13MS); /* fast but low resolution */
//tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_101MS); /* medium resolution and speed */
// tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_402MS); /* 16-bit data but slowest conversions */
/* Update these values depending on what you've set above! */
Serial.println("------------------------------------");
Serial.print ("Gain: "); Serial.println("Auto");
Serial.print ("Timing: "); Serial.println("13 ms");
Serial.println("------------------------------------");
}
String readLuz() {
/* Get a new sensor event */
sensors_event_t event;
tsl.getEvent(&event);
/* Display the results (light is measured in lux) */
Serial.print(event.light); Serial.println(" lux");
return String(event.light);
}
void Informacion(){
Serial.println("voy a enviar");
sensors_event_t event;
tsl.getEvent(&event);
//bot.sendMessage(chat_ID, "La luminosidad en tu jardín es de " ,"");
Serial.println("enviado");
}
void handleNewMessages(int numNewMessages) {
Serial.println("handleNewMessages");
Serial.println(String(numNewMessages));
for (int i = 0; i < numNewMessages; i++) {
String chat_id = String(bot.messages[i].chat_id);
Serial.println(chat_id);
if (chat_id != CHAT_ID){
bot.sendMessage(chat_id, "Unauthorized user", "");
continue;
}
//COger texto
String text = bot.messages[i].text;
Serial.println(text);
//Coger nombre
String from_name = bot.messages[i].from_name;
//if (text == "/get_info") {
//}
if (text == "/start") {
String welcome = "Bienvenida "+from_name+"\n";
welcome += "Properties.\n\n";
welcome += "/get_info : Obtener información actual del jardín\n";
bot.sendMessage(chat_id, welcome, "");
}
}
}
/**************************************************************************/
/*
Arduino setup function (automatically called at startup)
*/
/**************************************************************************/
void setup(void)
{
Serial.begin(115200);
// client.setInsecure();
/* Initialise the sensor */
//use tsl.begin() to default to Wire,
//tsl.begin(&Wire2) directs api to use Wire2, etc.
if(!tsl.begin())
{
/* There was a problem detecting the TSL2561 ... check your connections */
Serial.print("Ooops, no TSL2561 detected ... Check your wiring or I2C ADDR!");
while(1);
}
/* Display some basic information on this sensor and Setup the sensor gain and integration time */
//displaySensorDetails();
configureSensor();
///EJEMPLO SREVER
// Initialize SPIFFS
if(!SPIFFS.begin()){
Serial.println("An Error has occurred while mounting SPIFFS");
return;
}
;
// Connect to Wi-Fi
//WiFi.softAP(ssid_AP, password_AP);
WiFi.mode(WIFI_STA);
WiFi.config(ip, gateway, subnet);
WiFi.begin(ssid_STA, password_STA);
while (WiFi.status() != WL_CONNECTED) {
delay(3000);
Serial.println("Connecting to WiFi..");
}
// Print ESP32 Local IP Address
Serial.println("IP");
Serial.println(WiFi.localIP());
// Route for root / web page
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(SPIFFS, "/index.html");
});
server.on("/luz", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/plain", readLuz().c_str());
});
// Start server
server.begin();
/*
//ALARMS
//Coger la hora real al reiniciar
//fecha = now();
//Serial.print(hour(fecha)); Serial.print(minute(fecha)); Serial.print(second(fecha)); Serial.print(day(fecha)); Serial.print(month(fecha)); Serial.println(year(fecha));
//setTime(hour(fecha), minute(fecha),second(fecha), day(fecha), month(fecha),year(fecha));
setTime(12, 42, 00, 16, 6, 21);
// Crear las alarmas y configurar las funciones correspondientes a cada una
Alarm.alarmRepeat(8, 0, 0, Informacion); // Evento a las 14:00 diario
Alarm.alarmRepeat(12,43, 0, Informacion); // Evento a las 14:05 diario
Alarm.alarmRepeat(21, 0, 0, Informacion); // Evento a las 14:10 diario
*/
}
/**************************************************************************/
/*
Arduino loop function, called once 'setup' is complete (your own code
should go here)
*/
/**************************************************************************/
void loop(void){
if (millis() > lastTimeBotRan + botRequestDelay) {
Serial.println("loop");
Serial.println(bot.last_message_received);
int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
while (numNewMessages) {
Serial.println("got response");
handleNewMessages(numNewMessages);
numNewMessages = bot.getUpdates(bot.last_message_received + 1);
}
lastTimeBotRan= millis();
}
// Mostrar el reloj en el monitor serial
//digitalClockDisplay();
// Esperar 1 segundo y procesar las Alarmas mientras tanto...
//Alarm.delay(1000);
}
/*
void digitalClockDisplay() {
Serial.print(hour());
printDigits(minute());
//printDigits(second());
Serial.println();
}
void printDigits(int digits) {
Serial.print(":");
if (digits < 10)
Serial.print('0');
Serial.print(digits);
}
*/
I suppose you are missing the statement
// Add root certificate for api.telegram.org
client.setCACert(TELEGRAM_CERTIFICATE_ROOT);
I'm using Arduino Wemos Esp32 D1 R32.
I'm trying to make an MQTT connection between My Arduino board and a MQTT Broker.
When I try to send messages from my Arduino, It works just fine. (I'm using a pullup button to send a message.) Whenever I press the button a message is sent.
But when I try to read a message and write it on the Serial with the callback function it just doesn't work.
Could someone please help me with that issue?
Here is my code:
[code]
#include <ETH.h>
#include <WiFi.h>
#include <WiFiAP.h>
#include <WiFiClient.h>
#include <WiFiGeneric.h>
#include <WiFiMulti.h>
#include <WiFiScan.h>
#include <WiFiServer.h>
#include <WiFiSTA.h>
#include <WiFiType.h>
#include <WiFiUdp.h>
#include <PubSubClient.h>
#define BUFFER_SIZE 100
#define pinBotao1 25 //input botao pullup
#define led 26 //output acende led
#define pot 4 //input Resistor
//WiFi
const char* SSID = "******"; // SSID / nome da rede WiFi que deseja se conectar
const char* PASSWORD = "******"; // Senha da rede WiFi que deseja se conectar
WiFiClient wifiClient;
//MQTT Server
const char* BROKER_MQTT = "mqtt.eclipse.org"; //URL do broker MQTT que se deseja utilizar
int BROKER_PORT = 1883; // Porta do Broker MQTT
#define ID_MQTT "BCI0111"
#define TOPIC_PUBLISH "BCIBotao111"
PubSubClient MQTT(wifiClient); // Instancia o Cliente MQTT passando o objeto espClient
//Declaração das Funções
void mantemConexoes(); //Garante que as conexoes com WiFi e MQTT Broker se mantenham ativas
void conectaWiFi(); //Faz conexão com WiFi
void conectaMQTT(); //Faz conexão com Broker MQTT
void enviaPacote(); //Envia uma mensagem ao Broker.
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i=0;i<length;i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
void setup() {
pinMode(pinBotao1, INPUT_PULLUP);
pinMode(led, OUTPUT);
Serial.begin(115200);
conectaWiFi();
MQTT.setServer(BROKER_MQTT, BROKER_PORT);
MQTT.setCallback(callback);
}
void loop() {
mantemConexoes();
enviaValores();
MQTT.loop();
}
void mantemConexoes() {
if (!MQTT.connected()) {
conectaMQTT();
}
conectaWiFi(); //se não há conexão com o WiFI, a conexão é refeita
}
void conectaWiFi() {
if (WiFi.status() == WL_CONNECTED) {
return;
}
Serial.print("Conectando-se na rede: ");
Serial.print(SSID);
Serial.println(" Aguarde!");
WiFi.begin(SSID, PASSWORD); // Conecta na rede WI-FI
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
WiFi.begin(SSID, PASSWORD);
}
Serial.println();
Serial.print("Conectado com sucesso, na rede: ");
Serial.print(SSID);
Serial.print(" IP obtido: ");
Serial.println(WiFi.localIP());
}
void conectaMQTT() {
while (!MQTT.connected()) {
Serial.print("Conectando ao Broker MQTT: ");
Serial.println(BROKER_MQTT);
//if (MQTT.connect(ID_MQTT,USER_MQTT,PASSWORD_MQTT)) {
if (MQTT.connect(ID_MQTT)) {
Serial.println("Conectado ao Broker com sucesso!");
}
else {
Serial.println("Nao foi possivel se conectar ao broker.");
Serial.println("Nova tentativa de conexao em 10s");
delay(10000);
}
}
}
void enviaValores() {
bool estadoBotao1;
int estadoPot;
estadoBotao1 = digitalRead(pinBotao1);
estadoPot = char(analogRead(pot));
if (estadoBotao1==LOW) {
//Botao Apertado
MQTT.publish(TOPIC_PUBLISH, "estadoPot");
Serial.println("Botao1 APERTADO. Payload enviado.");
}
delay(1000);
}
You need to subscribe to one or more topics to receive messages. Typically you subscribe to the topic(s) you are interested in after connecting to MQTT, but you may also subscribe at other times based on your app's logic.
In this case you can change conectaMQTT like this:
void conectaMQTT() {
while (!MQTT.connected()) {
Serial.print("Conectando ao Broker MQTT: ");
Serial.println(BROKER_MQTT);
//if (MQTT.connect(ID_MQTT,USER_MQTT,PASSWORD_MQTT)) {
if (MQTT.connect(ID_MQTT)) {
Serial.println("Conectado ao Broker com sucesso!");
if (MQTT.subscribe(TOPIC_SUBSCRIBE)) {
Serial.println("Succesful subscription.");
} else {
Serial.println("Subscription failed.");
}
}
else {
Serial.println("Nao foi possivel se conectar ao broker.");
Serial.println("Nova tentativa de conexao em 10s");
delay(10000);
}
}
}
This is my code and i want to control stepper with IR remote. My code work fine but i want to know how can continu my action while a hold button on remote. The HEX code is different when i hold button and i don't know to recall my last function.
#include <boarddefs.h>
#include <ir_Lego_PF_BitStreamEncoder.h>
#include <IRremote.h>
#include <IRremoteInt.h>
#include <Stepper.h>
int dir;
int receiver = 6; // Signal Pin of IR receiver to Arduino Digital Pin 6
IRrecv irrecv(receiver); // create instance of 'irrecv'
decode_results results; // create instance of 'decode_results'
const int stepsPerRevolution = 200; // change this to fit the number of steps per revolution
// for your motor
// Ici c'est la nouvelle séquence que j'ai trouvé pour faire fonctionné le moteur (KP4M2) correctement avec le connecteur.
// Reste à mettre dans le bon ordre
Stepper myStepper(stepsPerRevolution, 2, 3, 4, 5);
void setup() {
irrecv.enableIRIn(); // Start the receiver
// set the speed at 60 rpm:
myStepper.setSpeed(100);
// initialize the serial port:
Serial.begin(9600);
}
void loop() {
if (irrecv.decode(&results)) // have we received an IR signal?
{
switch (results.value)
Here, i start switch with my HEX code fron IR remote
{
case 0xB4B49A65:
//myStepper.step(stepsPerRevolution);//counter clockwise rotation
//break;
VrDroite();
break;
case 0xB4B45AA5:
//myStepper.step(-stepsPerRevolution);//counter clockwise rotation
//break;
VrGauche();
case 0xB4B41AE5:
//myStepper.step(-stepsPerRevolution/10);//counter clockwise rotation
//break;
VrMicro();
}
irrecv.resume(); // receive the next value
Serial.println(results.value, HEX);
}
}
Use function for calling action
void VrDroite() {
myStepper.step(+100);
}
void VrGauche() {
myStepper.step(-stepsPerRevolution);//counter clockwise rotation
}
void VrMicro() {
myStepper.step(stepsPerRevolution / 10); //counter clockwise rotation
}
void VrNone() {
myStepper.step(0);
}enter code here
Thank
Try this.
This will remember your last keypress.
If the current keypress is a "hold", it will run the same function as the last keypress
#include <boarddefs.h>
#include <ir_Lego_PF_BitStreamEncoder.h>
#include <IRremote.h>
#include <IRremoteInt.h>
#include <Stepper.h>
int dir;
int receiver = 6; // Signal Pin of IR receiver to Arduino Digital Pin 6
IRrecv irrecv(receiver); // create instance of 'irrecv'
decode_results results; // create instance of 'decode_results'
// last keypress value
unsigned long prev_result_value = 0;
// this key press value
unsigned long current_result_value;
const int stepsPerRevolution = 200; // change this to fit the number of steps per revolution
// for your motor
// Ici c'est la nouvelle séquence que j'ai trouvé pour faire fonctionné le moteur (KP4M2) correctement avec le connecteur.
// Reste à mettre dans le bon ordre
Stepper myStepper(stepsPerRevolution, 2, 3, 4, 5);
void setup() {
irrecv.enableIRIn(); // Start the receiver
// set the speed at 60 rpm:
myStepper.setSpeed(100);
// initialize the serial port:
Serial.begin(9600);
}
void loop() {
if (irrecv.decode(&results)) { // have we received an IR signal?
current_result_value = results.value; // store the result
if (!prev_result_value)
prev_results_value = current_result_value; // first time through only.
if (results.value == HOLD_CODE) // is this a hold code?
current_results_value = rev_results_value; // make the current result the same as the last keypress.
//switch (results.value) {
switch (current_results_value) {
case 0xB4B49A65:
//myStepper.step(stepsPerRevolution);//counter clockwise rotation
//break;
VrDroite();
prev_results_value = current_results_value;
break;
case 0xB4B45AA5:
//myStepper.step(-stepsPerRevolution);//counter clockwise rotation
//break;
VrGauche();
prev_results_value = current_results_value;
case 0xB4B41AE5:
//myStepper.step(-stepsPerRevolution/10);//counter clockwise rotation
//break;
VrMicro();
prev_results_value = current_results_value;
}
irrecv.resume(); // receive the next value
Serial.println(results.value, HEX);
Serial.println(current_results_value, HEX);
Serial.println(prev_results_value, HEX);
}
}
void VrDroite() {
myStepper.step(+100);
}
void VrGauche() {
myStepper.step(-stepsPerRevolution);//counter clockwise rotation
}
void VrMicro() {
myStepper.step(stepsPerRevolution / 10); //counter clockwise rotation
}
void VrNone() {
myStepper.step(0);
}
Hi I did 2 diferent codes, then after verifying that they work i try to combine them and I got a problem. I used GSM.h to controle my GSM module, and to controle the GPS I used the SoftwareSerial.h.
I tryed to combine these to codes and this 2 libraries conflit with each other.
Can some one help me?
This is my code
//GSM
#include <GSM.h>
#define PINNUMBER "3805"
GSM gsmAccess; // include a 'true' parameter for debug enabled
GSM_SMS sms;
//N de telefone de envio
char remoteNumber[20]= "914181875";
//Conteudo do SMS
char txtMsg[200]="Tester";
int val = 0;
//GPS
//#include <SoftwareSerial.h>
#include <TinyGPS.h>
TinyGPS gps;
SoftwareSerial ss(4, 3);
static void print_float(float val, float invalid, int len, int prec);
int button = 7;
void setup()
{
// initialize serial communications
pinMode(button, INPUT);
Serial.begin(9600);
Serial.println("SMS Messages Sender");
// connection state
boolean notConnected = true;
// Start GSM shield
// If your SIM has PIN, pass it as a parameter of begin() in quotes
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_READY)
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("GSM initialized");
}
void loop()
{
val = digitalRead(button);
if (val == HIGH){
sendSMS();
}
}
void sendSMS(){
Serial.print("Message to mobile number: ");
Serial.println(remoteNumber);
// sms text
Serial.println("SENDING");
Serial.println();
Serial.println("Message:");
Serial.println(txtMsg);
// send the message
sms.beginSMS(remoteNumber);
sms.print(txtMsg);
sms.endSMS();
Serial.println("\nCOMPLETE!\n");
}
I would try using the AltSoftSerial library instead of SoftwareSerial:
https://github.com/PaulStoffregen/AltSoftSerial
The disadvantage of this library is it requires you to use specific pins for serial communication with your GPS hardware, which are different from the pins you're currently using:
// AltSoftSerial always uses these pins:
//
// Board Transmit Receive PWM Unusable
// ----- -------- ------- ------------
// Teensy 3.0 & 3.1 21 20 22
// Teensy 2.0 9 10 (none)
// Teensy++ 2.0 25 4 26, 27
// Arduino Uno 9 8 10
// Arduino Leonardo 5 13 (none)
// Arduino Mega 46 48 44, 45
// Wiring-S 5 6 4
// Sanguino 13 14 12
I don't have the hardware to test but the following code does compile:
//GSM
#include <GSM.h>
#define PINNUMBER "3805"
GSM gsmAccess; // include a 'true' parameter for debug enabled
GSM_SMS sms;
//N de telefone de envio
char remoteNumber[20]= "914181875";
//Conteudo do SMS
char txtMsg[200]="Tester";
int val = 0;
//GPS
#include <AltSoftSerial.h>
AltSoftSerial ss;
#include <TinyGPS.h>
TinyGPS gps;
static void print_float(float val, float invalid, int len, int prec);
int button = 7;
void setup()
{
// initialize serial communications
pinMode(button, INPUT);
Serial.begin(9600);
Serial.println("SMS Messages Sender");
// connection state
boolean notConnected = true;
// Start GSM shield
// If your SIM has PIN, pass it as a parameter of begin() in quotes
while(notConnected)
{
if(gsmAccess.begin(PINNUMBER)==GSM_READY)
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("GSM initialized");
}
void loop()
{
val = digitalRead(button);
if (val == HIGH){
sendSMS();
}
}
void sendSMS(){
Serial.print("Message to mobile number: ");
Serial.println(remoteNumber);
// sms text
Serial.println("SENDING");
Serial.println();
Serial.println("Message:");
Serial.println(txtMsg);
// send the message
sms.beginSMS(remoteNumber);
sms.print(txtMsg);
sms.endSMS();
Serial.println("\nCOMPLETE!\n");
}