Software serial using ESP8266 - string

I am transmitting the CSV file saved on SD card using STM32F103 on UART line to ESP8266, The file reading and UART transmission snippet is as below.
While loop of the STM32f103 for read/transmit file.
Using the Software Serial code on ESP8266 code I can read the transmitted string from the STM32F103 and the actual length of the transmitted string is 59 but I am getting following output on the Serial monitor
ESP8266 serial monitor output
The code for Software is as follows
#include <SoftwareSerial.h>
#include <Arduino.h>
#include <stdio.h>
#include <string.h>
using namespace std;
SoftwareSerial s; //RX TX
String str= "";
String str_tx = "";
char char_array[60];
double buff[24];
int str_len = 0;
double val;
char* token;
//char* rest = char_array;
int i=0;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
s.begin(115200, SWSERIAL_8N1, 13, 15, false, 128); //115200, SWSERIAL_8N1, 13, 15, false, 512
pinMode(13, INPUT);
pinMode(15, OUTPUT);
Serial.println("in setup 1");
Serial.println("in setup 2");
Serial.println("in setup 3");
}
void loop() {
// put your main code here, to run repeatedly:2
while(s.available() >0)
{
char ch=s.read();
if(ch != '\n')
str.concat(ch);
if( ch =='\n' )
{
/*Serial.println("------------------------------------");
Serial.println(char_array);
Serial.println("------------------------------------");*/
Serial.println(str);
str_len = str.length();
Serial.println(str_len);
str.toCharArray(char_array, str_len);
Serial.println(char_array);
//strcpy(char_array, str.c_str());
memset(char_array, 0, sizeof(char_array));
str="";
//break;
}
/*
str = s.readStringUntil('\n');
Serial.println(str);
str_len = str.length();
Serial.println(str_len);
//Serial.println(str.c_str());
//strcpy(char_array, str.c_str());
//str.toCharArray(char_array, str_len);
//Serial.println(char_array);*/
}
}
I have used the above code for the reading but the length is showing different after the 1st string which goes around 125 and because of that first time its getting copied into char buffer but further its showing empty.
Would appreciate if anyone could throw some light on what's causing this issue and how to solve it, Thankyou!

Software serial does not work very well on ESP8266. Use lower bitrate. It may be helpful but does not completely solve the problem. I had the same problem using GSM modules.
I used the hardware serial (Serial pin 1 , 3) for this communication and used a software serial to print out the debug information. It make it really hard to work with; because the port is used for programming; you need to add 470R resistor to prevent any damage to your module. Every time you change the code, you need to connect the programmer, program the module then you need to remove the programmer so the board can communicate with your STM32. But using the hardware serial was very stable and solved my problem.

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?

Pm_Read() can't read VMPK input

I have this problem:
i want to create a midi synthesizer in C,linux. Since I don't have a USB midi keyboard, I thought about using a virtual midi divice like VMPK. I found this code in a book that also explained how to use the portmidi library:
#include <stdio.h>
#include <portmidi.h>
#include <porttime.h>
int main() {
int cnt,i,dev;
PmError retval;
const PmDeviceInfo *info;
PmEvent msg[32];
PortMidiStream *mstream;
Pm_Initialize();
cnt = Pm_CountDevices();
if(cnt) {
for(i=0; i < cnt; i++){
info = Pm_GetDeviceInfo(i);
if(info->input)
printf("%d: %s \n", i, info->name);
}
printf("choose device: ");
scanf("%d", &dev);
Pt_Start(1, NULL, NULL);
retval = Pm_OpenInput(&mstream, dev, NULL, 512L, NULL,NULL);
if(retval != pmNoError)
printf("error: %s \n", Pm_GetErrorText(retval));
else {
while(Pt_Time(NULL) < 60000){
if(Pm_Poll(mstream)) {
cnt = Pm_Read(mstream, msg, 32);
for(i=0; i<cnt; i++) {
printf("status:%d, byte1=%d, "
"byte2=%d, time=%.3f\n",
Pm_MessageStatus(msg[i].message),
Pm_MessageData1(msg[i].message),
Pm_MessageData2(msg[i].message),
msg[i].timestamp/1000.);
}
}
}
}
Pm_Close(mstream);
}
}
else printf("No MIDI devices found\n");
Pm_Terminate();
return 0;
}
In short, once the program connects with a MIDI input device, it listens for 60 all the messages that come from them, (Printing the status byte and the two data bytes, as a midi protocol)
When I launch VMPK, it appears that the program reveals VMPK as midi input, under the name "out"
Program output
I also checked the "JACK audio connection" program to verify that VMPK was revealed as a MIDI input device
JACK audio output
I don't understand why when I press a key from the VMPK keyboard, I don't receive any messages from the program ...
I tried to change the VMPK configuration, but I didn't get any changes.
VMPK configuration menu
Maybe I'm doing something wrong in the VMPK configuration.
Any help is welcome.
I thank you in advance for your availability
ok, I found the problem. As I said, I set VMPK badly. If you set it this way, you can detect MIDI inputs
This is the output of programm:

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();
}
}
}

Arduino Serial receives false data

I am working on a project in which I use a phone app that I built in order to use Google's Speech Recognizer, connect my phone with my Arduino via Bluetooth and then when I say a word it sends the word in order to display it in a LCD.
The phone App works great with no problems. The problem is in the Arduino code. When I say the word hello for example the Arduino receives ello. I know that it receives it because I also use the Serial monitor to display the data in my computer screen except the LCD. Then after Arduino receives the first chunk of data if I send a second word like world Arduino receives elloorld. So it not only misses again the first letter of the word but also the Serial Port is not empty it in the end of the loop.
I tried with data += c; instead of data.concat(c); and the difference is that the second word isn't elloorld and it is just orld
Here is my code:
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 9, 8, 7, 6, 5, 4, 3, 2);
char c;
String data = "";
void setup() {
lcd.begin(16, 2);
Serial.begin(9600);
}
void loop() {
lcd.clear(); //clean the lcd
lcd.home(); // set the cursor in the up left corner
while(Serial.available() > 0){
c = Serial.read();
data.concat(c);
}
if(data.length() > 0){
Serial.println(data);
}
lcd.print(data);
delay(3000);
data = "";
}
If in the end of the loop I try to clean the Serial Port with this code:
while(Serial.available() > 0){
Serial.read();
}
Then the arduino doesn't receive data at all.
Your code wakes up every 3000 ms, then processes everything that is pending in the Serial input buffer and falls asleep again.
If you remove that ugly String data and the ugly delay(3000) and the unnecessary while, you can try this simple loop:
unsigned long lastreceived;
void loop() {
if (Serial.available()) {
lcd.write(Serial.read());
lastreceived=millis();
}
if (millis() - lastreceived > 1000) {
// after one second of silence, prepare for a new message
lcd.clear();
lcd.home();
lastreceived=millis(); // don't clear too often
}
}

Unexpected String when using BlueMix's Node-RED editor and MQTT->Debug Node

I'm following this tutorial,
http://energia.nu/creating-an-iot-connected-sensor-with-energia-mqtt/
I see the pushed data, but the Node-RED editor constantly prints 'Hello World #XX'. I don't see anything in the code that would suggest where its coming from:
#include <WiFi.h>
#include <PubSubClient.h>
#include <SPI.h> //only required if using an MCU LaunchPad + CC3100 BoosterPack. Not needed for CC3200 LaunchPad
WiFiClient wclient;
byte server[] = { 198, 41, 30, 241 }; // Public MQTT Brokers: http://mqtt.org/wiki/doku.php/public_brokers
byte ip[] = { 172, 16, 0, 100 };
char sensorRead[4];
#define WIFI_SSID "SSID"
#define WIFI_PWD "WIFIPASSWORD"
PubSubClient client(server, 1883, callback, wclient);
void callback(char* inTopic, byte* payload, unsigned int length){
// Handle callback here
}
void setup()
{
//Initialize serial and wait for port to open:
Serial.begin(115200);
Serial.println("Start WiFi");
WiFi.begin(WIFI_SSID, WIFI_PWD);
while(WiFi.localIP() == INADDR_NONE) {
Serial.print(".");
delay(300);
}
Serial.println("");
printWifiStatus();
}
void loop()
{
// read the input on analog pin:
int sensorValue = analogRead(24);
Serial.println(sensorValue);
// convert into to char array
String str = (String)sensorValue;
int str_len = str.length() + 1; // Length (with one extra character for the null terminator)
char char_array[str_len]; // Prepare the character array (the buffer)
str.toCharArray(char_array, str_len); // Copy it over
// publish data to MQTT broker
if (client.connect("LaunchPadClient")) {
client.publish("outTopic", char_array);
//client.subscribe("inTopic");
Serial.println("Publishing successful!");
client.disconnect();
}
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
}
Is this because this is a free/trial account? Incidentally, it shows I'm using 512MB/2GB, which seems high... does it include the data sent, or is 512MB just the application size?
You are using a MQTT broker that is public to the world, anybody can publish data to any topic on that broker. The messages are probably coming from somebody else doing similar experiments to yourself.
outTopic is the sort of topic name that many people could be using to test, try changing it to some random string in both the publishing code and the MQTT In node in Node-RED.
As for the size in Bluemix, this is how much memory is assigned to your application, it is unlikely to be actually using anything near that amount at the moment.

Resources