Receiving multiple chars at once with Software Serial - bluetooth

I have a Arduino Uno R3 and a Bluetooth Mate.
When linking the Mate to the Arduino Hardware Serial (pin 0,1) I can send multiple characters at once from my connected device but when I try to make the same thing with Software Serial (using pin 4,2 for example) I only get the first character and the rest of the chars are messed up.
My code:
#include <SoftwareSerial.h>  
int bluetoothTx = 4;  
int bluetoothRx = 2;  
SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
void setup()
{
 Serial.begin(115200);  
 bluetooth.begin(115200);  
}
void loop()
{
 if(bluetooth.available())
 {
   Serial.print((char)bluetooth.read());  
 }
}
For example if I send this chars: abcd from my android device I get this in the serial monitor: a±,ö
This code that uses Hardware Serial (I link my bluetooth to pins 0 and 1) works just fine:
void setup()
{
 Serial.begin(115200);  
}
void loop()
{
 if(Serial.available())
 {
   Serial.print((char)Serial.read());  
 }
}
I even tried changing the baud rate but it didn't helped
If I send the chars one by one it works fine but I would like to be able to send them as a string.

You could try to bufferize the string before printing it.
Look at the following answer: Convert serial.read() into a useable string using Arduino?

As pointed out by #hyperflexed in the comments this is a baudrate related issue.
I had to take the baudrate as low as 9600 to make it work.
This is the code that worked:
#include "SoftwareSerial.h";
int bluetoothTx = 4;
int bluetoothRx = 2;
SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
void setup()
{
Serial.begin(9600);
delay(500);
bluetooth.begin(115200);
delay(500);
bluetooth.print("$$$");
delay(500);
bluetooth.println("U,9600,N");
delay(500);
bluetooth.begin(9600);
}
void loop()
{
if(bluetooth.available()) {
char toSend = (char)bluetooth.read();
Serial.print(toSend);
}
if(Serial.available()) {
char toSend = (char)Serial.read();
bluetooth.print(toSend);
}
}
For changing the baudrate I had to put some big delays to make sure the commands are executed otherwise it won't work.

Related

Arduino to PC secure bluetooth connection(cryptography)

I'm using an Arduino Uno to build a smoke detection system, which works. Since I have to do an IoT project, I have to establish a secure connection with a device (I thought with my smartphone, or my PC), and I'm using a Bluetooth module HC-05 to do it. The idea is:
Send the smoke sensor data to Arduino IDE, encrypt them and display the encrypted data to the serial (and it works)
Connect Arduino to my smartphone using HC-05 and the app "Makerslab BT Demo" (already done)
Decrypt the value of the sensor when I press "1" on the app and display it;
Decrypt the value of the sensor when there's danger and display a "danger message".
(that's what I have to do now).
That's my code on Arduino IDE:
#include <AES.h>
#include <AESLib.h>
#include <AES_config.h>
#include <xbase64.h>
#include <SoftwareSerial.h>
SoftwareSerial BT(1,0);
#define VCC2 5
int smokeA0 = A0;
int buzzer = 11;
AES aes;
byte cipher[400];
char b64[400];
float sensorValue;
//char a;
void do_encrypt(String msg, String key_str, String iv_str){
byte iv[16];
memcpy(iv,(byte*)iv_str.c_str(),16);
int blen=base64_encode(b64,(char*)msg.c_str(),msg.length());
aes.calc_size_n_pad(blen);
int len=aes.get_size(); //zero padding
byte plain_p[len];
for(int i=0;i<blen;++i) plain_p[i]=b64[i];
for(int i=blen;i<len;++i) plain_p[i]='\0';
// l'AES-128-CBC encryption
int blocks = len/16;
aes.set_key((byte *)key_str.c_str(), 16);
aes.cbc_encrypt(plain_p, cipher, blocks, iv);
// use base64 encoder to encode the encrypted data:
base64_encode(b64,(char *)cipher,len);
Serial.println(String((char *)b64));
}
void setup() {
pinMode(buzzer, OUTPUT);
pinMode(smokeA0, INPUT);
pinMode(VCC2, OUTPUT);
digitalWrite(VCC2, HIGH);
BT.begin(9600);
BT.println(F("Hi! Press "1" to know the sensor value."));
Serial.begin(115200);
Serial.println(F("gas sensor is warming up!"));
delay(2000); //allow the sensor to warm up
noTone(buzzer);
}
void loop() {
String key_str="aaaaaaaaaaaaaaaa"; //16 bytes
String iv_str="aaaaaaaaaaaaaaaa"; //16 bytes
sensorValue = analogRead(smokeA0);
String msg = String(sensorValue, 3);
do_encrypt(msg,key_str,iv_str);
/* if(BT.available()){
a=(BT.read());
if(a=='1'){
Serial.print(F("Air quality: "));
}
}*/
if(sensorValue > 300){
Serial.print(F(" | Danger!"));
BT.print(F(" | Danger!"));
tone(buzzer,1000,2000);
}
else {
noTone(buzzer);
}
Serial.println(F(""));
delay(2000);
}
I'm not sure to use the right security protocol (AES), but encryption works. How I can decrypt data?

How to send float values from one bluetooth module to other(HC 05)

I am doing a project where I need to send data from ultrasonic sensor wirelessly present in one arduino to other arduino where I need these values in Serial monitor. But the problem is I cannot able to send these values through bluetooth. I tried to send one character, it is appearing in serial monitor.. But when I tried to the same for integer values it is not appearing in serial monitor.
I have configured Master and Slave modes for the Bluetooth. I have uploaded the image of the code which I am using to send these values. Please help me on this. Thanks in advance .
code
//# transmitting end
#define trigPin 12
#define echoPin 11
void setup() {
Serial.begin(38400); // Default communication rate of the Bluetooth module
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
long duration;
float distance;
digitalWrite(trigPin, LOW); // Added this line
delayMicroseconds(2); // Added this line
digitalWrite(trigPin, HIGH);
delayMicroseconds(10); // Added this line
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
Serial.println(distance,2); // Sends floatValue
delay(500);
}
//# receving end
#include <SoftwareSerial.h>
#define led 13
SoftwareSerial BTSerial(10, 11);
int data=0;
void setup() {
pinMode(led,OUTPUT);
Serial.begin(38400);
BTSerial.begin(38400); // Default communication rate of the Bluetooth module
}
void loop() {
int number;
if(Serial.available() > 0){ // Checks data is from the serial port
data = BTSerial.read(); // Reads the data from the serial port
//analogWrite(led,data);
delay(10);
//Serial.println(data);
}
Serial.println(data);
}
I need integer values at the serial monitor. But there I am getting some symbols like ?/<>..
From the Arduino reference, Serial.read() only reads the first available byte available in the Serial buffer. As an int is coded on 8 bytes, I would say that you need to read the incoming bytes sequentially in order to get the full value.
Maybe you can implement this by putting (Serial.available() > 0) in a while loop, concatenate the values you get in a char[8] for instance and then convert this char to a integer value.
Also, beware that you are sending floats and not int.
Thanks for the help..!
I modified the code in the receiver end to get the float values from the transmitter.. Here is my modified code
#include <SoftwareSerial.h>
int bluetoothTx = 10;
int bluetoothRx = 11;
String content; //content buffer to concatenate characters
char character; //To store single character
SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
void setup(){
bluetooth.begin(38400);
Serial.begin(9600);
}
void loop(){
bluetooth();
}
void bluetooth(){ //
while(bluetooth.available()){
character = bluetooth.read();
content.concat(character);
if(character == '\r'){ // find if there is carriage return
Serial.print(content); //display content (Use baud rate 9600)
content = ""; //clear buffer
Serial.println();
}
}
}

Bluetooth module HC-06 is not responding to any AT command on Arduino

Arduino Uno R3, HC-06. There's no response to the AT commands on the serial monitor.
I want to establish Bluetooth communication between PC and Arduino. At first I had to change the baud rate from 9600 to 115200, and the AT+BAUD8 command was working well. But after that change AT commands are not working. I cannot see any respond on the serial monitor.
#include <SoftwareSerial.h>
SoftwareSerial BTSerial(2, 3); // Bluetooth module Tx:Digital 2 Rx:Digital 3
void setup() {
Serial.begin(9600);
BTSerial.begin(9600);
Serial.println("ATcommand"); //ATcommand Start
}
void loop() {
if (BTSerial.available())
Serial.write(BTSerial.read());
if (Serial.available())
BTSerial.write(Serial.read());
}
I used the above simple code and also I've already checked the Tx, Rx pins.
What I want to do in the end is Bluetooth communication with a PC as a master and an Arduino as a slave.
Is it possible to upload code to Arduino through Bluetooth?
This code works for me:
#include <SoftwareSerial.h>
SoftwareSerial BT(10,11); // TX to pin_10. RX to pin_11 of Arduino.
void setup() {
Serial.begin(9600);
BT.begin(9600);
}
void loop() {
if(Serial.available()) {
String command = Serial.readStringUntil('\n');
Serial.println(command);
BT.print(command);
}
if (BT.available()){
String retorno = BT.readStringUntil('\n');
Serial.println(retorno);
}
}
Serial Monitor with New line.
AT
AT+VERSION
AT+NAMEmy_blue
AT+BAUDx

How to receive 2-byte decimal number from Bluetooth to arduino

I can send 1byte decimal number (0-256) easily over arduino, but I couldn't make it for 2 byte number.
the code below here I used for sending data between 0-256, this is works great.
#include <SoftwareSerial.h>
#include <Servo.h>
Servo myservo;
int bluetoothTx = 10;
int bluetoothRx = 11;
SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
void setup()
{
myservo.attach(9);
//Setup usb serial connection to computer
Serial.begin(9600);
//Setup Bluetooth serial connection to android
bluetooth.begin(9600);
}
void loop()
{
//Read from bluetooth and write to usb serial
if(bluetooth.available()> 0 )
{
int servopos = bluetooth.read();
Serial.println(servopos);
myservo.write(servopos);
}
}
I tried to program for 2 byte number , but I couldn't make it successfully , MSB and LSB data are not shifting properly . any help regarding this code will be much help for me go ahead .
#include <SoftwareSerial.h>
#include <Servo.h>
Servo myservo;
int bluetoothTx = 7;
int bluetoothRx = 8;
SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
void setup()
{
myservo.attach(9);
//Setup usb serial connection to computer
Serial.begin(9600);
//Setup Bluetooth serial connection to android
bluetooth.begin(9600);
}
void loop()
{
//Read from bluetooth and write to usb serial
if(bluetooth.available()>= 2 )
{
int servopos = bluetooth.read() << 8;
servopos |= bluetooth.read();
Serial.println(servopos);
myservo.write(servopos);
}
}

How to use BLE Shield based on HM-10 bluetooth module?

I'm a new bie on arduino projects. I would like to ask you for some help. I bought a BLE Shield for Arduino from ( http://imall.iteadstudio.com/development-platform/arduino/shields/im130704001.html ). They made this shield using Hm-10 Bluetooth module(http://www.jnhuamao.cn/bluetooth.asp?ID=1). Itead Studio has no sample codes using this shield. I have no idea on how to program it or send AT commands from Arduino.
I read the “AT commands” at the data sheet (ftp://imall.iteadstudio.com/Shield/IM130704001_ITEAD_BLE_Shield/DS_IM130704001_ITEAD_BLE_Shield.pdf) and I tried to send "AT commands” from arduino to BLE shield using this code ( http://arduino.cc/en/Reference/SoftwareSerial ) but I only received the commands back.
Did anybody here ever use this HM-10 bluetooth module ?
I need some arduino sketch for help !
#include <SoftwareSerial.h>
int led = 13;
int bluetoothTx = 2;
int bluetoothRx = 3;
SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
int baudrate[8] ={4800,9600,14400,19200,28800,38400,57600,115200};
int i = 1;
void setup() {
Serial.begin(9600);
bluetooth.begin(9600);
while(!Serial){}
Serial.write("AT sent");
delay(500);
bluetooth.write("AT+NAME?");
delay(500);
while (bluetooth.available()) {
Serial.write(bluetooth.read());
}
delay(100);
Serial.println("");
bluetooth.write("AT+POWE3");
delay(500);
while(bluetooth.available())
{
Serial.write(bluetooth.read());
}
delay(100);
Serial.println("");
delay(500);
bluetooth.write("AT+CHAR?");
delay(500);
while (bluetooth.available()) {
Serial.write(bluetooth.read());
}
delay(100);
Serial.println("");
delay(500);
bluetooth.write("AT+NAMEFlightline"); //Check Status
delay(500);
while (bluetooth.available()) {
Serial.write((char)bluetooth.read());
}
Serial.println("");
bluetooth.write("AT+CHAR0x2901"); //add charicteristic
delay(500);
while (bluetooth.available()) {
Serial.write(bluetooth.read());
}
Serial.println("");
bluetooth.write("AT+RELI0");
delay(500);
while (bluetooth.available()) {
Serial.write(bluetooth.read());
}
Serial.println("");
bluetooth.write("AT+SHOW1");
delay(100);
while (bluetooth.available()) {
Serial.write(bluetooth.read());
}
Serial.println("");
pinMode(led,OUTPUT);
digitalWrite(led,HIGH);
}
void testAllBaudRates(){
for(int j=0; j<8; j++)
{
bluetooth.begin(baudrate[j]);
delay(100);
Serial.println("boud rate " + String(baudrate[j],DEC) +" i-> "+String(j,DEC));
// Serial.println("");
bluetooth.write("AT");
delay(500);
while (bluetooth.available()) {
Serial.write(bluetooth.read());
Serial.println();
}
delay(100);
}
}
// and now a few blinks of the LED,
// so that we know the program is running
void loop()
{
//Read from bluetooth and write to usb serial
while(bluetooth.available())
{
char toSend = (char)bluetooth.read();
if(toSend == 'x'){
digitalWrite(led,HIGH);
Serial.println("set high");
bluetooth.write("RXOK");
}else if(toSend == 'y'){
digitalWrite(led,LOW);
Serial.println("set low");
bluetooth.write("RXOK");
}
Serial.print(toSend);
}
//Read from usb serial to bluetooth
while(Serial.available())
{
char toSend = (char)Serial.read();
bluetooth.write(toSend);
Serial.print(toSend);
}
}
Have a look at my sketch above I have a few things to point out that I wasted time on.
make sure you have the line
while(!Serial){}
Or you may get have a working shield but miss the responses as the serial monitor is no ready.
remember that you wont get a response from the blue-tooth module, with a command from the Serial Monitor if it is connected to a device. It is connected to the device when the light stops flashing.
if you run this sketch you should get this output
AT sent
OK+Set:3
OK+Get:0x2901 <- this may be blank the first time you run it
OK+Set:Flightline
OK+Set:0x2901
OK+Set:0
OK+Set:1
the most comprehensive list of AT commands can be found here
[All the AT commands and a good explanation][1]
You will need to at Characteristics to the device as I have done here
bluetooth.write("AT+CHAR?");
or you will find it to connect to iOS and Android
If you are connecting to Android use the BluetoothLE Classes not Bluetooth ones.
You can use this sketch with baud rate autodetect to control your HM-10. This is a part of Apploader project that allows to upload to Arduino board over BLE.
This is a little late too, but try the following code, if you send it "AT" it should give you back an "OK":
#include <SoftwareSerial.h>
int bluetoothTx = 2; // TX-O pin of bluetooth mate, Arduino D2
int bluetoothRx = 3; // RX-I pin of bluetooth mate, Arduino D3
SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
void setup()
{
Serial.begin(9600); // Begin the serial monitor at 9600bps
bluetooth.begin(115200); // The Bluetooth Mate defaults to 115200bps
delay(100); // Short delay, wait for the Mate to send back CMD
bluetooth.println("U,9600,N"); // Temporarily Change the baudrate to 9600, no parity
// 115200 can be too fast at times for NewSoftSerial to relay the data reliably
bluetooth.begin(9600); // Start bluetooth serial at 9600
}
void loop()
{
if(bluetooth.available()) // If the bluetooth sent any characters
{
// Send any characters the bluetooth prints to the serial monitor
Serial.print((char)bluetooth.read());
}
if(Serial.available()) // If stuff was typed in the serial monitor
{
// Send any characters the Serial monitor prints to the bluetooth
bluetooth.print((char)Serial.read());
}
// and loop forever and ever!
}

Resources