Cannot connect to ibm bluemix quickstart with the following code - arduino

#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
byte mac[] = { 0xde, 0xed, 0xba, 0xfe, 0xfe, 0xed};
String macstr="deedbafefeed";
byte ip[] = {192,168,1,1 };
char servername[]="quickstart.messaging.internetofthings.ibmcloud.com";
String clientName = String("d:quickstart:iotsample-arduino:")+macstr;
String topicName = String("iot-2/evt/ledstat/fmt/json");
float tempF = 0.0;
float tempC = 0.0;
float humidity = 0.0;
EthernetClient ethClient;
PubSubClient client(servername, 1883,0,ethClient);
void setup()
{
Ethernet.begin(mac,ip);
Serial.begin(9600);
}
void loop()
{
char clientStr[324];
clientName.toCharArray(clientStr,324);
char topicStr[26];
topicName.toCharArray(topicStr,26);
getData();
if (!client.connected()) {
Serial.println(client.connected());
Serial.print("Trying to connect to: ");
Serial.println(clientStr);
client.connect(clientStr);
Serial.println(client.connected());
Serial.print("attempt to send ");
Serial.println(buildJson());
delay(20000);
}
if (client.connected() ) {
String json = buildJson();
char jsonStr[200];
json.toCharArray(jsonStr,200);
boolean pubresult = client.publish(topicStr,jsonStr);
Serial.print("attempt to send ");
Serial.println(jsonStr);
Serial.print("to ");
Serial.println(topicStr);
if (pubresult)
Serial.println("successfully sent");
else
Serial.println("unsuccessfully sent");
}
delay(5000);
}
String buildJson() {
String data = "\n{";
data+="\n";
data+= "\"d\": {";
data+="\n";
data+="\"myName\": \"Arduino DHT11\",";
data+="\n";
data+="\"temperature (F)\": ";
data+=(int)tempF;
data+= ",";
data+="\n";
data+="\"temperature (C)\": ";
data+=(int)tempC;
data+= ",";
data+="\n";
data+="\"humidity\": ";
data+=(int)humidity;
data+="\n";
data+="}";
data+="\n";
data+="}";
return data;
}
void getData() {
int chk=0;
switch (chk)
{
case 0:
Serial.println("Read OK");
humidity = 90;
tempF = 12;
tempC = 56;
break;
case -1:
Serial.println("Checksum error");
break;
case -2:
Serial.println("Time out error");
break;
default:
Serial.println("Unknown error");
break;
}
}
the mac address when given in upper case also gives the same result. Trying any other mac address doesn't show any thing connected on the quickstart website.
The output of serial monitor and what is shown on the quickstart website is shown below
enter image description here

Have you tried recipe on Connecting Arduino Uno to IBM Watson IoT Platform? Where did you get this code from? Looks like the code that you are using is not same as the one given with the recipe. Here is the link to the recipe - https://developer.ibm.com/recipes/tutorials/connect-an-arduino-uno-device-to-the-ibm-internet-of-things-foundation/

Related

Arduino HTTP Client not connecting to Firebase

I am trying to post GPS data to firebase using the Arduino Uno R3, SIM800L and NEO6M via GPRS. I have managed to connect to the APN, but I can't get the "http_client.connect()" to work. It keeps giving the same error.
Code
#define TINY_GSM_MODEM_SIM800
#define TINY_GSM_RX_BUFFER 256
#include <TinyGsmClient.h>
#include <ArduinoHttpClient.h>
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
#define SerialMonitor Serial
#define ARDUINO_GPS_RX 3
#define ARDUINO_GPS_TX 2
TinyGPSPlus tinyGPS;
SoftwareSerial ss(ARDUINO_GPS_TX , ARDUINO_GPS_RX);
#define gpsPort ss
#define rxPin 9
#define txPin 8
SoftwareSerial sim800(txPin,rxPin);
const char FIREBASE_HOST[] = "realtimedatabase.firebaseio.com";
const String FIREBASE_AUTH = "";
const String FIREBASE_PATH = "/gps-data/coordinate/employee_03";
const int SSL_PORT = 443;
char apn[] = "";
char user[] = "";
char pass[] = "";
TinyGsm modem(sim800);
TinyGsmClientSecure gsm_client_secure_modem(modem,0);
HttpClient http_client = HttpClient(gsm_client_secure_modem, FIREBASE_HOST, SSL_PORT);
unsigned long previousMillis = 0;
void setup()
{
Serial.begin(9600);
gpsPort.begin(9600);
Serial.println(F("gps serial initialize"));
sim800.begin(9600);
Serial.println(F("SIM800A serial initialize"));
Serial.println(F("Initializing modem..."));
modem.init();
String modemInfo = modem.getModemInfo();
Serial.print(F("Modem: "));
Serial.println(modemInfo);
http_client.setHttpResponseTimeout(10 * 1000);
}
void loop()
{
Serial.print(F("Connecting to "));
Serial.print(apn);
if (!modem.gprsConnect(apn, user, pass))
{
Serial.println(F(" fail"));
//delay(1000);
return;
}
Serial.println(F(" OK"));
if (modem.isGprsConnected()) { Serial.println("GPRS connected"); }
http_client.connect(FIREBASE_HOST, SSL_PORT);
while (true) {
if (!http_client.connected())
{
Serial.println();
http_client.stop();// Shutdown
Serial.println(F("HTTP not connected"));
break;
}
else
{
//ss.listen();
gps_loop();
}
}
}
void PostToFirebase(const char* method, const String & path , const String & data, HttpClient* http)
{
String response;
int statusCode = 0;
http->connectionKeepAlive();
String url;
if (path[0] != '/')
{
url = "/";
}
url += path + ".json";
url += "?auth=" + FIREBASE_AUTH;
Serial.print("POST:");
Serial.println(url);
Serial.print("Data:");
Serial.println(data);
String contentType = "application/json";
http->put(url, contentType, data);
statusCode = http->responseStatusCode();
Serial.print(F("Status code: "));
Serial.println(statusCode);
response = http->responseBody();
Serial.print(F("Response: "));
Serial.println(response);
if (!http->connected())
{
Serial.println();
http->stop();// Shutdown
Serial.println(F("HTTP POST disconnected"));
}
}
void gps_loop()
{
// ss.listen();
boolean newData = false;
for (unsigned long start = millis(); millis() - start < 2000;){
//ss.listen();
while (ss.available()){
if (tinyGPS.encode(ss.read())){
newData = true;
break;
}
}
}
if(true){
newData = false;
String latitude, longitude;
latitude = String(tinyGPS.location.lat(), 6);
longitude = String(tinyGPS.location.lng(), 6);
Serial.print("Latitude= ");
Serial.print(latitude);
Serial.print(" Longitude= ");
Serial.println(longitude);
String gpsData = "{";
gpsData += "\"lat\":" + latitude + ",";
gpsData += "\"lng\":" + longitude + "";
gpsData += "}";
PostToFirebase("PATCH", FIREBASE_PATH, gpsData, &http_client);
}
}
Error
gps serial initialize
SIM800A serial initialize
Initializing modem...
Modem: SIM800 R14.18
Connecting to apn OK
GPRS connected
HTTP not connected
Connecting to apn OK
GPRS connected
I have tried using ESP8266 (Wemos D1 R1) to save my GPS data to the database via WiFi, and that worked. Now, the problem is I can't connect to the firebase database using my Arduino and SIM800L. What should I do?

Arduino - trying to get latitude and longitude from GPS and send to Firebase but failed

This is the problem continue from my previous question. After I added for listen() in loop function, the data can be read from the GPS and shown in Serial Monitor, but the http connection for now is failed, and it shows the status -2, anyone knows this status error? Is it I need to add other function as well?
#define TINY_GSM_MODEM_SIM800
#define TINY_GSM_RX_BUFFER 256
#include <TinyGsmClient.h>
#include <ArduinoHttpClient.h>
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
#define SerialMonitor Serial
#define ARDUINO_GPS_RX 10
#define ARDUINO_GPS_TX 11
TinyGPSPlus tinyGPS;
SoftwareSerial ss(ARDUINO_GPS_TX , ARDUINO_GPS_RX);
#define gpsPort ss
#define rxPin 8
#define txPin 9
SoftwareSerial sim800(txPin,rxPin);
const char FIREBASE_HOST[] = "my-firebase-host";
const String FIREBASE_AUTH = "my-firebase-auth";
const String FIREBASE_PATH = "/";
const int SSL_PORT = 443;
char apn[] = "internet";
char user[] = "";
char pass[] = "";
TinyGsm modem(sim800);
TinyGsmClientSecure gsm_client_secure_modem(modem, 0);
HttpClient http_client = HttpClient(gsm_client_secure_modem, FIREBASE_HOST, SSL_PORT);
unsigned long previousMillis = 0;
void setup()
{
Serial.begin(9600);
gpsPort.begin(9600);
Serial.println(F("gps serial initialize"));
sim800.begin(9600);
Serial.println(F("SIM800A serial initialize"));
Serial.println(F("Initializing modem..."));
modem.init();
String modemInfo = modem.getModemInfo();
Serial.print(F("Modem: "));
Serial.println(modemInfo);
http_client.setHttpResponseTimeout(10 * 1000);
}
void loop()
{
Serial.print(F("Connecting to "));
Serial.print(apn);
if (!modem.gprsConnect(apn, user, pass))
{
Serial.println(F(" fail"));
//delay(1000);
return;
}
Serial.println(F(" OK"));
http_client.connect(FIREBASE_HOST, SSL_PORT);
while (true) {
if (!http_client.connected())
{
Serial.println();
http_client.stop();// Shutdown
Serial.println(F("HTTP not connected"));
break;
}
else
{
//ss.listen();
gps_loop();
}
}
}
void PostToFirebase(const char* method, const String & path , const String & data, HttpClient* http)
{
String response;
int statusCode = 0;
http->connectionKeepAlive();
String url;
if (path[0] != '/')
{
url = "/";
}
url += path + ".json";
url += "?auth=" + FIREBASE_AUTH;
Serial.print("POST:");
Serial.println(url);
Serial.print("Data:");
Serial.println(data);
String contentType = "application/json";
http->put(url, contentType, data);
statusCode = http->responseStatusCode();
Serial.print(F("Status code: "));
Serial.println(statusCode);
response = http->responseBody();
Serial.print(F("Response: "));
Serial.println(response);
if (!http->connected())
{
Serial.println();
http->stop();// Shutdown
Serial.println(F("HTTP POST disconnected"));
}
}
void gps_loop()
{
ss.listen();
boolean newData = false;
for (unsigned long start = millis(); millis() - start < 2000;){
//ss.listen();
while (ss.available()){
if (tinyGPS.encode(ss.read())){
newData = true;
break;
}
}
}
if(true){
newData = false;
String latitude, longitude;
latitude = String(tinyGPS.location.lat(), 6);
longitude = String(tinyGPS.location.lng(), 6);
Serial.print("Latitude= ");
Serial.print(latitude);
Serial.print(" Longitude= ");
Serial.println(longitude);
String gpsData = "{";
gpsData += "\"lat\":" + latitude + ",";
gpsData += "\"lng\":" + longitude + "";
gpsData += "}";
PostToFirebase("PATCH", FIREBASE_PATH, gpsData, &http_client);
}
}

Arduino - trying to get longitude and latitude from GPS with Arduino Uno and GSM and send the data to Firebase cloud but getting 0.0000

I am using Arduino Uno R3, GSM SIM 800 and GPS to get the latitude and longitude and send to the Firebase cloud, but end up I only can get 0.0000 for the location, was trying for TinyGPS++ code before and the GPS is working. Can someone helps me to see where is the error, I really tried for many solutions but still can't work
*** solved for the above problems
But now comes with the problem is about the http connect with the firebase. The status showing -2 for the http connection problem.
#define TINY_GSM_MODEM_SIM800
#define TINY_GSM_RX_BUFFER 256
#include <TinyGsmClient.h>
#include <ArduinoHttpClient.h>
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
#define SerialMonitor Serial
#define ARDUINO_GPS_RX 11
#define ARDUINO_GPS_TX 10
TinyGPSPlus tinyGPS;
SoftwareSerial ss(ARDUINO_GPS_TX , ARDUINO_GPS_RX);
#define gpsPort ss
#define rxPin 3
#define txPin 2
SoftwareSerial sim800(txPin,rxPin);
const char FIREBASE_HOST[] = "my_firebase_host";
const String FIREBASE_AUTH = "my_firebase_auth";
const String FIREBASE_PATH = "/";
const int SSL_PORT = 443;
char apn[] = "internet";
char user[] = "";
char pass[] = "";
TinyGsm modem(sim800);
TinyGsmClientSecure gsm_client_secure_modem(modem, 0);
HttpClient http_client = HttpClient(gsm_client_secure_modem, FIREBASE_HOST, SSL_PORT);
unsigned long previousMillis = 0;
void setup()
{
Serial.begin(9600);
gpsPort.begin(9600);
Serial.println(F("gps serial initialize"));
sim800.begin(9600);
Serial.println(F("SIM800A serial initialize"));
Serial.println(F("Initializing modem..."));
modem.init();
String modemInfo = modem.getModemInfo();
Serial.print(F("Modem: "));
Serial.println(modemInfo);
http_client.setHttpResponseTimeout(10 * 1000);
}
void loop()
{
Serial.print(F("Connecting to "));
Serial.print(apn);
if (!modem.gprsConnect(apn, user, pass))
{
Serial.println(F(" fail"));
//delay(1000);
return;
}
Serial.println(F(" OK"));
http_client.connect(FIREBASE_HOST, SSL_PORT);
while (true) {
if (!http_client.connected())
{
Serial.println();
http_client.stop();// Shutdown
Serial.println(F("HTTP not connected"));
break;
}
else
{
gps_loop();
}
}
}
void PostToFirebase(const char* method, const String & path , const String & data, HttpClient* http)
{
String response;
int statusCode = 0;
http->connectionKeepAlive();
String url;
if (path[0] != '/')
{
url = "/";
}
url += path + ".json";
url += "?auth=" + FIREBASE_AUTH;
Serial.print("POST:");
Serial.println(url);
Serial.print("Data:");
Serial.println(data);
String contentType = "application/json";
http->put(url, contentType, data);
statusCode = http->responseStatusCode();
Serial.print(F("Status code: "));
Serial.println(statusCode);
response = http->responseBody();
Serial.print(F("Response: "));
Serial.println(response);
if (!http->connected())
{
Serial.println();
http->stop();// Shutdown
Serial.println(F("HTTP POST disconnected"));
}
}
void gps_loop()
{
boolean newData = false;
for (unsigned long start = millis(); millis() - start < 2000;){
while (ss.available()){
if (tinyGPS.encode(ss.read())){
newData = true;
break;
}
}
}
if(true){
newData = false;
String latitude, longitude;
latitude = String(tinyGPS.location.lat(), 6);
longitude = String(tinyGPS.location.lng(), 6);
Serial.print("Latitude= ");
Serial.print(latitude);
Serial.print(" Longitude= ");
Serial.println(longitude);
String gpsData = "{";
gpsData += "\"lat\":" + latitude + ",";
gpsData += "\"lng\":" + longitude + "";
gpsData += "}";
PostToFirebase("PATCH", FIREBASE_PATH, gpsData, &http_client);
}
}

Error using thingspeak talk back to control arduino led

The error I'm facing is about using talkback function of thingspeak to control my Arduino LED. it cannot execute the talkback command to off the led. The error is in my void get talkback. Please help me
#include "ThingSpeak.h"
#include <Ethernet.h>
#define redLED 8
byte mac[] = {0x90, 0xA2, 0xDA, 0x10, 0x40, 0x4F};
const String channelsAPIKey = "";
const String talkBackAPIKey = "";
const String talkBackID = "";
const String talkCommandID = "";
const unsigned int getTalkBackInterval = 10 * 1000;
const unsigned int updateChannelsInterval = 15 * 1000;
String talkBackCommand;
long lastConnectionTimeChannels = 0;
boolean lastConnectedChannels = false;
int failedCounterChannels = 0;
long lastConnectionTimeTalkBack = 0;
boolean lastConnectedTalkBack = false;
int failedCounterTalkBack = 0;
char charIn;
// Arduino Ethernet Client is initialized
EthernetClient client;
void setup()
{
Ethernet.init(10); // Most Arduino Ethernet hardware
Serial.begin(9600); //Initialize serial
// start the Ethernet connection:
pinMode(redLED, OUTPUT);
digitalWrite(redLED, HIGH);
}
void loop()
{
getTalkBack();
}
void getTalkBack()
{
String tsData;
tsData = talkBackID + "/commands/execute?api_key=" + talkBackAPIKey;
if ((!client.connected() && (millis() - lastConnectionTimeTalkBack > getTalkBackInterval)))
{
if (client.connect("api.thingspeak.com", 80))
{
client.println("GET /talkbacks/" + tsData + " HTTP/1.0");
client.println();
lastConnectionTimeTalkBack = millis();
if (client.connected())
{
Serial.println("---------------------------------------");
Serial.println("GET TalkBack command");
Serial.println();
Serial.println("Connecting to ThingSpeak");
Serial.println();
Serial.println();
Serial.println("Server response");
Serial.println();
failedCounterTalkBack = 0;
while (client.connected() && !client.available()) delay(2000); //waits for data
while (client.connected() || client.available())
{
charIn = client.read();
talkBackCommand += charIn;
Serial.print(charIn);
if (talkBackCommand == "LED_ON")
{
digitalWrite(redLED, HIGH);
}
if (talkBackCommand == "LED_OFF")
{
digitalWrite(redLED, LOW);
}
}
if (talkBackCommand = talkBackCommand.substring(talkBackCommand.indexOf("_CMD_") + 5));
{
Serial.println();
Serial.println();
Serial.println("Disconnected");
Serial.println();
Serial.println("--------");
Serial.println();
Serial.println("talkback command was");
Serial.println();
Serial.println("--------");
Serial.println();
Serial.println(talkBackCommand);
Serial.println("--------");
Serial.println();
}
}
else
{
failedCounterTalkBack++;
Serial.println("Connection to ThingSpeak failed (" + String(failedCounterTalkBack, DEC) + ")");
Serial.println();
lastConnectionTimeChannels = millis();
}
}
}
if (failedCounterTalkBack > 3 )
{
startEthernet();
}
client.stop();
Serial.flush();
}
The below is a image from my serial monitor. It shows that I can capture the command but couldn't execute it.
Looks like you are reading and appending all the received bytes to talkBackCommand. So, talkBackCommand is "HTTP/1.1 200 OK Date...." and if (talkBackCommand == "LED_ON") would never be true.
I think you wanted to see if the received data contain your commands LED_ON or LED_OFF. You can do something like this:
if (talkBackCommand.indexOf("LED_ON") != -1)
indexOf() locates a String in a String and returns index or -1 if not found.
See more info about indexOf() here: https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/indexof/

Send Mirf values with ethercard

I have project where I'm getting data over nRF24L01 and using Mirf to that. Now I'm working for Hub which need to send data to my webservice. For ethernet my choice was ENC28j60 with ethercard library.
Question : How I can wait data from Mirf and just send data forward with Ethercard browseUrl? I can send data without Mirf but there's some loop which I'm not understand.
My code :
#include <SPI.h>
#include <Mirf.h>
#include <nRF24L01.h>
#include <MirfHardwareSpiDriver.h>
#include <EtherCard.h>
// Set network settings
static byte mymac[] = { 0x74, 0x69, 0x69, 0x2D, 0x30, 0x31 };
byte Ethernet::buffer[700];
static uint32_t timer;
// My webservice
const char website[] PROGMEM = "my.webservice.com";
// Mirf variables
int tmpVal1;
// Local components
const int Yellow = 6;
const int Blue = 5;
void setup() {
Serial.begin(57600);
// Setup leds
pinMode(Yellow, OUTPUT);
digitalWrite(Yellow, LOW);
pinMode(Blue, OUTPUT);
digitalWrite(Blue, LOW);
setupMirf();
setupEthernet();
}
void loop() {
// Waiting to get date from Mirf
while (!Mirf.dataReady()) {
//ether.packetLoop(ether.packetReceive());
}
Mirf.getData((byte *)&tmpVal1);
Serial.print(tmpVal1);
Serial.println(F(" C"));
// Receive responses
ether.packetLoop(ether.packetReceive());
if (millis() > timer) {
timer = millis() + 5000;
//Serial.println();
Serial.println("Sending data to webservice : ");
ether.browseUrl(PSTR("/sendingdata.asmx/sendingdata?"), "Device=100&DeviceValue=80", website, my_callback);
}
//ShowLedNotification();
}
// called when the client request is complete
static void my_callback (byte status, word off, word len) {
Serial.println(">>>");
Ethernet::buffer[off+300] = 0;
Serial.print((const char*) Ethernet::buffer + off);
Serial.println("...");
digitalWrite(Blue,HIGH);
delay(200);
digitalWrite(Blue,LOW);
}
void ShowLedNotification() {
if (tmpVal1 > 0 ) {
digitalWrite(Yellow, HIGH);
delay(1000);
digitalWrite(Yellow, LOW);
}
else
{
digitalWrite(Blue, HIGH);
delay(1000);
digitalWrite(Blue, LOW);
}
}
long readVcc() {
long result;
// Read 1.1V reference against AVcc
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
delay(2); // Wait for Vref to settle
ADCSRA |= _BV(ADSC); // Convert
while (bit_is_set(ADCSRA,ADSC));
result = ADCL;
result |= ADCH<<8;
result = 1126400L / result; // Back-calculate AVcc in mV
return result;
}
//Setting up network and getting DHCP IP
void setupEthernet() {
Serial.println(F("Setting up network and DHCP"));
Serial.print(F("MAC: "));
for (byte i = 0; i < 6; ++i) {
Serial.print(mymac[i], HEX);
if (i < 5)
Serial.print(':');
}
Serial.println();
if (ether.begin(sizeof Ethernet::buffer, mymac) == 0)
Serial.println(F("Failed to access Ethernet controller"));
Serial.println(F("Setting up DHCP"));
if (!ether.dhcpSetup())
Serial.println(F("DHCP failed"));
ether.printIp("My IP: ", ether.myip);
ether.printIp("Netmask: ", ether.netmask);
ether.printIp("GW IP: ", ether.gwip);
ether.printIp("DNS IP: ", ether.dnsip);
// Check network connection
if (!ether.dnsLookup(website))
Serial.println("DNS failed");
ether.printIp("SRV: ", ether.hisip);
}
void setupMirf() {
//Initialize nRF24
Serial.println(F("Initializing Mirf"));
Mirf.spi = &MirfHardwareSpi;
Mirf.init();
Mirf.setRADDR((byte *)"serv1");
Mirf.payload = sizeof(tmpVal1);
// we use channel 90 as it is outside of WLAN bands
// or channels used by wireless surveillance cameras
Mirf.channel = 90;
Mirf.config();
}
Did get that work. Now using if clause not while Mirf.dataReady()
void loop() {
if (Mirf.dataReady()) {
Mirf.getData((byte *)&tmpVal1);
Serial.print(tmpVal1);
Serial.println(F(" C"));
ShowLedNotification();
// Send data to webservice
if (millis() > timer) {
timer = millis() + 5000;
Serial.println("Sending data to webservice");
String myVarsStr = "Device=";
myVarsStr += myDeviceID;
myVarsStr += "&DeviceValue=";
myVarsStr += tmpVal1;
char myVarsCh[40];
myVarsStr.toCharArray(myVarsCh, 40);
ether.browseUrl(PSTR("/receivedata.asmx/ReceiveData?"), myVarsCh, website, my_callback);
}
}
else
{
word pos = ether.packetReceive();
word len = ether.packetLoop(pos);
delay(200);
}
}

Resources