How do I build a string from individual characters over BLE HC-08? - arduino-uno

I am testing a BLE module (HC-08), which looks like a UART to the Arduino Uno.
This should be simple, but I have spent hours trying to build a string or char array from the response from commands sent over the software serial port.
first, here's the code:
#include <SoftwareSerial.h>
int data = 0;
SoftwareSerial Blue(10, 11); // RX, TX
void setup() {
Serial.begin(115200);
Blue.begin(9600);
Serial.println("BLE_Test started");
}
void loop() {
Blue.write("AT+VERSION?");
if (Blue.available()) {
data = Blue.read();
Serial.write(data);
}
delay(50);
}
And here's the output:
BLE_Test started
OK:SH-V1.251
OK:SH-V1.251
OK:SH-V1.251
OK:SH-V1.251
Each line ends with a CR-LF (13,10), so it looks fine on the screen.
So, here's my problem.
How can I build a string or char array out of the bytes coming from the BLE module? My goal is to make a function that simply sends a command string to the BLE module and return a string from the function. (Similar to Serial.readstring(), but SoftwareSerial has no readstring() property).
Like I said, it should be straightforward, but I am getting nowhere. Any tips would be appreciated.

it is readString with capital S and it is implemented in Stream which is a common base class for Serial implementations and SoftwareSerial and many other classes like LCD, EthernetClient, WiFiClient, ...

Doh!
That works, here's my working code:
//Send the command to the BLE module, returns with response in global inData
void getBlue(char* blueCmd) {
inData = "";
Blue.write(blueCmd);
delay(15);
while (Blue.available() > 0)
{
inData = Blue.readString();
}
}

Related

How do I pair an ESP32 and a HC-05 module?

I have tried a lot of times, but any solution doesn't work.
I'm using an ESP32 as a Control and HC-05 as an anthena for an Arduino UNO.
I make that the HC-05 could read every String it recieves, but I'm not able to link the ESP32 (DevKit v1) with it. This is my code. I tried using address or name, but none of them works, only return "Failed to connect". But I can find it.
#include "BluetoothSerial.h"
BluetoothSerial SerialBT;
String MACadd = "00:19:08:35:31:63"; // HC-05 Address: 19:8:353163 (Given by the HC-05)
uint8_t address[6] = {0x00, 0x19, 0x08, 0x35, 0x31, 0x63};
String name = "AUTO"; // The name I put, I can find this by my mobile phone
char *pin = "1234"; //<- standard pin would be provided by default
bool connected;
void setup()
{
Serial.begin(115200);
SerialBT.begin("ESP32_Control", true);
SerialBT.setPin(pin);
Serial.println("The device started in master mode, make sure remote BT device is on!");
connected = SerialBT.connect(name);
if(connected)
Serial.println("Connected Succesfully!");
else
while(!SerialBT.connected(10000))
Serial.println("Failed to connect. Make sure remote device is available and in range, then restart app.");
if (SerialBT.disconnect()) // disconnect() may take upto 10 secs max
Serial.println("Disconnected Succesfully!");
SerialBT.connect(); // this would reconnect to the name(will use address, if resolved) or address used with connect(name/address).
}
void loop()
{
if (Serial.available())
SerialBT.write(Serial.read());
if (SerialBT.available())
Serial.write(SerialBT.read());
delay(20);
}

Instant Veins 4.7-i1 Localization Time of Arrival

I am a masters student working on localization, using ranging (time of arrival between vehicle and RSU) and relative location (Using emulated Inertial Navigation System).
I have done an implementation of my kalman filter based localization logic on Matlab, now I would like to implement this on veins. I want only the RSU to send out a message comprising of its location and ID
1) I know that i can use
double Coord = mobility->getCurrentPosition().x;
double Coord = mobility->getCurrentPosition().y;
to the location of RSU(and my vehicle as well), I do not understand how I should assign these coordinates to the message. I cannot use sstream since I understand that the message are supposed to be of type const char *
Thanks for any input
Edit 1: So this is what my new code on RSU looks like:
#include "RsuScOne.h"
#include <sstream>
Define_Module(RsuScOne);
void RsuScOne::initialize(int stage) {
BaseWaveApplLayer::initialize(stage);
if (stage == 0) {
//Initializing members and pointers of your application goes here
//WaveShortMessage* wsm = new WaveShortMessage();
EV << "Initializing " << std::endl;
}
else if (stage == 1) {
//Initializing members that require initialized other modules goes here
}
}
void RsuScOne::finish() {
BaseWaveApplLayer::finish();
//statistics recording goes here
cancelEvent(sendWSAEvt);
}
void RsuScOne::onWSM(WaveShortMessage* wsm) {
//Your application has received a data message from another car or RSU
//code for handling the message goes here, see TraciDemo11p.cc for examples
populateWSM(wsm);
std::stringstream ss;
ss<<mobility->getCurrentPosition().x<<mobility->getCurrentPosition().y;
wsm->setWsmData(ss.str().c_str());
scheduleAt(simTime()+par("beaconInterval").doubleValue(), sendWSAEvt);
EV<<wsm;
}
void RsuScOne::handleSelfMsg(cMessage* msg) {
BaseWaveApplLayer::handleSelfMsg(msg);
}
But I realize that all that being done now is my RSU constantly sending a generic BSM, Why is this so?

Pulse sensor coding for Netduino Plus 2 gone wrong

I'm currently doing a project on Netduino Plus 2 using .net micro framework which requires me to code for a pulse sensor. I have tried finding codes for pulse sensor but to no avail. I tried using AnalogInput codes for pulse sensor but the output values seemed wrong (there was a constant high value despite no heartbeat placed near the sensor). Please advise!
Here are my current codes for the heartbeat sensor:
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.Netduino;
namespace heartrate
{
public class Program
{
public static void Main()
{
SecretLabs.NETMF.Hardware.AnalogInput rate =
new SecretLabs.NETMF.Hardware.AnalogInput(Pins.GPIO_PIN_A0);
int sensorvalue = 0;
while (true)
{
sensorvalue = rate.Read();
Debug.Print("" + sensorvalue);
Thread.Sleep(1000);
}
}
}
}
Here are the specs of the sensor, how it looks like and how it is connected.
http://www.elecrow.com/wiki/index.php?title=Pulse_Sensor
(This tutorial is for arduino, but I think the wiring is similar to that of Netduino)
Hard to tell without specs on your pulse device and how it is attached. For Analog input & output in my latest project (https://github.com/osstekz/cncBuddy) I use classes InputPort & OutputPort (Microsoft.SPOT.Hardware)
ex:
public NESControllerAdapter(Cpu.Pin pinClk, Cpu.Pin pinLatch, Cpu.Pin pinData1/*, Cpu.Pin pinData2 = Cpu.Pin.GPIO_NONE*/) {
// Binds to all pins
this._outpClk = new OutputPort(pinClk, false);
this._outpLatch = new OutputPort(pinLatch, false);
this._inpData1 = new InputPort(pinData1, false, Port.ResistorMode.Disabled);
//if (pinData2 != Cpu.Pin.GPIO_NONE) this._inpData2 = new InputPort(pinData2, false, Port.ResistorMode.Disabled);
}
...then like your rate.Read(); loop
public int ButtonPressed() {
// Locks all parms
this._PinTick(this._outpLatch);
// Reads plug state value
for (int i = 0; i < CncBuddyShared.iTOTALNESCONTROLLERBUTTONS; ++i) {
// Read the value, if true return this index as the first pressed button
if (this._inpData1.Read() == false) return i;
// Selects the next value
this._PinTick(this._outpClk);
}
return NESCONTROLLER_PRESSEDBUTTOM_NONE;
}

In Processing, using serial port, why is .equals not returning true?

I am using Processing to display data coming into the serial port.
I have simple string values coming into the serial port.
I have cut down all my code to this basic point of failure and I cannot understand why it fails. The if statement never evaluates to true. (I'm not trying to compare strings with = or == )
Please help if you know why this is happening :) I'd really appreciate an answer.
Ugh Alright then, since I don't have a reputation of 10, I won't post the helpful screenshot.
Here is the code that fails:
enter code here
import processing.serial.*;
Serial myPort;
String val; //Data recieved from the serial port
void setup() {
size(400,300);
String portName = Serial.list()[2]; //change the 0 to a 1 or 2 etc. to match your port //1 or 2 for USB on the Mac
myPort = new Serial(this, portName, 9600);
myPort.bufferUntil('\n');
}
void serialEvent (Serial myPort){
val = myPort.readStringUntil('\n');
print(val);
if(val != null){
if(val.equals("New sample set")){
print("yes\n");
} else {
print("not equal\n");
}
}
}
void draw() {
//The serialEvent controls the display
}
I have tried taking out the spaces and making it only one letter, but this did not help. I have tried using if(val.equals("New sample set")==true) but that didn't help either.
Alrighty, it only took a few hours but I have answered my own question :)
Yes, comparing strings must be done with .equals()
and
Yes, they must be trimmed so that all line feed characters are eliminated.
I was using trim incorrectly.
Simply saying myString.trim(); will not do.
this returns a string, so it needs to be placed somewhere; here's how:
myString=myString.trim();
I know, kind of obvious to the experienced coder, but I just couldn't see it. And I thought bufferUntil('\n') would only buffer the stuff before the \n... I guess not.
Hope the hours I spent in this silly little "boggle" can help someone else!
:)
Happy coding!!!
Successful processing code below:
import processing.serial.*;
Serial myPort;
String val; //Data recieved from the serial port
void setup() {
size(400,300);
String portName = Serial.list()[2]; //change the 0 to a 1 or 2 etc. to match your port //1 or 2 for USB on the Mac
myPort = new Serial(this, portName, 9600);
myPort.bufferUntil('\n');
}
void serialEvent (Serial myPort){
val = myPort.readStringUntil('\n');
print("After reading serial, val is "+val+".\n");
val=val.trim();
print("After trimming, val is "+val+".\n");
if(val != null){
print("After comparing to null, val is "+val+".\n");
if("N".equals(val)){
print("yes\n");
} else {
print(val+" is not equal to \"N\".\n");
}
}
}
void draw() {
//The serialEvent controls the display
}

Receiving SMS by Arduino GSM Shield and control the LED with the content of this SMS?

I am using Arduino GSM Shield receiving SMS from an Android app. And the content of this SMS will control a LED. If the content of this SMS is not "off", the LED will be on and the content will be printed in the serial monitor. But if it is "off", the LED will be off immediately. Besides, the LED will keep being on until the "off" message coming. For now, I used the code from the example of the software. But I cannot use the content of this SMS to control the status of LED. With the code below, the LED could not be turned on and the content could not be displayed on the monitor. I think it was because the sketch failed to get the whole content of this SMS. Could anybody tell me how to solve this problem? Thanks.
#include <GSM.h>
GSM gsmAccess;
GSM_SMS sms;
char senderNumber[20];
int led=13;
void setup()
{
Serial.begin(9600);
pinMode(led,OUTPUT);
digitalWrite(led,LOW);
while (!Serial) {
;
}
Serial.println("SMS Messages Receiver");
boolean notConnected = true;
while(notConnected)
{
if(gsmAccess.begin("6442")==GSM_READY)
notConnected = false;
else
{
Serial.println("Not connected");
delay(1000);
}
}
Serial.println("GSM initialized");
Serial.println("Waiting for messages");
}
void loop()
{
char c;
int val=0;
val=digitalRead(led);
if (val==HIGH){
digitalWrite(led,HIGH);
}
if (sms.available())
{
Serial.println("Message received from:");
sms.remoteNumber(senderNumber, 20);
Serial.println(senderNumber);
if(sms.peek()=='#')
{
Serial.println("Discarded SMS");
sms.flush();
}
while(c=sms.read())
if(c='off'){
digitalWrite(led,LOW);
}else{
digitalWrite(led,HIGH);
Serial.print(c);
}
Serial.println("\nEND OF MESSAGE");
sms.flush();
Serial.println("MESSAGE DELETED");
}
delay(1000);
}
With this line
if(c='off'){
you are setting the value of c to "off". I guess you want to compare the value of c to the string "off" instead. Use == instead of =.
Also, what happens if someone sends "OFF" instead of "off"......? you need to handle that case as well. Try converting the SMS to lower characters before you do the compare.

Resources