Sending Strings from arduino to Processing - string

I want to get Processing to read Strings from Arduino.
I send two Strings massages from the arduino and I want to store them in two different variables on Processing.
I tried to do it, but the two Strings are passed to the first variable and the second variable remains empty. I don't understand why this is the case. Can someone help?
Regards
Arduino Code
void setup() {
Serial.begin(9600);
delay(1000);
Serial.println("1.first message");
Serial.println("2.second message");
delay(100);
}
void loop() {
}
Processing Code
import processing.serial.*;
Serial myPort;
void setup() {
myPort=new Serial(this, "COM3", 9600);
}
void draw() {
String s1=myPort.readStringUntil('\n');
String s2=myPort.readStringUntil('\n');
// printing variables
if(s1!=null){
print("s1:",s1);
}
if(s2!=null){
println("s2:",s2);
}
}

The following works on my Mac system. The incoming strings are placed in a string array as they arrive. The string at index[0] then becomes s1 and the string at index[1] is s2. I also added a delay(100); between the two strings on the Arduino side, but this may not be necessary; you can try it both ways.
import processing.serial.*;
Serial myPort;
String[] s; // Array to hold two strings.
int counter = 0;
void setup() {
printArray(Serial.list()); // List of serial ports
// Enter appropriate number for your system
myPort = new Serial(this, Serial.list()[2], 9600);
s = new String[2];
println("===========");
}
void draw() {
String str = myPort.readStringUntil('\n');
if(str != null) {
s[counter] = str;
if(counter == 0){
println("s1 = ",s[0]);
} else {
println("s2 = ",s[1]);
}
counter++;
}
}

Related

Serial Data Read and parse to variables from continuous string (Arduino)

I have 2 Arduino and 2 xbee. I send 2 sensor data from Arduino 1 (router) to Arduino to (coordinator):
On coordinator, I receive wireless data from this 2 sensors(from router) perfectly.
The data stream is something like this:
20.1324325452924 divided in: -first sensor(temperature): 20.1324325452 -second sensor(gas):924
My goal is to have these 2 values as 2 variables that get updated constantly and then pass these values on to the rest of the program to make something like print on LCD or something else:
temperature=20.1324325452 gas=924
I managed to divide that initial string that I receive on serial (20.1324325452924) in 2 variables but values from this 2 variables not updating like in the initial string (when sensor values are changed):
My code:
LiquidCrystal lcd(12,11,10,9,8,7);
String temperature;
String gas;
String readString;
char IncomingData[13];
void setup() {
Serial.begin(9600);
}
void loop() {
while (Serial.available() > 0)
{
char IncomingData = Serial.read();
readString += IncomingData ;
temperature = readString.substring(0, 13); //get the first 13 characters
gas = readString.substring(13, 16); //get the last 3 characters
Serial.print(IncomingData); //here I have my string: 20.1324325452924 which is updating properly when I have sensor values changes
// Process message when new line character is DatePrimite
if (IncomingData == '\n')
{
Serial.println(temperature);
lcd.begin(16, 2);
lcd.setCursor(0,0);
lcd.write("T:");
lcd.print(temperature);
delay(500);
temperature = ""; // Clear DatePrimite buffer
Serial.println(gaz);
lcd.begin(16, 2);
lcd.setCursor(0,1);
lcd.write("G:");
lcd.print(gas);
delay(500);
gaz = ""; // Clear DatePrimite buffer
}
}
}
Output from serial: 20.1324325452924
20.1324325452 924
First string it's updating when I receive new sensor data but the next 2 remains the same every time. I'm stuck for days I don't know to do this work. All I need to do is to divide the initial string which contains the data from 2 sensors in 2 variables that get updated constantly and then pass these values on to the rest of the program to make something like print on LCD.
Does anyone have any idea how to make this work?
Split the data after you receive the complete string.
void loop() {
while(!Serial.available()); // wait till data to be filled in serial buffer
String incommingStr = Serial.readStringUntil('\n'); // read the complete string
String temperature = incommingStr.substring(0, 13);
String gas = incommingStr.substring(13, 16);
Serial.print(incommingStr);
Serial.println(temperature);
Serial.println(gas);
lcd.setCursor(0,0);
lcd.print(temperature);
lcd.setCursor(0,1);
lcd.print(gas);
delay(500);
}
You only need to call lcd.begin() once. Calling it from the setup() function.
you have to modify the program like this: (do an action on readString in loop)
// Process message when new line character is DatePrimite
if (IncomingData == '\n')
{
Serial.println(temperature);
lcd.begin(16, 2);
lcd.setCursor(0,0);
lcd.write("T:");
lcd.print(temperature);
delay(500);
temperature = ""; // Clear DatePrimite buffer
Serial.println(gaz);
lcd.begin(16, 2);
lcd.setCursor(0,1);
lcd.write("G:");
lcd.print(gas);
delay(500);
gaz = ""; // Clear DatePrimite buffer
readString = ""; //clear either you concatenate at each loop!!*******
}

display bytes greater than 0x7f

I'd like to connect my program to a serial port & to show the received data from the serial port. I successfully did that, but I have a problem.
I'd like to convert the string shown in the window into a stream of bits
I followed How could I get the bits from a string in c#?
& my problem is what to do to show a byte like 0xAA, it's greater than 7f the maximum value of the ascii characters
I'm developing a program using C# language, I'd like to connect it to a serial port & to show the received data from the serial port,I successfully did that, but I have a problem, I'd like to convert the string shown in the window into a stream of bits I followed How could I get the bits from a string in C#?
& my problem is what to do to show a byte like 0xAA, it's greater than 7f the maximum value of the ASCII characters
public partial class mm_dig_ctrl : Form
{
public mm_dig_ctrl()
{
InitializeComponent();
if (!MySerP.IsOpen)
{
MySerP.Open();
TB_Port_Status.Text = "Port is Opened";
}
else
{
TB_Port_Status.Text = "Port is Busy";
}
MySerP.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(DataReceivedHandler);
}
public delegate void AddDataDelegate(String rxstring);
public AddDataDelegate myDelegate;
private void mm_dig_ctrl_Load(object sender, EventArgs e)
{
this.myDelegate = new AddDataDelegate(AddDataMethod);
}
public void AddDataMethod(String myString)
{
TBRX_Read.AppendText(myString);
}
private void DataReceivedHandler(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
String rxstring,to_show;
rxstring = MySerP.ReadExisting();
to_show = GetBits(rxstring);
TBRX_Read.Invoke(this.myDelegate, new object[] { to_show });
//TBRX_Read.Text += rxstring;
}
public string GetBits(string input)
{
StringBuilder sb = new StringBuilder();
foreach (byte b in input)
{
sb.Append(Convert.ToString(b, 16));
}
return sb.ToString();
}
'

Sending strings over Serial to Arduino

I'm currently experimenting with sending a string to my Arduino Yun and trying to get it to reply back depending on what I send it.
I picked up a framework of some code here and have been experimenting with it but apart from the serial monitor displaying 'ready' I can't make it go any further.
The code is:
//declace a String to hold what we're inputting
String incomingString;
void setup() {
//initialise Serial communication on 9600 baud
Serial.begin(9600);
while(!Serial);
//delay(4000);
Serial.println("Ready!");
// The incoming String built up one byte at a time.
incomingString = "";
}
void loop () {
// Check if there's incoming serial data.
if (Serial.available() > 0) {
// Read a byte from the serial buffer.
char incomingByte = (char)Serial.read();
incomingString += incomingByte;
// Checks for null termination of the string.
if (incomingByte == '\0') {
// ...do something with String...
if(incomingString == "hello") {
Serial.println("Hello World!");
}
incomingString = "";
}
}
}
Can anyone point me in the right direction?
Thanks
I suspect the problem is that you're adding the null terminator onto the end of your string when you do: incomingString += incomingByte. When you're working with string objects (as opposed to raw char * strings) you don't need to do that. The object will take care of termination on its own.
The result is that your if condition is effectively doing this: if ("hello\0" == "hello") .... Obviously they're not equal, so the condition always fails.
I believe the solution is just to make sure you don't append the byte if it's null.
Try This:
String IncomingData = "";
String Temp = "";
char = var;
void setup()
{
Serial.begin(9600);
//you dont have to use it but if you want
// if(Serial)
{
Serial.println("Ready");
}
//or
while(!Serial)
{delay(5);}
Serial.println("Ready");
void loop()
{
while(Serial.available())
{
var = Serial.read();
Temp = String(var);
IncomingData+= Temp;
//or
IncomingData.concat(Temp);
// you can try
IncomindData += String(var);
}
Serial.println(IncomingData);
IncomingData = "";
}

Speech recognition using SetInputToWaveFile ends prematurely

I want to do speech recognition of an audio file.
My code is pretty basic and derived from here. The problem is that it stops with every wave file prematurely after a few seconds even though some wave files are hours long.
How to make it scan the whole file?
namespace Stimmenerkennung
{
public partial class Form1 : Form
{
//...
Thread erkennung;
bool completed;
private void Form1_Load(object sender, EventArgs e)
{
erkennung = new Thread(erkennen);
erkennung.Start();
}
void erkennen()
{
using (SpeechRecognitionEngine recognizer =
new SpeechRecognitionEngine())
{
// Create and load a grammar.
Grammar dictation = new DictationGrammar();
dictation.Name = "Dictation Grammar";
recognizer.LoadGrammar(dictation);
// Configure the input to the recognizer.
recognizer.SetInputToWaveFile(#"REC01.wav");
// Attach event handlers for the results of recognition.
recognizer.SpeechRecognized +=
new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
recognizer.RecognizeCompleted +=
new EventHandler<RecognizeCompletedEventArgs>(recognizer_RecognizeCompleted);
// Perform recognition on the entire file.
db("Starting asynchronous recognition...");
recognizer.RecognizeAsync();
while (!completed)
{
//fs((int)(100 / recognizer.AudioPosition.TotalSeconds * recognizer.AudioPosition.Seconds));
db(recognizer.AudioState.ToString());
Thread.Sleep(100);
}
}
}
// Handle the SpeechRecognized event.
void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
if (e.Result != null && e.Result.Text != null)
{
db(e.Result.Text);
}
else
{
db(" Recognized text not available.");
}
}
// Handle the RecognizeCompleted event.
void recognizer_RecognizeCompleted(object sender, RecognizeCompletedEventArgs e)
{
if (e.Cancelled)
{
db(" Operation cancelled.");
}
if (e.InputStreamEnded)
{
db(" End of stream encountered.");
}
completed = true;
}
void db(string t)
{
this.textBox1.Invoke((MethodInvoker)delegate
{
textBox1.Text = textBox1.Text + Environment.NewLine + t;
//textBox1.Text = t;
});
}
}
}
You can split the file on few seconds chunks by the silences and feed the chunk to the recognizer separately. Then you can combine results into a single string.
You can use any voice activity detection implementation to perform the split, a simple energy-based VAD which calculate frame energy will be sufficient.
You can find some existing implementations of the VAD in CMUSphinx projet

How to grab value from a thread?

Hi i am trying to grab a value from my threading but it seem work not so find to me course i found that my code structure are unstable enough..here is my code i name my thread class as "clsThreadCount" and below is my implementation
public volatile bool Grab = false;
public volatile int count = 0;
public void Initialization(int i)
{
count = i;
}
public void Play()
{
Grab = false;
_shouldStop = false;
ThreadTest();
}
public void Stop()
{
_shouldStop = true;
workerThread.Join(1);
workerThread.Abort();
}
private void ThreadTest()
{
workerThread = new Thread(DoWork);
workerThread.Start();
while (!workerThread.IsAlive) ;
}
private void DoWork()
{
try
{
while (!_shouldStop)
{
if (Grab)
{
count++;
Grab = false;
}
}
}
catch (Exception)
{
Play();
}
finally
{
}
}
when my program(main menu) are starting to run i will trigger the initialize function at pass the parameter as 7
ObjThreadCount.Initialization(7); // count = 7
ObjThreadCount.Play(); // the thread are running
ObjThreadCount.Grab = true; // the grab equal to true, count++ are trigger
Thread.Sleep(100); // wait awhile
lblResult.Text = ObjThreadCount.count.ToString(); // sometime i can get count++ result (e.g. 8)
ObjThreadCount.Stop(); // thread stop
sometime my program can able to get a right counting from the thread but sometime are not.
i realize at my while loop implementation there are something are missing..
something like waitone or waitautoevent..can i ignore Thread.Sleep(100) ?? what are the suitable code should i add in the while loop ?
Please help me~ :S
** sorry in the first upload i forgot to write down "volatile" into the variable
thank you..
If C# (and C and java, and probably C++), you need to declare _shouldStop and Grab as volatile.

Resources