Hello everyone I've never posted before so I may not know how a couple of things work but I've made a fairly basic BLE sketch where a central connects consecutively with 2 peripherals, checks the rssi with each of them and then writes a value to the characteristic of the one with the most powerful rssi. My problem is that the bleCharacteristic.writeValue() function is not going through at all and to confirm this I made a while loop at the point where the value should be updated on the peripheral and the program stops there which means that the value is never written in the first place. I have tried to change the value with the BLE app from my phone and it works as it should but it doesn't with the central.
Here's the codes for the central.
`
#include <ArduinoBLE.h>
int rssiState1, rssiState2 ;
BLEDevice peripheral1;
BLEDevice peripheral2;
void setup() {
Serial.begin(9600);
while (!Serial);
rssiState1 = -13;
rssiState2 = -10;
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
while (1);
}
Serial.println("Bluetooth® Low Energy Central - Peripheral Explorer");
}
void loop() {
BLE.scanForUuid("19B10010-E8F2-537E-4F6C-D104768A1214");
Serial.print("Scanning for Rover 1 ");
Serial.println();
delay(3000);
// check if a peripheral has been discovered
BLEDevice peripheral1 = BLE.available();
if (peripheral1) {
// discovered a peripheral, print out address, local name, and advertised service
Serial.print("Found ");
Serial.print(peripheral1.address());
Serial.print(" '");
Serial.print(peripheral1.localName());
Serial.print("' ");
Serial.print(peripheral1.advertisedServiceUuid());
Serial.println();
// see if peripheral is a Rover
if (peripheral1.localName() == "Rover 1") {
// stop scanning
BLE.stopScan();
// connect to the peripheral
Serial.println("Connecting ...");
if (peripheral1.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
}
//rssiState1 = peripheral1.rssi();
// Print RSSI
Serial.print("RSSI=");
Serial.println(rssiState1);
// // retrieve the moror characteristic
BLECharacteristic motorCharacteristic = peripheral1.characteristic("19b10002-e8f2-537e-4f6c-d104768a1214");
//if (rssiState1 > rssiState2 || rssiState1 == rssiState2) {
delay(3000);
while(motorCharacteristic.written()== false){
motorCharacteristic.writeValue((byte(0x01))); //τιμη 1 για το 1 και 0 μηδεν για το άλλο
// }else if (rssiState1 < rssiState2){
// motorCharacteristic.writeValue((byte)0x00);
}
// }
Serial.println("Moving Rover 1");
}
}
BLE.disconnect();
BLE.scanForUuid("19B10011-E8F2-537E-4F6C-D104768A1214");
Serial.println("Scanning for Rover 2 ");
delay(3000);
BLEDevice peripheral2 = BLE.available();
if (peripheral2) {
// discovered a peripheral, print out address, local name, and advertised service
Serial.print("Found ");
Serial.print(peripheral2.address());
Serial.print(" '");
Serial.print(peripheral2.localName());
Serial.print("' ");
Serial.print(peripheral2.advertisedServiceUuid());
Serial.println();
// see if peripheral is a Rover
if (peripheral2.localName() == "Rover 2") {
// stop scanning
BLE.stopScan();
// connect to the peripheral
Serial.println("Connecting ...");
if (peripheral2.connect()) {
Serial.println("Connected");
} else {
Serial.println("Failed to connect!");
return;
}
// rssiState2 = peripheral2.rssi();
// Print RSSI
Serial.print("RSSI=");
Serial.println(rssiState2);
BLECharacteristic motorCharacteristic = peripheral2.characteristic("19b10001-e8f2-537e-4f6c-d104768a1214");
// if (rssiState1 < rssiState2) {
motorCharacteristic.writeValue((byte(0x01))); //τιμη 1 για το 1 και 0 μηδεν για το άλλο
// }else if (rssiState1 > rssiState2){
delay(3000);
// peripheral2.characteristic("19b10001-e8f2-537e-4f6c-d104768a1214").writeValue((byte)0x00);
Serial.println("Moving Rover 2");
// }
BLE.disconnect();
}
delay(3000);
}
}
`
And here's the code of the peripheral
`
#include <ArduinoBLE.h>
//const int motorPin = 4; // set buttonPin to digital pin 4
BLEService motorService("19B10010-E8F2-537E-4F6C-D104768A1214"); // create service
// create motor characteristic and allow remote device to read and write
BLEByteCharacteristic motorCharacteristic("19b10002-e8f2-537e-4f6c-d104768a1214", BLERead | BLEWrite);
void setup() {
Serial.begin(9600);
while (!Serial);
pinMode(LED_BUILTIN, OUTPUT); // use the Motor as an output
// begin initialization
if (!BLE.begin()) {
Serial.println("starting Bluetooth® Low Energy module failed!");
//while (1);
}
// set the local name peripheral advertises
BLE.setLocalName("Rover 1");
// set the UUID for the service this peripheral advertises:
BLE.setAdvertisedService(motorService);
// add the characteristics to the service
motorService.addCharacteristic(motorCharacteristic);
// add the service
BLE.addService(motorService);
motorCharacteristic.writeValue((byte)0x00);
// start advertising
BLE.advertise();
Serial.println("advertising ...");
Serial.println("Bluetooth® device active, waiting for connections...");
Serial.println("motorchar");
Serial.println(motorCharacteristic.value()) ;
}
void loop() {
// listen for Bluetooth® Low Energy peripherals to connect:
BLE.poll();
BLEDevice central = BLE.central();
//if a central is connected to peripheral:
if (central) {
Serial.print("Connected to central: ");
// print the central's MAC address:
Serial.println(central.address());
while (central.connected()) {
Serial.println("it is connetcted");
// if the remote device wrote to the characteristic,
if (motorCharacteristic.written()) {
Serial.println("it is written");
// use the value to is written()) {
if (motorCharacteristic.value()>0) { // any value other than 0
Serial.println("Movement active");
digitalWrite(LED_BUILTIN, HIGH); // will turn the LED on
delay(5000);
digitalWrite(LED_BUILTIN, LOW);
//motorCharacteristic.writeValue((byte)0x00);
Serial.println("Movement inactive");
}
}
Serial.println("motorchar");
Serial.println(motorCharacteristic.value()) ;
}
}
}
`
Also in the serial of the peripheral the value is always 0 just to cross check that it is never written
I have also tried to send a different value type other than a byte but the problem is that it never goes through
Related
I have two node mcu modules connected to the same network, running the same code and powered the same way. Both of them are subscribed to the topic Terma but one of them randomly disconnects and then reconnects to the MQTT broker meanwhile it stayed connected to the wifi uninterruptedly, the other module stays connected with no problem. I don't know if it is a network issue or if the node mcu is damaged.
here is the code:
#include <PubSubClient.h>
// Update these with values suitable for your network.
const char* ssid = "Milagros";
const char* password = "18095381";
const char* mqtt_server = "192.168.1.133";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
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();
// Switch on the LED if an 1 was received as first character
if ((char)payload[0] == '1') {
digitalWrite(14, LOW);
client.publish("estado","1");
// but actually the LED is on; this is because
// it is active low on the ESP-01)
} else {
digitalWrite(14, HIGH);
client.publish("estado","0");
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("terma", "hello world 1");
// ... and resubscribe
client.subscribe("terma");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
pinMode(14, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1884);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
I am trying to set up the SIM7600CE to have it connect to the internet whenever I turn it on with Arduino Mega. I know how to turn it on with software by set the pin D12 to HIGH but I don't know how to read the signal of the NETLIGHT pin to get to know when the NETLIGHT starts to blink, which means the SIM card is registered into network successfully. Is there any way I can read that signal? Or is there any other way I can acknowledge when SIM card is registered into network successfully by software?
edit: I am trying to get the information that my SIM7600 is connected by using AT command. Even though I can send the AT command, I cannot parse the response. The result of the code below turns out that the Serial keeps printing the string "at+csq" constantly. Can anybody help?
#define mySerial Serial1
#define PWRKEY 12
void setup()
{
digitalWrite(PWRKEY, HIGH); //Press the boot button
Serial.begin(115200);
delay(500);
mySerial.begin(115200);
delay(5000);
while (1)
{
Serial.println("AT+CSQ"); //AT command for Signal quality test
updateSerial();
delay(1500);
}
}
void loop()
{
updateSerial();
}
void updateSerial()
{
delay(500);
while (Serial.available())
{
mySerial.write(Serial.read());
}
while (mySerial.available())
{
Serial.write(mySerial.read());
if (Serial.find("+CSQ: ")) //Find the AT+CSQ response
{
char c = mySerial.read();
if (c != '9') //check the first digit after "+CSQ: ", +CSQ: 99,99 means not detectable,
{
Serial.println("connected");
break;
}
}
}
Checkout the AT manual for the MODEM. Enable all URCs related to network registration, once registered on the network - you will receive a URC that will have information if your SIM was able to register on the network or not.
I have solved the problem with the same logic. However, I tried to just write and read in the SIM7600 serial, with some printing on the monitor to guide/debug. Plus, I used a connection flag as a condition to break the while loop when the MODEM is connected.
#define mySerial Serial1
#define PWRKEY 12
bool connectionFlag = 0; //will be set when connected
void setup()
{
digitalWrite(PWRKEY, HIGH); //Press the boot button
Serial.begin(115200);
delay(500);
mySerial.begin(115200);
delay(5000); //Give it a little time to initialize
while (1)
{
mySerial.println("AT+CSQ"); //AT command for Signal quality test
connectionCheck();
if (connectionFlag ==1) break;
delay(1500);
}
Serial.println("done");
mySerial.println("AT+CSQ"); //Get the CSQ response to confirm.
updateSerial();
}
void loop()
{
updateSerial();
}
void connectionCheck()
{
delay(500);
while (mySerial.available())
{
// Serial.write(mySerial.read());
if (mySerial.find("+CSQ: ")) //Find the AT+CSQ response
{
Serial.print("initializing\t");
char c = mySerial.read();
if (c != '9') //check the first digit after "+CSQ: ", +CSQ: 99,99 means not detectable,
{
Serial.println("connected");
connectionFlag = 1;
break;
}
}
}
}
void updateSerial()
{
delay(500);
if (mySerial.available())
{
Serial.write(mySerial.read());
}
if (Serial.available())
{
mySerial.write(Serial.read());
}
}
Sorry for the messy code, but I was wondering if anyone knows why it can't be run on my Arduino Uno? It's for a locking door controlled by RFID and IR remote respectively, and it stopped working for some reason when I edited the code for the void ir() section.
my code:
#include <MFRC522.h>
#include "Stepper.h"
#include "IRremote.h"
#define SS_PIN 10
#define RST_PIN 9
#define ACCESS_DELAY 2000
#define DENIED_DELAY 1000
MFRC522 mfrc522(SS_PIN, RST_PIN);
#define STEPS 32 // Number of steps per revolution of Internal shaft
Stepper small_stepper(STEPS, 2, 4, 3, 5);
int Steps2Take; // 2048 = 1 Revolution
int receiver = 8; // 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'
bool locked = true;
int steps = 500;
// Create MFRC522 instance.
/*----- Variables, Pins -----*/
/*-----( Declare objects )-----*/
// Setup of proper sequencing for Motor Driver Pins
// In1, In2, In3, In4 in the sequence 1-3-2-4
void setup()
{
irrecv.enableIRIn(); // Start the receiver
Serial.begin(9600); // Initiate a serial communication
SPI.begin(); // Initiate SPI bus
mfrc522.PCD_Init(); // Initiate MFRC522
Serial.println("Put your card to the reader...");
Serial.println();
}
void rfid()
{
// Look for new cards
if ( ! mfrc522.PICC_IsNewCardPresent())
{
return;
}
// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial())
{
return;
}
//Show UID on serial monitor
Serial.print("UID tag :");
String content= "";
byte letter;
for (byte i = 0; i < mfrc522.uid.size; i++)
{
Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
Serial.print(mfrc522.uid.uidByte[i], HEX);
content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
content.concat(String(mfrc522.uid.uidByte[i], HEX));
}
Serial.println();
Serial.print("Message : ");
content.toUpperCase();
if (content.substring(1) == "B9 67 D6 6E") //change here the UID of the card/cards that you want to give access
{
Serial.println("Authorized access");
Serial.println();
delay(500);
small_stepper.setSpeed(500); //Speed (Max 500)
Steps2Take = steps; // Rotate 500CW
small_stepper.step(Steps2Take); //Do the steps
delay(3000);
Steps2Take = -steps; // Rotate 500CW
small_stepper.step(Steps2Take); //Do the steps
}
else {
Serial.println(" Access denied");
delay(3000);
}
}
void ir()
{ if (irrecv.decode(&results)) // have we received an IR signal?
{
switch(results.value)
{
case 0xFFA857: //VOL - pressed
if (locked == true){
small_stepper.setSpeed(500); //Speed (Max 500)
Steps2Take = steps; // Rotate 500CW
small_stepper.step(Steps2Take); //Do the steps
locked = false;
}
case 0xFF629D: //VOL + pressed
if (locked == false){
small_stepper.setSpeed(500); //Speed (Max 500)
Steps2Take = -steps; // Rotate 500 ACW
small_stepper.step(Steps2Take); //Do the steps
locked = true;
}
}
}
}
}
void loop()
{
ir();
rfid();
}
My error:
/var/folders/5f/6gg5hb5174n1h9hmdy2pmn3w0000gp/T//ccQ6deD3.ltrans0.ltrans.o: In function main':
/private/var/folders/5f/6gg5hb5174n1h9hmdy2pmn3w0000gp/T/AppTranslocation/F6976C18-1AF6-4EB1-A8BD-1B9FBC53FC03/d/Arduino.app/Contents/Java/hardware/arduino/avr/cores/arduino/main.cpp:46: undefined reference toloop'
collect2: error: ld returned 1 exit status
Multiple libraries were found for "Stepper.h"
Used: /Users/Ulitimac/Documents/Arduino/libraries/Stepper
Not used: /private/var/folders/5f/6gg5hb5174n1h9hmdy2pmn3w0000gp/T/AppTranslocation/F6976C18-1AF6-4EB1-A8BD-1B9FBC53FC03/d/Arduino.app/Contents/Java/libraries/Stepper
exit status 1
Error compiling for board Arduino/Genuino Uno.
Thanks in advance!
Description
I am writing a web server on ESP-8266(01), that will control 3 locks using Arduino Mega.
The locks will be controlled by Bluetooth ESP 8266 (get method from phone) and using my laptops browser.
I can do it all with bluetooth HC-05 (easily).
The issue I am facing is with my ESP-8266 wifi module.
I need to send 3 different strings from ESP for Arduino to read it.
If it's "AAAA" Arduino will read it and unlock door one, if it BBBB then door 2 and etc etc.....
So I used this code:
#include <ESP8266WiFi.h>
const char* ssid = "Do-Not-Ask-For-Password";
const char* password = "ITISMYPASSWORD";
//const char* ssid = "`STAR-NET-Azhar-32210352";
//const char* password = "ITISMYPASSWORD";
int ledPin = 2; // GPIO2
WiFiServer server(80);
// Update these with values suitable for your network.
IPAddress ip(192,168,8,128); //Node static IP
IPAddress gateway(192,168,8,1);
IPAddress subnet(255,255,255,0);
void setup() {
Serial.begin(115200);
delay(10);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
WiFi.config(ip, gateway, subnet);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Start the server
server.begin();
Serial.println("Server started");
// Print the IP address
Serial.print("Use this URL to connect: ");
Serial.print("http://");
Serial.print(WiFi.localIP());
Serial.println("/");
}
void loop() {
ESP.wdtDisable();
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}
// Wait until the client sends some data
// Serial.println("new client");
// while(!client.available()){
// delay(1);
// }
if(!client.available()){
delay(1);
client.flush();
}
// Read the first line of the request
String request = client.readStringUntil('\r');
//Serial.println(request);
client.flush();
// Match the request
int value1 = LOW;
int value2 = LOW;
int value3 = LOW;
if (request.indexOf("/LOCK=ON1") != -1) {
//digitalWrite(ledPin, HIGH);
value1 = HIGH;
Serial.println("AAAA");
}
if(request.indexOf("/LOCK=ON2") != -1){
value2 = HIGH;
Serial.println("BBBB");
}
if(request.indexOf("/LOCK=ON3") != -1){
value3 = HIGH;
Serial.println("CCCC");
}
// Set ledPin according to the request
//digitalWrite(ledPin, value);
// Return the response
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println(""); // do not forget this one
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.println("<br><br>");
client.print("LOCK ONE IS NOW: ");
if(value1 == HIGH) {
client.print("UNLOCKED");
// Serial.println("A");
} else {
client.print("LOCKED");
}
client.println("<br><br>");
client.print("LOCK TWO IS NOW: ");
if(value2 == HIGH) {
client.print("UNLOCKED");
// Serial.println("B");
} else {
client.print("LOCKED");
}
client.println("<br><br>");
client.print("LOCK THREE IS NOW: ");
if(value3 == HIGH) {
client.print("UNLOCKED");
//Serial.println("C");
} else {
client.print("LOCKED");
}
client.println("<br><br>");
client.println("CLICK HERE TO UNLOCK THE LOCK ONE<br>");
client.println("CLICK HERE TO UNLOCK THE LOCK TWO<br>");
client.println("CLICK HERE TO UNLOCK THE LOCK THREE<br>");
client.println("</html>");
delay(100);
//Serial.println("client disconnected");
// Serial.println("");
}
The Result I Get on Browser is ( Which is What i need):
enter image description here
ISSUE:
Now The Issue Is Some Times it misses the serial data i send, For Example if i click unlock door 1, It sends data and i click unlock door 2 it does nothn and when i reset it sends data from all 3 but for two to 3 times and then module resets it self ....
This Is What I got From Serial Monitor:
enter image description here
Now i have searched alot and its watchdre out what i did wrong in the code.
this is how my ESP is connected:
vcc & CHPD to 3.3V ragulator
gnd to gnd of powersuply and to arduino gnd...
GP 0 ------> 3.3v with 2.2k Resistor ( in non flashing state).
Rst ------> 3.3v with resistor
RX to TX
TX to RX
Any Ideas how to fix it?
Is There any other way to control Arduino pins (6 different pins) from ESP 8266 module??
ive been trying from many days please help!!
Ok I am Posting It For those who are facing the same problem!! i took the Hello ESP example And Modified it to Print Serial!!!
On Mega My Serial Was Started at 9600 and i started Serial On ESP at 9600 aswell :| So This is the Code .... Slow Server and WDT issue is Almost Gone....
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
//const int RELAY_PIN = 2; //RELAY
const char* ssid = "Do-Not-Ask-For-Password";
const char* password = "AeDrki$32ILA!$#2";
MDNSResponder mdns;
ESP8266WebServer server(80);
void handleRoot() {
server.send(200, "text/plain", "hWelcome To Door Unlock Project By Haziq Sheikh");
}
void handleNotFound(){
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET)?"GET":"POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i=0; i<server.args(); i++){
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
}
void setup(void){
// pinMode(RELAY_PIN, OUTPUT);
Serial.begin(9600);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
//digitalWrite(RELAY_PIN, 1);
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
// digitalWrite(RELAY_PIN, 0);
if (mdns.begin("esp8266", WiFi.localIP())) {
Serial.println("MDNS responder started");
}
server.on("/", handleRoot);
server.on("/lock1", [](){
server.send(200, "text/plain", "Okay Door One Unlocked");
Serial.println("AAAA");
});
server.on("/lock2", [](){
server.send(200, "text/plain", "Okay -- Door 2 Unlocked");
Serial.println("BBBB");
});
server.on("/lock3", [](){
server.send(200, "text/plain", "Okay -- Door 3 is Unlocked");
Serial.println("CCCC");
});
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
}
void loop(void){
server.handleClient();
}
#include <SoftwareSerial.h>
char inchar; //Will hold the incoming character from the serial port.
SoftwareSerial cell(2,3); //Create a 'fake' serial port. Pin 2 is the Rx pin, pin 3 is the Tx pin.
int led1 = A2;
void setup()
{
// Prepare the digital output pins
pinMode(led1, OUTPUT);
digitalWrite(led1, HIGH);
//Initialize GSM module serial port for communication.
cell.begin(19200);
delay(30000); // Give time for GSM module to register on network, etc.
cell.println("AT+CMGF=1"); // Set SMS mode to text
delay(200);
cell.println("AT+CNMI=3,3,0,0"); // Set module to send SMS data to serial out upon receipt
delay(200);
}
void loop()
{
//If a character comes in from the cellular module...
if(cell.available() >0)
{
delay(10);
inchar=cell.read();
if (inchar=='a')
{
delay(10);
inchar=cell.read();
if (inchar=='0')
{
digitalWrite(led1, LOW);
}
else if (inchar=='1')
{
digitalWrite(led1, HIGH);
}
delay(10);
delay(10);
}
cell.println("AT+CMGD=1,4"); // Delete all SMS
}
}
This is the code for receiving SMSes from the cellular network. I am using the Arduino Gboard with SIM900. There is no error in the code, but the LED on the board doesn't switch on or off in response to an SMS.
Why?
Here's a fully functional code for sending a command thru SMS using Arduino and GSM, it will also reply the state of the light.
#include <SoftwareSerial.h>
SoftwareSerial GPRS(10, 11);
String textMessage;
String lampState;
const int relay = 12; //If you're using a relay to switch, if not reverse all HIGH and LOW on the code
void setup() {
pinMode(relay, OUTPUT);
digitalWrite(relay, HIGH); // The current state of the light is ON
Serial.begin(9600);
GPRS.begin(9600);
delay(5000);
Serial.print("GPRS ready...\r\n");
GPRS.print("AT+CMGF=1\r\n");
delay(1000);
GPRS.print("AT+CNMI=2,2,0,0,0\r\n");
delay(1000);
}
void loop(){
if(GPRS.available()>0){
textMessage = GPRS.readString();
Serial.print(textMessage);
delay(10);
}
if(textMessage.indexOf("ON")>=0){ //If you sent "ON" the lights will turn on
// Turn on relay and save current state
digitalWrite(relay, HIGH);
lampState = "ON";
Serial.println("Lamp set to ON\r\n");
textMessage = "";
GPRS.println("AT+CMGS=\"+631234567890\""); // RECEIVER: change the phone number here with international code
delay(500);
GPRS.print("Lamp was finally switched ON.\r");
GPRS.write( 0x1a );
delay(1000);
}
if(textMessage.indexOf("OFF")>=0){
// Turn off relay and save current state
digitalWrite(relay, LOW);
lampState = "OFF";
Serial.println("Lamp set to OFF\r\n");
textMessage = "";
GPRS.println("AT+CMGS=\"+631234567890\""); /// RECEIVER: change the phone number here with international code
delay(500);
GPRS.print("Lamp was finally switched OFF.\r");
GPRS.write( 0x1a );
delay(1000);
}
if(textMessage.indexOf("STATUS")>=0){
String message = "Lamp is " + lampState;
GPRS.print("AT+CMGF=1");
delay(1000);
Serial.println("Lamp state resquest");
textMessage = "";
GPRS.println("AT+CMGS=\"+631234567890\""); // RECEIVER: change the phone number here with international code
delay(500);
GPRS.print("Lamp is currently ");
GPRS.println(lampState ? "ON" : "OFF"); // This is to show if the light is currently switched on or off
GPRS.write( 0x1a );
delay(1000);
}
}
Change
AT+CNMI=3,3,0,0
to:
AT+CNMI=2,2,0,0,0
The simplest way is the best way.
// if You use SoftwareSerial lib, declare object for GSM
SoftwareSerial gsm(8,9); // TX, RX
void setup(){
// initialise UART and GSM communication between Arduino and modem
Serial.begin(115200);
gsm.begin(115200);
// wait 5-10sec. for modem whitch must connect to the network
delay(5000);
// configure modem - remember! modem didn't remeber Your's configuration!
gsm.print("at+cmgf=1\r"); // use full functionality (calls, sms, gprs) - see app note
gsm.print("at+clip=1\r"); // enable presentation number
gsm.print("at+cscs=\"GSM\"\r"); // configure sms as standard text messages
gsm.print("at+cnmi=1,2,0,0,0\r"); // show received sms and store in sim (probobly, I don't compre this settings with app note but it's working :)
}
void loop(){
String response = gsmAnswer();
if(response.indexOf("+CMT:") > 0 ) { // SMS arrived
// Now You can parse Your Message, if You wont controll only LED, just write
if(response.indexOf("LED ON") > 0) {
digitalWrite(LED_PIN, HIGH); // enable it
}else if(response.indexOf("LED OFF") > 0) {
digitalWrite(LED_PIN, LOW); // turn off
}
delay(1000);
}
}
String gsmAnswer(){
String answer;
while(!gsm.available());
while(gsm.available()){
delay(5);
if(Serial.available() > 0){
char s = (char)gsm.read();
answer += s;
}
}
return answer;
}
One think more, incomming sms has the following format:
+CMT: "+48xxxxxxxxx","","17/07/07,21:57:04+08"
Test of arrived messages
You should first know exactly what the response is before attempting to parse it.
Try something simple like the following code (note: untested!) to get a feeling of what you should look for:
void loop() {
if(cell.available() > 0) {
char ch = cell.read();
Serial.print(ch);
}
}
My guess is you'll see more than just a '0' or a '1' :)
void loop() {
while(cell.available() > 0) {inchar = cell.read(); readString+=c;delay(1);} ///can be a delay up to (10) so you can get a clear reading
Serial.print(readString); /// Declare a string " String readString; "
for (i=0; i<200; i++){ /// Serch for the txt you sent up to (200) times it depends how long your ""readString" is
if(readString.substring(i,i+4)=="RING"){ //// I am looking for the word RING sent from my phone
digitalWrite(13,HIGH);
break;
}
}
}
this will help you find the specific word ir your reading (text message)