Arduino LORA Send and Receive Data - arduino

I tried to allow sending and receiving data using 2 Arduino Unos, 2 LORA chips (SX1278 433MHz), 2 antennas and 2 Arduino IDE.
Problem is with the receiving data command.
This is the code for SENDING command:
#include <SPI.h>
#include <LoRa.h>
int counter = 0;
const int ss = 10;
const int reset = 9;
const int dio0 = 2;
void setup() {
Serial.begin(9600);
LoRa.begin(433E6);
LoRa.setPins(ss, reset, dio0);
while (!Serial);
Serial.println("LoRa Sender");
}
void loop() {
Serial.print("Sending packet: ");
Serial.println(counter);
// send packet
LoRa.beginPacket();
LoRa.print("hello ");
LoRa.print(counter);
LoRa.endPacket();
counter++;
delay(5000);
}
On serial monitor, I succeed in sending packages, but not receiving. This is the RECEIVING code:
#include <SPI.h>
#include <LoRa.h>
const int ss = 10;
const int reset = 9;
const int dio0 = 2;
void setup() {
Serial.begin(9600);
LoRa.begin(433E6);
LoRa.setPins(ss, reset, dio0);
while (!Serial);
Serial.println("LoRa Receiver");
}
void loop() {
// try to parse packet
int packetSize = LoRa.parsePacket();
if (packetSize) {
// received a packet
Serial.print("Received packet '");
// read packet
while (LoRa.available()) {
Serial.print((char)LoRa.read());
Serial.print("hello ");
}
// print RSSI of packet
Serial.print("' with RSSI ");
Serial.println(LoRa.packetRssi());
}
}
I used instructions about connections from this git page:
https://github.com/sandeepmistry/arduino-LoRa

To make this board work, I had to explicitly initialize SPI
SPI.begin(/*sck*/ 5, /*miso*/ 19, /*mosi*/ 27, /*ss*/ cs);
It may be the same for yours. Also, you should properly initialize Lora:
while (!LoRa.begin(433E6)) {
Serial.print(".");
delay(500);
}
Serial.println("LoRa Initializing OK!");
With the code you posted, you don't really know if it initialized correcly or if it's actually sending any data.

First I haven't worked with Lora library. I worked with SX1278 libaray. So I can help you with that.
At first here is the link to the libaray - Lora SX1278.h library
Now you might ask why I'm not using the library from the original GitHub repo. Well I faced issue with that library and the issue is this:
The sx1278::getPacket() library function is modified to stabilize the Lora receive functionality. There was a bug which led the esp to panic. The payloadlength read from the REG_FIFO register was not checked for valid value which led to reading the REG_FIFO register read for over 65000 times. Moreover yield() is added in time consuming parts of this function.
That is why I'm using this custom library. Anyway, for you:
You can use this function to send packet:
T_packet_state = sx1278.sendPacketTimeoutACK(ControllerAddress, message); //T_packet_state is 0 if the packet data is sent successful.
Also to receive data use this function:
R_packet_state = sx1278.receivePacketTimeoutACK(); //R_packet_state is 0 if the packet data is received successfully.
And at the beginning of the code just define this few things:
//Lora SX1278:
#define LORA_MODE 10 //Add your suitable mode from the library
#define LORA_CHANNEL CH_6_BW_125 //Ch number and Bandwidth
#define LORA_ADDRESS 3 //Address of the device from which you will send data
uint8_t ControllerAddress = 5; //Address of receiving end device
My first decent answer on StackOverflow. Finger Crossed

Related

How can I connect an ESP32 to an A6 GSM module?

I'm really in need of help with this problem and as most commonly advised, I have researched and researched and researched for days and I can't figure out what's wrong...
With that being said, I'm working on a project that uses an ESP-32S (pinout) and an A6 GSM module. (pinout) I'm attempting to get them connected to have the A6 send data to ThingSpeak... My problem is that I can't get it to work... I have the exact same configuration between the two using an ESP8266 and it connects and works but with the ESP32S it just doesn't seem to work...
Below is the code I have used to connect the 32 to the A6 and everything says success and pass but it won't change any ThingSpeak values using any methods...
#define TINY_GSM_MODEM_A6
#include "TinyGsmClient.h"
#include "ThingSpeak.h"
#define SerialMon Serial
HardwareSerial SerialAT(1);
bool modemConeted;
// Your GPRS credentials
// Leave empty, if missing user or pass
const char apn[] = "wireless.twilio.com";
const char user[] = "";
const char pass[] = "";
bool dataSent = false;
TinyGsm modem(SerialAT);
TinyGsmClient client(modem);
void setup(){
SerialMon.begin(9600);
delay(1000);
gsmModSetup();
}
void gsmModSetup() {
// Set GSM module baud rate
SerialAT.begin(9600, SERIAL_8N1, 27, 26, false); //27 and 26 are the pins on the ESP32S connected to the U_Rxd/U_Txd pins of A6
delay(3000);
SerialMon.println("Initializing modem...");
modem.init();
delay(3000);
String modemInfo = modem.getModemInfo();
SerialMon.print("Modem: ");
SerialMon.println(modemInfo);
SerialMon.print("Waiting for network...");
if (!modem.waitForNetwork()) {
SerialMon.println(" fail");
delay(10000);
return;
}
SerialMon.println(" OK");
SerialMon.print("Connecting to ");
SerialMon.print(apn);
if (!modem.gprsConnect(apn, user, pass)) {
SerialMon.println(" fail");
delay(5000);
return;
}
SerialMon.println(" OK");
}
void loop(){
}
I'm using a Twilo Sim card that's loaded with data (as said above it works with esp8266 so not the SIM and not the board) The only part of this code that doesn't pass is the part that says GPRS connect. it never says pass or fail. It just sits for like five minutes then continues.
After this, I try and post to ThingSpeak and it gives ThingSpeak ERROR-307 which means failed to connect to ThingSpeak...
I have tried 2 different ways
The what I find the easy and normal way
ThingSpeak.setField(1, temp);
ThingSpeak.setField(2, h);
ThingSpeak.setField(3, p);
ThingSpeak.setField(4, pt);
ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
and the more complicated way of connecting to the server then sends a GET command with all the values put together with strings.
if (client.connect(thingSpeakAddress, 80))
{
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: " + WriteAPIKey + "\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(thingSpeakData.length());
client.print("\n\n");
client.print(thingSpeakData);
}
client.stop();
Yet neither work and I don't know what to do... My A6 is connected to the 32 using GPIO26 & 27 they're connected to the A6 U_Rxd/U_Txd pins. All boards share common ground as they should.
Any more guides to read or code to change or libraries to try would be extremely helpful as my days of digging has yielded nothing but frustration as one attempt after another fails. the readers of this really are my last hope in solving this problem that's hindering my farther progression.
(Any questions about anything on my end, please ask. -Thank you)
The enclose documentation shows ESP32S pins for HW Serial 0 RX/TX on pin GIPO01/GIPO03, HW Serial 1 RX/TX on pin GIPO09/GIPO10 Given you have attached no oter HW at the moment, why not try with the basic config with serial1Read about this: https://github.com/G6EJD/ESP32-Using-Hardware-Serial-Ports and use the latest core ESP32 package (as of today 23.3.2020 is 1.04, previous releases had issues with serial. Do notforget to setup the serial a given in the article its different to esp8266 (!) so much about code compability. If you use the code on both platforms, you have to work with
#ifdef ESP32
//configure serial for esp32
#elif ESP8266
//configure serial for esp8266
#else
#error "Hardware not supported"
#endif
Here a small test routine for just the serial communication. If you type something in the input line of serial monitor it should be mirrored in the output window
#include <HardwareSerial.h>
void setup() {
Serial.begin(9600);
// set the data rate for the HardwareSerial port
Serial2.begin(9600);
}
void loop() {
if (Serial2.available()) {
Serial.write(Serial2.read());
}
if (Serial.available()) {
Serial2.write(Serial.read());
}
}
You can then expand the serial2 to your settings. If it fails it may be dueto: U1UXD is unused and can be used for your projects. Some boards use this port for SPI Flash access though - so try Serial3.

SMS notification not working with Arduino Nano with a GSM module

I want to use an Arduino Nano to monitor SMS traffic of a GSM module. I'm able to read and send SMS but the notification system is not working: when I send an SMS (to the SIM card that is in the GSM module) no new data becomes available in the Serial port. Any idea why or how can I debug to find the problem?
The communication is done through pins 9 and 10 of Arduino and RX and TX for the GSM module, which is an Quectel EC25. The code I'm using:
#include <SoftwareSerial.h>
#define DEBUG Serial
SoftwareSerial EC25(10,9); // RX, TX - 9600 baud rate
// pin 8 of raspi -> pin 9 of arduino nano
// pin 10 of raspi -> pin 10 of arduino nano
#define AT_RESPONSE_LEN 100
#define TIMEOUT 1000
void setup() {
// put your setup code here, to run once:
EC25.begin(9600);
DEBUG.begin(9600);
// some AT commands just to see if the coms are ok
sendATComm("AT","OK\r\n");
sendATComm("AT+IPR?","OK\r\n");
sendATComm("AT+CGSN","OK\r\n");
sendATComm("AT+CNMI=2,1,0,0,0","OK\r\n");
DEBUG.println("listennig");
}
void loop() {
// put your main code here, to run repeatedly:
if (EC25.available()){
DEBUG.println("Notification received!");
}
}
// function for sending at command.
const char* sendATComm(const char *command, const char *desired_reponse)
{
uint32_t timer;
char response[AT_RESPONSE_LEN]; // module response for AT commands.
memset(response, 0 , AT_RESPONSE_LEN);
EC25.flush();
sendATCommOnce(command);
timer = millis();
while(true){
if(millis()-timer > TIMEOUT){
sendATCommOnce(command);
timer = millis();
}
char c;
int i = 0;
while(EC25.available()){
c = EC25.read();
DEBUG.write(c);
response[i++]=c;
delay(2);
}
if(strstr(response, desired_reponse)){
return response;
memset(response, 0 , strlen(response));
break;
}
}
}
// send at comamand to module
void sendATCommOnce(const char *comm)
{
EC25.print(comm);
EC25.print("\r");
delay(100);
}
So, it turns out that I had to define the output port of URC to use UART communication (not using it as default).
The default configuration was set to either usbat or usbmodem, meaning that the notification information I was waiting for was being sent to one of these serial ports. But I was listening to UART (through RX and TX pints) and therefore I was not getting any notification.
AT command QURCCFG can be used to set which port URC signals should be sent to. In this case I want them to be sent to UART:
AT+QURCCFG="urcport","uart1"

ESP8266 to ESP8266 i2C Communication

I am trying to get my ESP8266's connect and send messages over an i2c bus. I am using a NodeMcu Development Board. Pins D1,D2 and GND are connected to each other.
The code on my master is :
#include <Wire.h>
void setup() {
Wire.begin(D1,D2); // join i2c bus (address optional for master)
Serial.begin(115200);
}
byte x = 0;
void loop() {
Wire.beginTransmission(8);
Wire.write(x); // sends one byte
Wire.endTransmission(); // stop transmitting
Serial.println("Transmitted");
x++;
delay(500);
}
And the code on my slave ESP is:
#include <Wire.h>
void setup() {
Wire.begin(8); // join i2c bus with address #8
Wire.onReceive(receiveEvent); // register event
Serial.begin(115200); // start serial for output
}
void loop() {
delay(100);
}
// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
Serial.println("Received..");
/*
while (1 < Wire.available()) { // loop through all but the last
char c = Wire.read(); // receive byte as a character
Serial.print(c); // print the character
}
*/
int x = Wire.read(); // receive byte as an integer
Serial.println(x); // print the integer
}
Running this gives no output on the receiver chip.
As mentioned in the comments it doesn't look like I2C is supported, but you could use PJON
You just need to connect a single wire to enable communication between the two devices
I'm not sure but I would expect the Wire library from Arduino to use the hardware I2C controller for ATMega. The I2C driver in the firmware from Espressif seems to be doing I2C over GPIO, that would hint there is no hw controller on ESP (what are the odds they would be the same anyway). So you need to use something else than Wire.h, thus I would suggest - try downloading something that fakes I2C over GPIO for your Arduino IDE. Like this .. maybe, I haven't tried that out. I know not a complete solution, but maybe at least this helps.. good luck!
ESP8266(I2C Master) to ESP8266(I2C Slave) works from version 2.5.0. Check out my comments on the ESP8266 GitHub

I2C Stops Transmitting After Exactly 7 Requests with Arduino

I am using an ATTiny85 running the TinyWire library to communicate with an Arduino Uno running the Wire library, from an I2C connection. I can transmit one byte at a time perfectly fine for as many requests as I want, however a problem arises when I try and send two bytes at a time. Below is the code I am using (note - I am using a popular modified version of the TinyWire library which has the OnRequest method implemented). Here's my code for the slave:
#include "TinyWireS.h" // wrapper class for I2C slave routines
#define I2C_SLAVE_ADDR 0x27 // i2c slave address
void setup()
{
TinyWireS.begin(I2C_SLAVE_ADDR); // init I2C Slave mode
TinyWireS.onRequest(requestEvent);
}
void loop()
{
}
void requestEvent()
{
int16_t bigNum = analogRead(3);
byte myArray[2];
myArray[0] = (bigNum >> 8) & 0xFF;
myArray[1] = bigNum & 0xFF;
TinyWireS.send(myArray[0]);
TinyWireS.send(myArray[1]);
}
and for the master:
#include <Wire.h>
#define DEVICE_2 0x27
void setup()
{
Wire.begin();
Serial.begin(9600);
}
void loop()
{
delay(2000);
int16_t bigNum;
byte a,b;
// read 2 bytes, from address 0x27
Serial.println("Request Start");
Wire.requestFrom(DEVICE_2, 2);
a = Wire.read();
b = Wire.read();
bigNum = a;
bigNum = bigNum << 8 | b;
Serial.print(bigNum);
Serial.print("\n");
}
Regardless of the delay time, I can always only get exactly 7 requests. I've tried many values from no delay to 5 second delays in between calls. If I power off the ATTiny, then supply power again while the Uno is still connected to the Serial port, I can get 7 more requests before stopping again. The Serial monitor always shows that the Uno's main loop somehow gets paused directly after calling requestFrom(), which makes it look to me like it's waiting for something, but I can't figure out what. When I unplug the ATTiny, the Uno prints to the Serial port -28412. I have also tried putting the following before reading from the buffer:
if(Wire.available() > 0) {
a = Wire.read();
b = Wire.read();
}
Thanks for your help.
According to this Issue, you can only send one byte from the onRequest callback function. It is called from the ISR, so it really shouldn't do very much. He suggests remembering which byte has been sent, then send the next one when another request event happens. See this example.

Cosm example with temp and humidity sensor (DHT11) added

Added a temperature and humidity sensor (DHT11) to the standard Cosm Arduino sensor client example. Works for a short while then data streams flat line.
Any idea what could be causing the problem?
Many thanks
Staza
/**
* Cosm Arduino sensor client example.
*
`` * This sketch demonstrates connecting an Arduino to Cosm (https://cosm.com),
* using the new Arduino library to send and receive data.
/**
DHT11 temp and humidity sensor added to the COSM example code
**/
#include <SPI.h>
#include <Ethernet.h>
#include <HttpClient.h>
#include <Cosm.h>
#include <dht11.h>
//DHT11*********************************************************************
dht11 DHT11;
#define DHT11PIN 7//pin DHT11 sensor is connected to
//DHT11*********************************************************************
#define API_KEY "xxxxxx" // your Cosm API key
#define FEED_ID xxxxx // your Cosm feed ID
// MAC address for your Ethernet shield
byte mac[] = {xxxx, xxxx, xxxx, xxxx, xxxx, xxxx};
// Analog pin which we're monitoring (0 and 1 are used by the Ethernet shield)
int sensorPin = 2;
unsigned long lastConnectionTime = 0; // last time we connected to Cosm
const unsigned long connectionInterval = 15000; // delay between connecting to Cosm in milliseconds
// Initialize the Cosm library
// Define the string for our datastream ID
char sensorId[] = "sensor_reading";
char sensorId2[] = "DHT11_humidity_sensor_reading";
char sensorId3[] = "DHT11_temperature_sensor_reading";
CosmDatastream datastreams[] = {
CosmDatastream(sensorId, strlen(sensorId), DATASTREAM_FLOAT),
CosmDatastream(sensorId2, strlen(sensorId2), DATASTREAM_FLOAT),
CosmDatastream(sensorId3, strlen(sensorId3), DATASTREAM_FLOAT),
};
// Wrap the datastream into a feed
CosmFeed feed(FEED_ID, datastreams, 3 /* number of datastreams */);
EthernetClient client;
CosmClient cosmclient(client);
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println("Cosm Sensor Client Example");
Serial.println("==========================");
Serial.println("Initializing network");
while (Ethernet.begin(mac) != 1) {
Serial.println("Error getting IP address via DHCP, trying again...");
delay(15000);
}
Serial.println("Network initialized");
Serial.println();
}
void loop() {
// main program loop
if (millis() - lastConnectionTime > connectionInterval) {
//check DHT11 sensor is working OK
int chk = DHT11.read(DHT11PIN);
Serial.print("Read DHT11 sensor: ");
switch (chk)
{
case 0: Serial.println("OK"); break;
case -1: Serial.println("Checksum error"); break;
case -2: Serial.println("Time out error"); break;
default: Serial.println("Unknown error"); break;
}
sendData(); // send data to Cosm
getData(); // read the datastream back from Cosm
lastConnectionTime = millis(); // update connection time so we wait before connecting again
}
}
// send the supplied values to Cosm, printing some debug information as we go
void sendData() {
int sensorValue = analogRead(sensorPin);
int humidityDHT11 = ((float)DHT11.humidity);
int tempDHT11 = ((float)DHT11.temperature);
datastreams[0].setFloat(sensorValue);
datastreams[1].setFloat(humidityDHT11); //DHT11 humidity value*******
datastreams[2].setFloat(tempDHT11); //DHT11 temp value********
Serial.print("Read sensor value ");
Serial.println(datastreams[0].getFloat());
Serial.print("Read DHT11 humidity sensor value ");
Serial.println(datastreams[1].getFloat());
Serial.print("Read DHT11 temperature sensor value ");
Serial.println(datastreams[2].getFloat());
Serial.println("Uploading to Cosm");
int ret = cosmclient.put(feed, API_KEY);
Serial.print("PUT return code: ");
Serial.println(ret);
Serial.println();
}
// get the value of the datastream from Cosm, printing out the value we received
void getData() {
Serial.println("Reading data from Cosm");
int ret = cosmclient.get(feed, API_KEY);
Serial.print("GET return code: ");
Serial.println(ret);
if (ret > 0) {
Serial.print("Datastream is: ");
Serial.println(feed[0]);
Serial.print("Sensor value is: ");
Serial.println(feed[0].getFloat());
Serial.print("Datastream is: ");
Serial.println(feed[1]);
Serial.print("Sensor value is: ");
Serial.println(feed[1].getFloat());
Serial.print("Datastream is: ");
Serial.println(feed[2]);
Serial.print("Sensor value is: ");
Serial.println(feed[2].getFloat());
}
Serial.println();
}
Cosm has a debug page which might give you a clue as to what's going wrong.
This is currently located at: https://cosm.com/users/YOURUSERNAME/debug and it lists all incoming requests in real time as they come through. If your device works initially, you should see it start making requests successfully, and depending on how long it takes till it flatlines you might be able to keep this page open and hopefully see when it starts failing.
Do you see anything in the Arduino serial output when it seems to stop working, or does it seem like the Arduino is still happily sending data?
The other thing you could try is using Wireshark to inspect network traffic over the wire. Setting this up is slightly more involved however, so I'd suggest trying the other approaches first.
If none of this seems feasible I'd suggest mailing Cosm support with your feed details and have them look into it.
Seconding smulube's suggestion to monitor the serial output. Additionally, eliminate the variable of the COSM code & Ethernet: start debugging the issue with a sketch that is just taking readings from the DHT11 and monitor what's going on in the Arduino's serial output on your computer (in the Tools dropdown menu).
I just received my DHT22 (RHT03) from Sparkfun last night and tried several samples that wouldn't compile (my fault, I'm sure). The sample that worked "out of the box" for me with my Arduino Uno came from Tom Boyd's page (be sure to scroll to the bottom for the most recent code): DHT11 / Aosong AM2302 humidity and temperature sensor
I'm curious: how long did it take for your sensor to flatline? I integrated the code from Tom with the Cosm code and it's been running without interruption for me for an hour now.
Cheers,
Reeves

Resources