Esp32 LoRa lmic TTN not connecting - iot

I am trying to get my ESP32 + RFM95C connected to The Things Network.
The Error I recieve is simple this:
24951: EV_JOINING
24970: EV_TXSTART
426696: EV_JOIN_TXCOMPLETE: no JoinAccept
And that repeats, Here is my setup code:
static const u1_t PROGMEM APPEUI[8]= { secret stuff here };
void os_getArtEui (u1_t* buf) { memcpy_P(buf, APPEUI, 8);}
// This should also be in little endian format, see above.
// static const u1_t PROGMEM DEVEUI[8]= { secret stuff here };
static const u1_t PROGMEM DEVEUI[8]= { secret stuff here };
void os_getDevEui (u1_t* buf) { memcpy_P(buf, DEVEUI, 8);}
// This key should be in big endian format (or, since it is not really a
// number but a block of memory, endianness does not really apply). In
// practice, a key taken from ttnctl can be copied as-is.
static const u1_t PROGMEM APPKEY[16] = { secret stuff here };
void os_getDevKey (u1_t* buf) { memcpy_P(buf, APPKEY, 16);}
static uint8_t mydata[] = "Hello, world!";
static osjob_t sendjob;
// Schedule TX every this many seconds (might become longer due to duty
// cycle limitations).
const unsigned TX_INTERVAL = 60;
// Pin mapping
const lmic_pinmap lmic_pins = {
.nss = 5,
.rxtx = LMIC_UNUSED_PIN,
.rst = 27,
.dio = {2, 26, 25},
};
void printHex2(unsigned v) {
v &= 0xff;
if (v < 16)
Serial.print('0');
Serial.print(v, HEX);
}
void onEvent (ev_t ev) {
Serial.print(os_getTime());
Serial.print(": ");
switch(ev) {
case EV_SCAN_TIMEOUT:
Serial.println(F("EV_SCAN_TIMEOUT"));
break;
case EV_BEACON_FOUND:
Serial.println(F("EV_BEACON_FOUND"));
break;
case EV_BEACON_MISSED:
Serial.println(F("EV_BEACON_MISSED"));
break;
case EV_BEACON_TRACKED:
Serial.println(F("EV_BEACON_TRACKED"));
break;
case EV_JOINING:
Serial.println(F("EV_JOINING"));
break;
case EV_JOINED:
Serial.println(F("EV_JOINED"));
{
u4_t netid = 0;
devaddr_t devaddr = 0;
u1_t nwkKey[16];
u1_t artKey[16];
LMIC_getSessionKeys(&netid, &devaddr, nwkKey, artKey);
Serial.print("netid: ");
Serial.println(netid, DEC);
Serial.print("devaddr: ");
Serial.println(devaddr, HEX);
Serial.print("AppSKey: ");
for (size_t i=0; i<sizeof(artKey); ++i) {
if (i != 0)
Serial.print("-");
printHex2(artKey[i]);
}
Serial.println("");
Serial.print("NwkSKey: ");
for (size_t i=0; i<sizeof(nwkKey); ++i) {
if (i != 0)
Serial.print("-");
printHex2(nwkKey[i]);
}
Serial.println();
}
// Disable link check validation (automatically enabled
// during join, but because slow data rates change max TX
// size, we don't use it in this example.
LMIC_setLinkCheckMode(0);
break;
/*
|| This event is defined but not used in the code. No
|| point in wasting codespace on it.
||
|| case EV_RFU1:
|| Serial.println(F("EV_RFU1"));
|| break;
*/
case EV_JOIN_FAILED:
Serial.println(F("EV_JOIN_FAILED"));
break;
case EV_REJOIN_FAILED:
Serial.println(F("EV_REJOIN_FAILED"));
break;
case EV_TXCOMPLETE:
Serial.println(F("EV_TXCOMPLETE (includes waiting for RX windows)"));
if (LMIC.txrxFlags & TXRX_ACK)
Serial.println(F("Received ack"));
if (LMIC.dataLen) {
Serial.print(F("Received "));
Serial.print(LMIC.dataLen);
Serial.println(F(" bytes of payload"));
//Now we sleep
esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
esp_deep_sleep_start();
}
// Schedule next transmission
os_setTimedCallback(&sendjob, os_getTime()+sec2osticks(TX_INTERVAL), do_send);
break;
case EV_LOST_TSYNC:
Serial.println(F("EV_LOST_TSYNC"));
break;
case EV_RESET:
Serial.println(F("EV_RESET"));
break;
case EV_RXCOMPLETE:
// data received in ping slot
Serial.println(F("EV_RXCOMPLETE"));
break;
case EV_LINK_DEAD:
Serial.println(F("EV_LINK_DEAD"));
break;
case EV_LINK_ALIVE:
Serial.println(F("EV_LINK_ALIVE"));
break;
/*
|| This event is defined but not used in the code. No
|| point in wasting codespace on it.
||
|| case EV_SCAN_FOUND:
|| Serial.println(F("EV_SCAN_FOUND"));
|| break;
*/
case EV_TXSTART:
Serial.println(F("EV_TXSTART"));
break;
case EV_TXCANCELED:
Serial.println(F("EV_TXCANCELED"));
break;
case EV_RXSTART:
/* do not print anything -- it wrecks timing */
break;
case EV_JOIN_TXCOMPLETE:
Serial.println(F("EV_JOIN_TXCOMPLETE: no JoinAccept"));
break;
default:
Serial.print(F("Unknown event: "));
Serial.println((unsigned) ev);
break;
}
}
void do_send(osjob_t* j){
// Check if there is not a current TX/RX job running
if (LMIC.opmode & OP_TXRXPEND) {
Serial.println(F("OP_TXRXPEND, not sending"));
} else {
// Prepare upstream data transmission at the next possible time.
LMIC_setTxData2(1, mydata, sizeof(mydata)-1, 0);
Serial.println(F("Packet queued"));
}
// Next TX is scheduled after TX_COMPLETE event.
}
Nothing all that special, just boilerplate sketch code.
I have a Dragino LPS8 LoRaWan Gateway with these settings:
Does anyone know why my connection will not go through?

It has been a while, and I have learned a LOT more about LoRaWan since I originally posted this question. I now know that OTAA will not work with a single channel gateway such as the dragino I had shown in the pictures. A gateway such as https://www.adafruit.com/product/4345 (an 8 channel gateway) would have been a better place for me to start this project.

Related

ESP8266 WeMos D1 using deepsleep drains too much battery

I've developed a fingerprint sensor using NodeMCU D1 mini powered by a 1000mah battery.
Everything seems working correctly except for battery energy consumption.
I have read several topic where user says that using deepsleep fuction on NodeMCU 1000mah battery should last more than 3 month but mine doesn't reach 2 days.
This is my circuit schematic
I also report here my code snipped that I'm currently using. The circuit should wake up from deepsleep when the button is pressed and start reading the fingerprint sensor. If it detect a valid fingerprint, a message is sent to MQTT broker.
#include <Adafruit_Fingerprint.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* _ssid = "ZZZXXXYYY";
const char* _password = "pass";
const char* mqttServer = "IPADDRESS";
const int mqttPort = 1883;
const char* mqttUser = "USER";
const char* mqttPassword = "PASS";
long initialMillis = 0;
unsigned int raw=0;
// On Leonardo/Micro or others with hardware serial, use those! #0 is green wire, #1 is white
// uncomment this line:
//#define mySerial Serial
// For UNO and others without hardware serial, we must use software serial...
// pin #2 is IN from sensor (GREEN wire)
// pin #3 is OUT from arduino (WHITE wire)
// comment these two lines if using hardware serial
SoftwareSerial mySerial(4, 5);
WiFiClient espClient;
PubSubClient client(espClient);
Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);
void setup()
{
Serial.begin(9600);
pinMode(A0, INPUT);
// Connect to Fingerprint. Set the data rate for the sensor serial port
finger.begin(57600);
delay(5);
if (finger.verifyPassword()) {
Serial.println("Found fingerprint sensor!");
} else {
Serial.println("Did not find fingerprint sensor :(");
ESP.deepSleep(10 * 1000000);
}
finger.getTemplateCount();
// Connect to WIFI
WiFi.mode(WIFI_STA);
WiFi.begin(_ssid, _password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Connect to MQTT
client.setServer(mqttServer, mqttPort);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESPFingerprint", mqttUser, mqttPassword )) {
Serial.println("Connected to MQTT server");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
// Calculate battery percentage
raw = analogRead(A0);
String bLevel = "{\"Battery\":" + String(raw) + "}";
Serial.print("Battery: ");
Serial.print(raw);
Serial.print(" -> ");
Serial.println(bLevel);
initialMillis = millis();
client.publish("tele/fingerprint/LWT", "Online");
client.publish("tele/fingerprint/STATE", (char*)bLevel.c_str(), true);
Serial.print("MQTT subscribed: ");
Serial.println(WiFi.localIP());
}
void loop()
{
unsigned long currentMillis = millis();
int fid = getFingerprintIDez();
if(fid != -1) {
String fpIdstr = String(fid);
client.publish("cmnd/fingerprint/RESULT", (char*)fpIdstr.c_str());
Serial.println("Fingerprint correct. Going to sleep.");
client.publish("tele/fingerprint/LWT", "Offline");
// trigger disconnection from MQTT broker to correctly send the message before going to sleep
client.disconnect();
espClient.flush();
// wait until connection is closed completely
while(client.state() != -1){
delay(10);
}
ESP.deepSleep(0);
}
else if(currentMillis - initialMillis >= 15000){
Serial.println("Timeout expired. Going to sleep.");
client.publish("tele/fingerprint/LWT", "Offline");
ESP.deepSleep(0);
}
delay(50); //don't ned to run this at full speed.
}
uint8_t getFingerprintID() {
uint8_t p = finger.getImage();
switch (p) {
case FINGERPRINT_OK:
Serial.println("Image taken");
break;
case FINGERPRINT_NOFINGER:
Serial.println("No finger detected");
return p;
case FINGERPRINT_PACKETRECIEVEERR:
Serial.println("Communication error");
return p;
case FINGERPRINT_IMAGEFAIL:
Serial.println("Imaging error");
return p;
default:
Serial.println("Unknown error");
return p;
}
// OK success!
p = finger.image2Tz();
switch (p) {
case FINGERPRINT_OK:
Serial.println("Image converted");
break;
case FINGERPRINT_IMAGEMESS:
Serial.println("Image too messy");
return p;
case FINGERPRINT_PACKETRECIEVEERR:
Serial.println("Communication error");
return p;
case FINGERPRINT_FEATUREFAIL:
Serial.println("Could not find fingerprint features");
return p;
case FINGERPRINT_INVALIDIMAGE:
Serial.println("Could not find fingerprint features");
return p;
default:
Serial.println("Unknown error");
return p;
}
// OK converted!
p = finger.fingerFastSearch();
if (p == FINGERPRINT_OK) {
Serial.println("Found a print match!");
} else if (p == FINGERPRINT_PACKETRECIEVEERR) {
Serial.println("Communication error");
return p;
} else if (p == FINGERPRINT_NOTFOUND) {
Serial.println("Did not find a match");
return p;
} else {
Serial.println("Unknown error");
return p;
}
// found a match!
Serial.print("Found ID #"); Serial.print(finger.fingerID);
Serial.print(" with confidence of "); Serial.println(finger.confidence);
return finger.fingerID;
}
// returns -1 if failed, otherwise returns ID #
int getFingerprintIDez() {
uint8_t p = finger.getImage();
if (p != FINGERPRINT_OK) return -1;
p = finger.image2Tz();
if (p != FINGERPRINT_OK) return -1;
p = finger.fingerFastSearch();
if (p != FINGERPRINT_OK) return -1;
// found a match!
Serial.print("Found ID #"); Serial.print(finger.fingerID);
Serial.print(" with confidence of "); Serial.println(finger.confidence);
return finger.fingerID;
}
Can somebody let me know if there is something wrong in my code or circuit?

How to convert an image file to base64 string using Arduino UNO or using any other Microcontroller?

Suppose I am in a room which is totally locked and I am begging for the key, so I can go outside. But the person who locked the door behind me is asking to solve a problem for him. The problem is that I have an SD card, SD card module, Arduino UNO, power, a laptop with internet access. What I need to do for the person is that I have to convert an image file stored in the SD card to a base64 string using the Arduino. Now I want to know how to this task for the person, so I can go out freely. Kindly remember the title of this question, otherwise, my life is in danger, and please avoid suggestions only. If you have done this before, then you might answer the question, otherwise please do not. Sorry for being harsh, but it is really bad to have a bad answer. StackOverflow is my last hope.
I have used a library called base64 for Arduino, but I didn't solve my problem. Here is the library. https://github.com/adamvr/arduino-base64
My aim was to convert image to the Base64 string format and then send this string through ESP8266 module to the webserver.
Until now, I didn't find any solution to this problem. I found an alternative to send images taken by a camera. That alternative is a camera module with ESP32-S. This module is "ESP32-S Cam", which takes pictures and sends them to an online webserver.
Here is the code for ESP32 Cam for taking and sending picture to the server where we will have a PHP Scrip given under this code.
#include "esp_http_client.h"
#include "esp_camera.h"
#include <WiFi.h>
#include "Arduino.h"
const char* ssid = "ashiq"; // my wifi "SSID" name
const char* password = "11585858"; // my wifi Password
int capture_interval = 20000; // Microseconds between captures
const char *post_url = "http://app.softwarism.com/esp32/getPhoto.php"; // Location where images are POSTED
bool internet_connected = false;
long current_millis;
long last_capture_millis = 0;
//for indicating that the picture has been taken and then sent
#define GPIO_PIN_WAKEUP GPIO_NUM_12
// CAMERA_MODEL_AI_THINKER
#define PWDN_GPIO_NUM 32
#define RESET_GPIO_NUM -1
#define XCLK_GPIO_NUM 0
#define SIOD_GPIO_NUM 26
#define SIOC_GPIO_NUM 27
#define Y9_GPIO_NUM 35
#define Y8_GPIO_NUM 34
#define Y7_GPIO_NUM 39
#define Y6_GPIO_NUM 36
#define Y5_GPIO_NUM 21
#define Y4_GPIO_NUM 19
#define Y3_GPIO_NUM 18
#define Y2_GPIO_NUM 5
#define VSYNC_GPIO_NUM 25
#define HREF_GPIO_NUM 23
#define PCLK_GPIO_NUM 22
void setup()
{
Serial.begin(115200);
//Setup indication pin Mode
pinMode(GPIO_PIN_WAKEUP,OUTPUT);
if (init_wifi()) { // Connected to WiFi
internet_connected = true;
Serial.println("Internet connected");
}
camera_config_t config;
config.ledc_channel = LEDC_CHANNEL_0;
config.ledc_timer = LEDC_TIMER_0;
config.pin_d0 = Y2_GPIO_NUM;
config.pin_d1 = Y3_GPIO_NUM;
config.pin_d2 = Y4_GPIO_NUM;
config.pin_d3 = Y5_GPIO_NUM;
config.pin_d4 = Y6_GPIO_NUM;
config.pin_d5 = Y7_GPIO_NUM;
config.pin_d6 = Y8_GPIO_NUM;
config.pin_d7 = Y9_GPIO_NUM;
config.pin_xclk = XCLK_GPIO_NUM;
config.pin_pclk = PCLK_GPIO_NUM;
config.pin_vsync = VSYNC_GPIO_NUM;
config.pin_href = HREF_GPIO_NUM;
config.pin_sscb_sda = SIOD_GPIO_NUM;
config.pin_sscb_scl = SIOC_GPIO_NUM;
config.pin_pwdn = PWDN_GPIO_NUM;
config.pin_reset = RESET_GPIO_NUM;
config.xclk_freq_hz = 20000000;
config.pixel_format = PIXFORMAT_JPEG;
//init with high specs to pre-allocate larger buffers
if (psramFound()) {
config.frame_size = FRAMESIZE_UXGA;
config.jpeg_quality = 10;
config.fb_count = 2;
} else {
config.frame_size = FRAMESIZE_SVGA;
config.jpeg_quality = 12;
config.fb_count = 1;
}
// camera init
esp_err_t err = esp_camera_init(&config);
if (err != ESP_OK) {
Serial.printf("Camera init failed with error 0x%x", err);
return;
}
}
bool init_wifi()
{
int connAttempts = 0;
Serial.println("\r\nConnecting to: " + String(ssid));
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED ) {
delay(500);
Serial.print(".");
if (connAttempts > 10) return false;
connAttempts++;
}
return true;
}
esp_err_t _http_event_handler(esp_http_client_event_t *evt)
{
switch (evt->event_id) {
case HTTP_EVENT_ERROR:
Serial.println("HTTP_EVENT_ERROR");
break;
case HTTP_EVENT_ON_CONNECTED:
Serial.println("HTTP_EVENT_ON_CONNECTED");
break;
case HTTP_EVENT_HEADER_SENT:
Serial.println("HTTP_EVENT_HEADER_SENT");
break;
case HTTP_EVENT_ON_HEADER:
Serial.println();
Serial.printf("HTTP_EVENT_ON_HEADER, key=%s, value=%s", evt->header_key, evt->header_value);
break;
case HTTP_EVENT_ON_DATA:
Serial.println();
Serial.printf("HTTP_EVENT_ON_DATA, len=%d", evt->data_len);
if (!esp_http_client_is_chunked_response(evt->client)) {
// Write out data
// printf("%.*s", evt->data_len, (char*)evt->data);
}
break;
case HTTP_EVENT_ON_FINISH:
Serial.println("");
Serial.println("HTTP_EVENT_ON_FINISH");
break;
case HTTP_EVENT_DISCONNECTED:
Serial.println("HTTP_EVENT_DISCONNECTED");
break;
}
return ESP_OK;
}
static esp_err_t take_send_photo()
{
Serial.println("Taking picture...");
camera_fb_t * fb = NULL;
esp_err_t res = ESP_OK;
fb = esp_camera_fb_get();
if (!fb) {
Serial.println("Camera capture failed");
return ESP_FAIL;
}else{
indication();
}
esp_http_client_handle_t http_client;
esp_http_client_config_t config_client = {0};
config_client.url = post_url;
config_client.event_handler = _http_event_handler;
config_client.method = HTTP_METHOD_POST;
http_client = esp_http_client_init(&config_client);
esp_http_client_set_post_field(http_client, (const char *)fb->buf, fb->len);
esp_http_client_set_header(http_client, "Content-Type", "image/jpg");
esp_err_t err = esp_http_client_perform(http_client);
if (err == ESP_OK) {
Serial.print("esp_http_client_get_status_code: ");
Serial.println(esp_http_client_get_status_code(http_client));
}
esp_http_client_cleanup(http_client);
esp_camera_fb_return(fb);
}
void loop()
{
// TODO check Wifi and reconnect if needed
current_millis = millis();
if (current_millis - last_capture_millis > capture_interval) { // Take another picture
last_capture_millis = millis();
take_send_photo();
//indicate that the picture has been taken and sent
indication();
}
}
void indication(){
digitalWrite(GPIO_PIN_WAKEUP,HIGH);
delay(1000);
digitalWrite(GPIO_PIN_WAKEUP,LOW);
}
Here is the PHP Script waiting to get the picture sent by the camera.
<?php
require_once("con.php");
$received = file_get_contents('php://input');
$fileToWrite = "uploads/smart_tick_".time().".jpg";
if(file_put_contents($fileToWrite, $received)){
echo "Uploaded";
}
?>
Note: Do not forget to create a folder "uploads" in the same directory where the PHP Script is.

Arduino project Servo glitch (memory game)

I recently got into Arduino with a Rex Qualis Arduino Uno R3 and I am trying to build a project that would beat the Simon memory game (or Repeat the Beat).
It waits for user response through one of four buttons then adds that to the list, executes the list, then waits for user input on the next move.
Everything works how it's supposed to, but the weirdest things happen on execution:
On the first loop after full execution, Servo 1 will execute its move function without authorization.
On the second loop after full execution, Servo 2 will execute its move function and so on.
After the fourth loop, execution, and servo 4 executing its move function, it doesn't happen again. I don't know why it cycles through all the servos one by one in the first four loops then is fine after but it kinda breaks my project.
Is there a problem in my code that redirects to the move functions or something? All help is appreciated. Here is the code for reference:
//Simon killer
//Da Cube
#include <Servo.h>
//Declare buttons
int button1 = 4;
int button2 = 5;
int button3 = 6;
int button4 = 7;
//Declare servos
Servo servo1;
Servo servo2;
Servo servo3;
Servo servo4;
int moves[100]; //Memory up to 100
int x = 0;
int y = 1;
void setup() {
pinMode(button1, INPUT_PULLUP); //Button setup
pinMode(button2, INPUT_PULLUP);
pinMode(button3, INPUT_PULLUP);
pinMode(button4, INPUT_PULLUP);
servo1.attach(8); //Servo setup
servo2.attach(9);
servo3.attach(10);
servo4.attach(11);
moveServo1();//System check
moveServo2();
moveServo3();
moveServo4();
}
//move functions
void moveServo1() {
servo1.write(5);
delay(500);
servo1.write(45);
delay(500);
}
void moveServo2() {
servo2.write(5);
delay(500);
servo2.write(45);
delay(500);
}
void moveServo3() {
servo3.write(175);
delay(500);
servo3.write(135);
delay(500);
}
void moveServo4() {
servo4.write(5);
delay(500);
servo4.write(45);
delay(500);
}
void loop() {
//Read Input by button
while (x < y) {
if (digitalRead(button1) == LOW) {
moves[x] = 1;
x++;
} else if (digitalRead(button2) == LOW) {
moves[x] = 2;
x++;
} else if (digitalRead(button3) == LOW) {
moves[x] = 3;
x++;
} else if (digitalRead(button4) == LOW) {
moves[x] = 4;
x++;
}
}
y++;
//Decode Memory Array
for (int i = 0; i < (sizeof(moves)); i++) {
switch (moves[i]) {
case 1:
moveServo1();
break;
case 2:
moveServo2();
break;
case 3:
moveServo3();
break;
case 4:
moveServo4();
break;
}
}
}
First i would check to see if the code that makes the Servos move 1-4 isn't the one in the setup loop.
moveServo1();//System check
moveServo2();
moveServo3();
moveServo4();
Here you make a servo sistem check, which means every time you power up the arduino, the first servo will move, then the second and so on and only then the void loop starts...comment these lines and see if that helps

Arduino's serial communication with gsm board

I am trying to write a program where arduino receives text from the gsm module.But my program is able to read the first text and perform a duty,but i want it to receive multiple texts and perform individual tasks for each respective texts?Any help will be great.Thank You.
#include <SoftwareSerial.h>
SoftwareSerial gsm(2, 3);
String inString[64]; // string to hold input coming from device
String read;
int count = 0;
boolean verifyingDone = false; // flags to determine the action completed and to perform next action
boolean regist = false;
boolean registercomplete = false;
boolean location = false;
void setup()
{
// put your setup code here, to run once:
Serial.begin(9600);
gsm.begin(4800);
delay(100);
gsm.print("ate0\r"); // removes the echo from the device
delay(100);
gsm.print("at+cnmi=1,2,0,0,0\r"); // to receive a text
Serial.print("The Device has been Intiated");
}
void loop() {
if (gsm.available())
{
while (gsm.available())
{
read = gsm.readString();
verifyNum(); // verifying the number
/* verifyingDone=true;
if(verifyingDone){
delay(1000);
gsm.print("at+cgpsinfo\r");
delay(1000);
checkGps();
verifyingDone=false;
*/
reading1: inString[count++] = read;
Serial.print(String(read));
if (count == 64) {
break;
}
}
delay(200);
count = 0;
}
}
void clearBufferArray()
{
for (int i = 0; i < count; i++)
{
inString[i] = "";
}
}
void verifyNum() {
if (read.startsWith("\r\n+CMT: ")) { // checking the incoming text and verifying the pre-defined number
int index1 = read.indexOf('"');
int index2 = read.indexOf('"', index1 + 1);
String Number = read.substring(index1 + 2, index2);
char floatbuf[100]; // make this at least big enough for the whole string
Number.toCharArray(floatbuf, 100);
int number = atoi(floatbuf);
//Serial.println(number);
delay(1000);
if (strcmp(number, 24190) == 0)
{
Serial.println("The Sending number is " + Number);
Serial.println("This is the registered number");
regist = true;
if (regist) {
gsm.print("AT+CMGS=\"0434519166\"\r"); // Sending registeration confirmation via sms
delay(100);
gsm.print("Success this mobile number has been registered .\r");
gsm.print("\r");
delay(100);
gsm.println((char)26);
delay(10000);
registercomplete = true;
if (regist == true && registercomplete == true) { //after complete registeration ,checking the gps and sending the co-ordinates
checkGps();
delay(500);
}
}
else {
gsm.print("AT+CMGSO=\"0434519166\" \,\"Someone tried to access your device\"\r"); // When not a registered number
}
}
}
}
void checkGps()
{
Serial.print("Gps Search has started");
delay(10000);//big delay to complete previous process //Not able to do this process completely------>Coz not able to re-read the string obtained from the first read..have to find an alternate to read incoming signals efficiently and re-using it
clearBufferArray();
delay(1000);
gsm.write("at+cgpsinfo\r");
delay(10000);
Serial.println();
Serial.println();
Serial.print("Locating.....Wait for a moment");
/*int spacePosition = read.indexOf(':');
if (read.charAt(spacePosition + 1) == ',' && regist==true )*/
if (read.startsWith("\r\n+CGPINFO:,,,"))
{
Serial.println("GPS signal not found.Go outside"); //
gsm.print("AT+CMGS=\"0434519166\"\r"); // Sending location as sms
delay(100);
gsm.print("GPS signal not found.Go outside ");
gsm.print("\r");
delay(100);
gsm.println((char)26);
delay(1000);
regist = false;
}
else
{
Serial.println("Signal found");
gsm.print("AT+CMGS=\"0434519166\"\r"); //Confirming signal found and sending location----->location finding programs can be obtained from previouses sketches
delay(100);
gsm.print("GPS found.Location will be sent soon ");
gsm.print("\r");
delay(100);
gsm.println((char)26);
delay(1000);
}
}
Thank You,Above code is justa tryout ,any help is welcome!

Red Bear Lab BLE Shield isn't connecting to my iPhone

I've recently purchased this: http://redbearlab.com/bleshield/
I've connected it to my Arduino and I'm trying to run the very first test program that they tell me to run which is the BLE Controller sketch. I've connected it and resolved some original compile errors that I initially got, and now it will upload. When I upload it, my iPhone is unresponsive to the shield. I'm trying to figure out if the problem is in the code or if it's a problem with the shield itself. If it's the code, how could I fix the code? I'm relatively new to Arduino and completely new to making it work with Bluetooth. Here's the entire sketch that the guide told me to download from Github.
BLEControllerSketch.ino
/*
Copyright (c) 2012, 2013 RedBearLab
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <Servo.h>
#include <SPI.h>
#include <EEPROM.h>
#include <boards.h>
#include <RBL_nRF8001.h>
#include "Boards.h"
#define PROTOCOL_MAJOR_VERSION 0 //
#define PROTOCOL_MINOR_VERSION 0 //
#define PROTOCOL_BUGFIX_VERSION 2 // bugfix
#define PIN_CAPABILITY_NONE 0x00
#define PIN_CAPABILITY_DIGITAL 0x01
#define PIN_CAPABILITY_ANALOG 0x02
#define PIN_CAPABILITY_PWM 0x04
#define PIN_CAPABILITY_SERVO 0x08
#define PIN_CAPABILITY_I2C 0x10
// pin modes
//#define INPUT 0x00 // defined in wiring.h
//#define OUTPUT 0x01 // defined in wiring.h
#define ANALOG 0x02 // analog pin in analogInput mode
#define PWM 0x03 // digital pin in PWM output mode
#define SERVO 0x04 // digital pin in Servo output mode
byte pin_mode[TOTAL_PINS];
byte pin_state[TOTAL_PINS];
byte pin_pwm[TOTAL_PINS];
byte pin_servo[TOTAL_PINS];
Servo servos[MAX_SERVOS];
void setup()
{
Serial.begin(57600);
Serial.println("BLE Arduino Slave");
/* Default all to digital input */
for (int pin = 0; pin < TOTAL_PINS; pin++)
{
// Set pin to input with internal pull up
pinMode(pin, INPUT);
digitalWrite(pin, HIGH);
// Save pin mode and state
pin_mode[pin] = INPUT;
pin_state[pin] = LOW;
}
// Default pins set to 9 and 8 for REQN and RDYN
// Set your REQN and RDYN here before ble_begin() if you need
//ble_set_pins(3, 2);
// Set your BLE Shield name here, max. length 10
//ble_set_name("My Name");
// Init. and start BLE library.
ble_begin();
}
static byte buf_len = 0;
void ble_write_string(byte *bytes, uint8_t len)
{
if (buf_len + len > 20)
{
for (int j = 0; j < 15000; j++)
ble_do_events();
buf_len = 0;
}
for (int j = 0; j < len; j++)
{
ble_write(bytes[j]);
buf_len++;
}
if (buf_len == 20)
{
for (int j = 0; j < 15000; j++)
ble_do_events();
buf_len = 0;
}
}
byte reportDigitalInput()
{
if (!ble_connected())
return 0;
static byte pin = 0;
byte report = 0;
if (!IS_PIN_DIGITAL(pin))
{
pin++;
if (pin >= TOTAL_PINS)
pin = 0;
return 0;
}
if (pin_mode[pin] == INPUT)
{
byte current_state = digitalRead(pin);
if (pin_state[pin] != current_state)
{
pin_state[pin] = current_state;
byte buf[] = {'G', pin, INPUT, current_state};
ble_write_string(buf, 4);
report = 1;
}
}
pin++;
if (pin >= TOTAL_PINS)
pin = 0;
return report;
}
void reportPinCapability(byte pin)
{
byte buf[] = {'P', pin, 0x00};
byte pin_cap = 0;
if (IS_PIN_DIGITAL(pin))
pin_cap |= PIN_CAPABILITY_DIGITAL;
if (IS_PIN_ANALOG(pin))
pin_cap |= PIN_CAPABILITY_ANALOG;
if (IS_PIN_PWM(pin))
pin_cap |= PIN_CAPABILITY_PWM;
if (IS_PIN_SERVO(pin))
pin_cap |= PIN_CAPABILITY_SERVO;
buf[2] = pin_cap;
ble_write_string(buf, 3);
}
void reportPinServoData(byte pin)
{
// if (IS_PIN_SERVO(pin))
// servos[PIN_TO_SERVO(pin)].write(value);
// pin_servo[pin] = value;
byte value = pin_servo[pin];
byte mode = pin_mode[pin];
byte buf[] = {'G', pin, mode, value};
ble_write_string(buf, 4);
}
byte reportPinAnalogData()
{
if (!ble_connected())
return 0;
static byte pin = 0;
byte report = 0;
if (!IS_PIN_DIGITAL(pin))
{
pin++;
if (pin >= TOTAL_PINS)
pin = 0;
return 0;
}
if (pin_mode[pin] == ANALOG)
{
uint16_t value = analogRead(pin);
byte value_lo = value;
byte value_hi = value>>8;
byte mode = pin_mode[pin];
mode = (value_hi << 4) | mode;
byte buf[] = {'G', pin, mode, value_lo};
ble_write_string(buf, 4);
}
pin++;
if (pin >= TOTAL_PINS)
pin = 0;
return report;
}
void reportPinDigitalData(byte pin)
{
byte state = digitalRead(pin);
byte mode = pin_mode[pin];
byte buf[] = {'G', pin, mode, state};
ble_write_string(buf, 4);
}
void reportPinPWMData(byte pin)
{
byte value = pin_pwm[pin];
byte mode = pin_mode[pin];
byte buf[] = {'G', pin, mode, value};
ble_write_string(buf, 4);
}
void sendCustomData(uint8_t *buf, uint8_t len)
{
uint8_t data[20] = "Z";
memcpy(&data[1], buf, len);
ble_write_string(data, len+1);
}
byte queryDone = false;
void loop()
{
while(ble_available())
{
byte cmd;
cmd = ble_read();
Serial.write(cmd);
// Parse data here
switch (cmd)
{
case 'V': // query protocol version
{
byte buf[] = {'V', 0x00, 0x00, 0x01};
ble_write_string(buf, 4);
}
break;
case 'C': // query board total pin count
{
byte buf[2];
buf[0] = 'C';
buf[1] = TOTAL_PINS;
ble_write_string(buf, 2);
}
break;
case 'M': // query pin mode
{
byte pin = ble_read();
byte buf[] = {'M', pin, pin_mode[pin]}; // report pin mode
ble_write_string(buf, 3);
}
break;
case 'S': // set pin mode
{
byte pin = ble_read();
byte mode = ble_read();
if (IS_PIN_SERVO(pin) && mode != SERVO && servos[PIN_TO_SERVO(pin)].attached())
servos[PIN_TO_SERVO(pin)].detach();
/* ToDo: check the mode is in its capability or not */
/* assume always ok */
if (mode != pin_mode[pin])
{
pinMode(pin, mode);
pin_mode[pin] = mode;
if (mode == OUTPUT)
{
digitalWrite(pin, LOW);
pin_state[pin] = LOW;
}
else if (mode == INPUT)
{
digitalWrite(pin, HIGH);
pin_state[pin] = HIGH;
}
else if (mode == ANALOG)
{
if (IS_PIN_ANALOG(pin)) {
if (IS_PIN_DIGITAL(pin)) {
pinMode(PIN_TO_DIGITAL(pin), LOW);
}
}
}
else if (mode == PWM)
{
if (IS_PIN_PWM(pin))
{
pinMode(PIN_TO_PWM(pin), OUTPUT);
analogWrite(PIN_TO_PWM(pin), 0);
pin_pwm[pin] = 0;
pin_mode[pin] = PWM;
}
}
else if (mode == SERVO)
{
if (IS_PIN_SERVO(pin))
{
pin_servo[pin] = 0;
pin_mode[pin] = SERVO;
if (!servos[PIN_TO_SERVO(pin)].attached())
servos[PIN_TO_SERVO(pin)].attach(PIN_TO_DIGITAL(pin));
}
}
}
// if (mode == ANALOG)
// reportPinAnalogData(pin);
if ( (mode == INPUT) || (mode == OUTPUT) )
reportPinDigitalData(pin);
else if (mode == PWM)
reportPinPWMData(pin);
else if (mode == SERVO)
reportPinServoData(pin);
}
break;
case 'G': // query pin data
{
byte pin = ble_read();
reportPinDigitalData(pin);
}
break;
case 'T': // set pin digital state
{
byte pin = ble_read();
byte state = ble_read();
digitalWrite(pin, state);
reportPinDigitalData(pin);
}
break;
case 'N': // set PWM
{
byte pin = ble_read();
byte value = ble_read();
analogWrite(PIN_TO_PWM(pin), value);
pin_pwm[pin] = value;
reportPinPWMData(pin);
}
break;
case 'O': // set Servo
{
byte pin = ble_read();
byte value = ble_read();
if (IS_PIN_SERVO(pin))
servos[PIN_TO_SERVO(pin)].write(value);
pin_servo[pin] = value;
reportPinServoData(pin);
}
break;
case 'A': // query all pin status
for (int pin = 0; pin < TOTAL_PINS; pin++)
{
reportPinCapability(pin);
if ( (pin_mode[pin] == INPUT) || (pin_mode[pin] == OUTPUT) )
reportPinDigitalData(pin);
else if (pin_mode[pin] == PWM)
reportPinPWMData(pin);
else if (pin_mode[pin] == SERVO)
reportPinServoData(pin);
}
queryDone = true;
{
uint8_t str[] = "ABC";
sendCustomData(str, 3);
}
break;
case 'P': // query pin capability
{
byte pin = ble_read();
reportPinCapability(pin);
}
break;
case 'Z':
{
byte len = ble_read();
byte buf[len];
for (int i=0;i<len;i++)
buf[i] = ble_read();
Serial.println("->");
Serial.print("Received: ");
Serial.print(len);
Serial.println(" byte(s)");
Serial.print(" Hex: ");
for (int i=0;i<len;i++)
Serial.print(buf[i], HEX);
Serial.println();
}
}
// send out any outstanding data
ble_do_events();
buf_len = 0;
return; // only do this task in this loop
}
// process text data
if (Serial.available())
{
byte d = 'Z';
ble_write(d);
delay(5);
while(Serial.available())
{
d = Serial.read();
ble_write(d);
}
ble_do_events();
buf_len = 0;
return;
}
// No input data, no commands, process analog data
if (!ble_connected())
queryDone = false; // reset query state
if (queryDone) // only report data after the query state
{
byte input_data_pending = reportDigitalInput();
if (input_data_pending)
{
ble_do_events();
buf_len = 0;
return; // only do this task in this loop
}
reportPinAnalogData();
ble_do_events();
buf_len = 0;
return;
}
ble_do_events();
buf_len = 0;
}
Any and all help is greatly appreciated.
I've been working with these quite a bit in the last 8 months, so I'll do what I can to help. I don't have the reputation to comment and ask for clarification on specific things, so I'm just gonna try to cover everything I can.
Let's first lay out a few things:
Because your sketch uploaded I'm assuming that you have added all of the necessary libraries to Arduino. If you haven't, I don't know why it is uploading, but be sure to do that.
The problem almost certainly won't be with the Arduino code. I ran the code you provided, as well as the sketch provided by RBL (Red Bear Lab) that is on my computer. I was able to connect to my iPhone using both sketches.
I'm going to lay out everything I think could potentially be the source of the problem:
Make sure that all of your header pins (you should have a bunch of headers sticking out of the board in rows of 3 next to the digital pins) are connected correctly, as RBL shows in their instructions. If you want me to provide a picture of mine I can do that.
Make sure that the white power light is on on your shield. If it isn't, power isn't getting to the shield itself.
Be sure that you actually have bluetooth enabled on your phone.
You didn't mention that you downloaded the app. Be sure to do that (it is called "BLE Controller" by RedBear), as you cannot connect to the iPhone without the app (Apple's bluetooth menu will not show the BLE shield).
If you have downloaded the app, be sure that you have selected the correct setting from the choices using the button on the top left of the screen (3 lines on top of each other). For the sketch you provided, you should select BLE Controller.
If you have tried everything and nothing else is working, try one of the other sketches provided by RBL, such as SimpleChat. This uses the serial monitor on Arduino to communicate back and forth with the iPhone. If this doesn't work, upload a picture of your specific shield (the top of it) so I can take a look at it. Best of luck.

Resources