Arduino serial.available strange error - c++

I am trying to read data from an Arduino serial port. My current code:
if(Serial.available()>0){
if(Serial.available()==9){...}
When I type 9 characters in the serial monitor it works fine.
So when I add a second if in the
if(Serial.available()>0)
after the
if(Serial.available()==9){}
it recognizes each character as a single reading. For example when i type 4 characters it says Serial.available()=1 4 times.
real code:
if(Serial.available() > 0){
if(Serial.available()==9){
for(int i =0;i<9;i++){
RGB[i]=Serial.read() - '0';
}
//get the data from the integer array
R= RGB[0]*100+RGB[1]*10+RGB[2];
G= RGB[3]*100+RGB[4]*10+RGB[5];
B= RGB[6]*100+RGB[7]*10+RGB[8];
for(int q=0; q<=255; q++){
if(R>Rp){
Rp+=1;
analogWrite(8, Rp);
}else if(R<Rp){
Rp-=1;
analogWrite(8, Rp);
}
if(G>Gp){
Gp+=1;
analogWrite(9, Gp);
}else if(G<Gp){
Gp-=1;
analogWrite(9, Gp);
}
if(B>Bp){
Bp+=1;
analogWrite(10, Bp);
}else if(B<Bp){
Bp-=1;
analogWrite(10, Bp);
}
delay(10);
}
}
// if(Serial.read()=='r'){
// if(readinglstate==0){
// analogWrite(readinglight, 5);
// readinglstate=1;
// }else if(readinglstate==1){
// analogWrite(readinglight, 70);
// readinglstate=2;
// }else if(readinglstate==2){
// analogWrite(readinglight, 255);
// readinglstate=3;
// }else if(readinglstate==3){
// analogWrite(readinglight, 0);
// readinglstate=0;
// }
// }
}
The commented code is the one that changes the things...

The
Serial.read()=='r'
is popping the byte off the receive buffer. Think of it more like...
input = Serial.read(); // pop the next byte off, regardless of its value.
if (input == 'r') {
hence all your bytes in the buffer are read off the buffer. until "Serial.available() == 0"
I recommend the peek function.
if(Serial.peek()=='r'){
Serial.read(); // already know it, so pop it.
if(readinglstate==0){
...

Input data can arrive in several chunks, so you need to slightly rework approach to read data, please check the following code for reference:
int bytesToRead = 0;
int currBytePtr = 0;
int RGB[9];
while (9 > currBytePtr) { // we need 9 bytes of data
if (0 < (bytesToRead = Serial.available())) { // have something to read
for (int i = 0; i < bytesToRead; ++i ) {
RGB[currBytePtr++] = Serial.read();
if (9 == currBytePtr) { // we have enough data
break;
}
}
} else {
delay(1000); // sleep a bit
}
} // while
// process data received
...

why not just read the data till you have 9 bytes then process.
char buffer[10];
int index=0;
while (Serial.available()){
buffer[index++]=Serial.read();
if (index>8) {
ProcessData(buffer);
index=0;
}
}

Related

Difficulty in reading values from an array

I am writing a C++ code and I am struggling with something rather simple:
I have declared an array
uint8_t *received_data as global variable in my code.
Then I allocate its memory inside a function:
void advertisementCallback(const Gap::AdvertisementCallbackParams_t *params) {
if(params->type == 3){
for(int i = 0; i < params->advertisingDataLen; i++){
if(params->advertisingData[i] == 0x16){
if(params->advertisingData[i+1] == 0x34 && params->advertisingData[i+2] == 0x23){
received_data_size = params->advertisingDataLen - (i + 3);
received_data = new uint8_t[received_data_size];
for(int index = i+3; index < params->advertisingDataLen; index++){
received_data[index] = params->advertisingData[index];
//printf("%02x ", received_data[index]);//params->advertisingData[index]);
//printf("\r\n");
}
}
}
}
}
}
Note that the commented printf's are printing the data I receive correctly.
But then in my main when I try the same printf I receive garbage most of the times and some times I receive the last three elements of the array in the first three places and then garbage.
My main is:
int main(void)
{
BLE& ble = BLE::Instance(BLE::DEFAULT_INSTANCE);
ble.init(bleInitComplete);
bool state = true;
while(true){
ble.waitForEvent();
measurement[2]++;
printf("In the loop \n");
for(int i = 0; i < received_data_size; i++){
printf("%02x ", received_data[i]);//params->advertisingData[index]);
printf("\r\n");
}
delete[] received_data;
}
}
The whole code as of now is:
#include "mbed.h"
#include "ble/BLE.h"
/* Optional: Device Name, add for human read-ability */
const static char DEVICE_NAME[] = "G4";
uint16_t uuid16_list[] = {0x2334};
/* You have up to 26 bytes of advertising data to use. */
const static uint8_t AdvData[] = {0x01,0x02,0x03,0x04,0x05}; /* Example of hex data */
uint8_t meas = 0;
uint8_t received_data_size;
static uint8_t *received_data;
uint8_t measurement[] = {0x34,0x23, meas};
/* Optional: Restart advertising when peer disconnects */
void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *params)
{
BLE::Instance().gap().startAdvertising();
}
/**
* This function is called when the ble initialization process has failed
*/
void onBleInitError(BLE &ble, ble_error_t error)
{
/* Avoid compiler warnings */
(void) ble;
(void) error;
/* Initialization error handling should go here */
}
void advertisementCallback(const Gap::AdvertisementCallbackParams_t *params) {
if(params->type == 3){
for(int i = 0; i < params->advertisingDataLen; i++){
if(params->advertisingData[i] == 0x16){
if(params->advertisingData[i+1] == 0x34 && params->advertisingData[i+2] == 0x23){
received_data_size = params->advertisingDataLen - (i + 3);
received_data = new uint8_t[received_data_size];
for(int index = i+3; index < params->advertisingDataLen; index++){
received_data[index] = params->advertisingData[index];
//printf("%02x ", received_data[index]);//params->advertisingData[index]);
//printf("\r\n");
}
}
}
}
}
}
/**
* Callback triggered when the ble initialization process has finished
*/
void bleInitComplete(BLE::InitializationCompleteCallbackContext *params)
{
BLE& ble = params->ble;
ble_error_t error = params->error;
if (error != BLE_ERROR_NONE) {
/* In case of error, forward the error handling to onBleInitError */
onBleInitError(ble, error);
return;
}
/* Ensure that it is the default instance of BLE */
if(ble.getInstanceID() != BLE::DEFAULT_INSTANCE) {
return;
}
/* Set device name characteristic data */
ble.gap().setDeviceName((const uint8_t *) DEVICE_NAME);
/* Optional: add callback for disconnection */
ble.gap().onDisconnection(disconnectionCallback);
/* Sacrifice 3B of 31B to Advertising Flags */
ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE );
ble.gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
/* Sacrifice 2B of 31B to AdvType overhead, rest goes to AdvData array you define */
//ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::MANUFACTURER_SPECIFIC_DATA, AdvData, sizeof(AdvData));
ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::SERVICE_DATA, measurement, sizeof(measurement));
ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, (uint8_t *)uuid16_list, sizeof(uuid16_list));
/* Optional: Add name to device */
ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME));
/* Set advertising interval. Longer interval == longer battery life */
ble.gap().setAdvertisingInterval(500); /* 100ms */
/* Start advertising */
//ble.gap().startAdvertising();
/*Start Scanning*/
ble.gap().setScanParams(500 /* scan interval */, 200 /* scan window */);
ble.gap().startScan(advertisementCallback);
}
int main(void)
{
BLE& ble = BLE::Instance(BLE::DEFAULT_INSTANCE);
ble.init(bleInitComplete);
bool state = true;
while(true){
ble.waitForEvent();
measurement[2]++;
printf("In the loop \n");
for(int i = 0; i < received_data_size; i++){
printf("%02x ", received_data[i]);//params->advertisingData[index]);
printf("\r\n");
}
delete[] received_data;
}
}
BLE stands for bluetooth low energy. The code is based on examples found at mbed.org
I guess I am missing something, but I am not sure what exactly. Thank you very much for your help.
First of all, without taking a further look at the rest of the code, the first three bytes of your global received_data will never be written. Take a look into this particular part of your advertisementCallback():
for(int index = i+3; index < params->advertisingDataLen; index++){
received_data[index] = params->advertisingData[index];
So the index used for writing to received_data always starts at an offset of 3 - never less - , while it should start at 0. Add a dedicated index variable for this purpose. In your main(), you created a loop starting at 0:
for(int i = 0; i < received_data_size; i++){
printf("%02x ", received_data[i]);
Therefore the first three bytes of your debug output will always contain random data.

Arduino hanging when data sent via bluetooth serial

Below is the code being used by Arduino to extract two integers at a time, from formatted text in the serial. The format being two numbers. each followed by a comma, eg 51,7, After reading in the ints, it is supposed to do stuff with them, then loop back and go again, unless there is no data, then it is supposed to skip past the if and do stuff using the current int values.
void setup() {
Serial.begin(9600);
}
char rx_byte = 0;
String rx_str[2] = {""};
int nums[2] = {0}, a;
int PIN = 13;
boolean not_read = true;
void loop() {
if (Serial.available() > 0) { // is a character available?
memset(nums, 0, sizeof(nums));
rx_str[0] = "";
rx_str[1] = "";
a = 0;
while( a < 2 ){
not_read = true;
while(not_read){
rx_byte = Serial.read(); // get the character
if ((rx_byte >= '0') && (rx_byte <= '9')) {
rx_str[a] += rx_byte;
} // if ((rx_byte >= '0') && (rx_byte <= '9'))
else if (rx_byte == ',') {
not_read = false;
a++;
} // else if (rx_byte == ',')
} // while(not_read)
} // while(int a < 2)
nums[0] = rx_str[0].toInt();
nums[1] = rx_str[1].toInt();
} // if (Serial.available() > 0)
// do stuff with ints
} // void loop
This turnout works fine when the Arduino is plugged into the usb and the right data is entered into the serial monitor. The problem is, when the data is written by another program in c, using bluetooth with an HC-05-1 module, when there is no data, arduino hangs at the if statement waiting for serial input, instead of skipping past and doing stuff. Below is the C++ code for writing the data.
void right( double times[3] ) {
nums[0] = (int) times[0];
nums[1] = (int) times[1];
int bytes_written = 0; // bytes_read = 0;
printf( "\n nums[0]: %d ", nums[0]);
printf( "\n nums[1]: %d ", nums[1]);
sprintf( buf, "%d,%d,", nums[0],nums[1] );
printf( "\n writing ");
puts(buf);
bytes_written = write(s, buf, sizeof(buf));
printf("\n %d Bytes written to bluetooth", bytes_written);
printf("\n +----------------------------------+\n\n");
}
And this is sample output from function right()
nums[0]: 4
nums[1]: 2
writing 4,2,
15 Bytes written to bluetooth
+----------------------------------+
I dont kmow how relevant this is but here some output from function right() when the bluetooth and board are not powered up.
nums[0]: 16
nums[1]: 5
writing 16,5,
16,5,
15 Bytes written to bluetooth
+----------------------------------+
Not sure where that extra line of output comes from. Last week it used to output 0 Bytes written to bluetooth without the extra line, but changes have been made since then.
Edit....
Patrick Trentin's diagnosis was right.
sprintf( buf, "%d,%d,", nums[0],nums[1] );
needed to be changed to
int str_len = sprintf( buf, "%d,%d,", nums[0],nums[1] );
and
bytes_written = write(s, buf, sizeof(buf));
needed to be changed to
bytes_written = write(s, buf, str_len);
It was a bit disappointing how long the read process took, so some pretty serious optimization is needed, but it does seem to do what was intended... eventually.

how can I display/save the value of what return an AT command

Good day all!
I am working on a project with Arduino UNO and a SIM908.
I am trying to understand the AT command.
When I enter
Serial.print("AT")
Serial.println("AT+CGPSSTATUS?");
Serial retuen a value and I would like to save that value into a buffer
char buffer[size]
I do not want to have other string than the return value of an AT command.
I also red that document
SIM908 AT Command Manual_V1.01
At the page 13, you can read (NB. < CR>< LF> : I added a space after the first <, other there are not display)
The "AT" or "at" prefix must be set at the beginning of each Command
line. To terminate a Command line enter < CR>. Commands are usually
followed by a response that includes. "< CR>< LF>< CR>< LF>"
Throughout this document, only the responses are presented, < CR>< LF>
are omitted intentionally
Then, I am asking how I can "extract" the response between < CR>< LF> and < CR>< LF>
Looking at this exemple (let me know if I am wrong), how can I detect the < CR>< LF>
void setup()
{
char buffer[200];
Serial.println("AT+CGPSSTATUS?");
}
void loop()
{
if (Serial.available())
{
// HERE I SHOULD CHECK IF CR ANF LF
Serial.write(Serial.read());
// AND SAVE IT IN buffer. IS'T NOT?
}
}
}
Do you see what I means?
How could you help me to store in a buffer, only the return value of an AT command?
Many thank for your help
It's very interresting what you show me. Here is how I adapt my code
I adapted my code and by the way I created a file for testing Serail while we send a AT command.
The concern function are loop() and read_AT_string(). (I renamed the read_String to read_AT_string().
Here my code and I explain, after the issue, regardin your proposal
#include <SoftwareSerial.h>
int baud_rate = 9600;
int pin_gsm = 3;
int pin_gps = 4;
int pin_power = 5;
//int pin_dtr = 6;
boolean debug = true;
boolean raedy_to_go = false;
// Reading String
#define BUFFERSIZE 200
char buffer[BUFFERSIZE];
char inChar;
int index;
void setup()
{
Serial.begin(baud_rate);
delay(5000); // Wait for 5sec after begin
if(debug)
{
Serial.println(F("\n****************************"));
Serial.println(F("STARTING SYSTEM Read AT stream"));
Serial.println(F("******************************"));
}
pinMode(pin_gsm,OUTPUT); // Set the pins
pinMode(pin_gps,OUTPUT);
pinMode(pin_power,OUTPUT);
powerUpSim908:
if(powerUpSim908())
{
delay(1000);
if(gps_power()){
gsm_enable();
raedy_to_go = true;
if(debug)
{
Serial.println(F("\n****************************"));
Serial.println(F("READY TO GO\n"));
Serial.println(F("****************************\n"));
}
}
else
{
raedy_to_go = false;
if(debug)
{
Serial.println(F("\nNOT READY TO GO.\nGPS could not be power\nRestart the module\nor/and check the battery level.\n"));
}
goto powerUpSim908;
}
}
else
{
raedy_to_go = false;
if(debug)
{
Serial.println(F("\nNOT READY TO GO.\nCheck the battery level.\n"));
}
};
}
void loop()
{
/*
if (Serial.available())
{
Serial.print("Character received: ");
Serial.write(Serial.read());
Serial.println("");
}
*/
if(raedy_to_go)
{
read_AT_string("AT",5000);
delay(10000);
}
}
char read_AT_string(char* command, int timeout)
{
unsigned long previous;
previous = millis();
Serial.println(F("\nDISPLAY BUFFER:"));
index=0;
Serial.println(command);
do
{
if(Serial.available() > 0) // Don't read unless
// there you know there is data
{
Serial.println("1");
if (Serial.peek() == 13) // check if CR (without reading)
{
Serial.println("13");
if(Serial.available() > 0)
{
Serial.read(); // read and ignore
if (Serial.peek()==10) // then check if LF (without reading)
{
Serial.println("10");
if(index < Serial.readBytesUntil(13, buffer, BUFFERSIZE-1)) // One less than the size of the buffer array
{
Serial.println("b");
inChar = Serial.read(); // Read a character
buffer[index] = inChar; // Store it
index++; // Increment where to write next
buffer[index] = '\0'; // Null terminate the string
}
}
}
}
}
}while(((millis() - previous) < timeout));
Serial.println(buffer);
buffer[0]='\0';
Serial.println(F("END DISPLAY BUFFER"));
}
/* FUNCTION */
boolean powerUpSim908(void)
{
if(debug)
{
Serial.println(F("Powering up SIM908"));
}
boolean turnedON = false;
//uint8_t answer=0;
int cont;
for (cont=0; cont<3; cont++)
{
digitalWrite(pin_power,HIGH);
delay(1500);
digitalWrite(pin_power,LOW);
Serial.println(F("Checking if the module is up"));
if(sendATcommand("AT", "OK", 5000))
{
cont = 4; // Leave the loop
turnedON = true;
}
else
{
turnedON = false;
if(debug)
{
Serial.println(F("\nTrying agin to turn on SIM908"));
}
};
}
if(turnedON)
{
if(debug)
{
Serial.println(F("Module is tunrned up\n"));
}
}
else
{
if(debug)
{
Serial.println(F("Module is NOT tunrned ON\n"));
}
}
return turnedON;
}
boolean sendATcommand(char* ATcommand, char* expected_answer, unsigned int timeout)
{
uint8_t x=0;
bool answer=false;
//åchar response[100];
//buffer[0]='\0';
unsigned long previous;
//memset(response, '\0', 100); // Initialice the string
//Serial.println(response);
delay(100);
while( Serial.available() > 0) Serial.read(); // Clean the input buffer
if (ATcommand[0] != '\0')
{
Serial.println(ATcommand); // Send the AT command
}
x = 0;
previous = millis();
index=0;
do
{
if(Serial.available() > 0)
// there you know there is data
{
if(index < BUFFERSIZE-1) // One less than the size of the array // Same as buffer size
{
inChar = Serial.read(); // Read a character
buffer[index] = inChar; // Store it
index++; // Increment where to write next
//Serial.println(index);
buffer[index] = '\0'; // Null terminate the string
}
}
}while(((millis() - previous) < timeout));
if(strstr(buffer,"NORMAL POWER DOWN") != NULL)
{
answer = false;
}
else if (strstr(buffer, expected_answer) != NULL) // check if the desired answer (OK) is in the response of the module
{
/*
Serial.println(F("### BUFFER"));
Serial.println(buffer);
Serial.println(F("### END BUFFER"));
*/
answer = true;
}
else
{
answer = false;
}
if(debug)
{
if(answer)
{
//Serial.println(F("Expected answer : OK!\n"));
}
else
{
//Serial.println(F("Expected answer : KO!\n"));
};
}
return answer;
}
void gps_enable(void)
{
if(debug)
{
Serial.println(F("\nEnabling GPS ..."));
}
digitalWrite(pin_gps,LOW); //Enable GPS mode
digitalWrite(pin_gsm,HIGH); //Disable GSM mode
delay(2000);
}
void gsm_enable(void)
{
if(debug)
{
Serial.println(F("\nEnabling GSM ..."));
}
digitalWrite(pin_gsm,LOW); //Enable GSM mode
digitalWrite(pin_gps,HIGH); //Disable GPS mode
delay(2000);
}
/* UTILISTIES */
/* GPS */
boolean gps_power(void) //turn on GPS power supply
{
/*
Serial.println("AT");
delay(2000);
*/
boolean gpspwr = false;
boolean gpsrst = false;
if(sendATcommand("AT+CGPSPWR=1","OK",2000))
{
gpspwr = true;
if(debug)
{
Serial.println("turn on GPS power supply => OK");
}
}
else
{
if(debug)
{
Serial.println("turn on GPS power supply => KO");
}
};
//delay(1000);
if(sendATcommand("AT+CGPSRST=1","OK",2000))
{
gpsrst = true;
if(debug)
{
Serial.println("reset GPS in autonomy mode => OK");
}
}
else
{
if(debug)
{
Serial.println("reset GPS in autonomy mode => KO");
}
}; //reset GPS in autonomy mode
delay(1000);
if(gpspwr && gpsrst)
{
return true;
}else
{
return false;
}
}
At the read_AT_string, the first if(Serial.peek()==13) always return false.
1 is printed, but '13' is not, then I supposed
if(Serial.peek()==13)
return false
Here is what is printed within 5 sec
AT DISPLAY BUFFER:
1
1
1
1
1
1
1
1
1
[...] // It prints 1 until now
1
END DISPLAY BUFFER
Here a piece of code to detect and remove CR+LF (Attention: if A CR is read but it's not followed by a LF, it is removed as well):
if (Serial.peek()==13) { // check if CR (without reading)
Serial.read(); // read and ignore
if (Serial.peek()==10) // then check if LF (without reading)
Serial.read();
}
To read the rest of the response from Serial you could use:
buffer[Serial.readBytesUntil(13, buffer, 199)]=0; // readbytes returns the number of bytes read
You then have to discard the ending CRLF (same as above).
Edit
There are several issues with the code that you've posted in a separate answer.
When you powerUpSim908() you have to be aware that the gsm module may send unrequested data (see documentation, chapter 1.4):
Note: A HEX string such as "00 49 49 49 49 FF FF FF FF" will be sent
out through serial port at the baud rate of 115200 immediately after
SIM908 is powered on. The string shall be ignored since it is used for
synchronization with PC tool. Only enter AT Command through serial
port after SIM908 is powered on and Unsolicited Result Code "RDY" is
received from serial port.
This means that before you send anything, you have to discard this data by reading it. I guess this is why you don't get CRLF when reading the response: you first get the HEX string or "RDY".
Then readBytesUntil() reads as many bytes as available (maxi 199 in my example above), stores them in the buffer. It stops reading when it encounters the byte 13 (i.e.CR). There is no need to loop on an index. The function returns the number of chars that could be read, and it doesn't put an ending 0 at the end of the buffer (i.e. no valid C string). If you want to use the function in another way than what I proposed, you must store the length returned, because you have no other way to find it out later on.

Reading from Arduino Serial seems to be very unstable

I have the following simple code to read commands sent from the computer to an Arduino Mega board:
void get_command()
{
char received;
int index = 0;
while (Serial.available() > 0) {
if (index < BUFFER_SIZE -1) {
received = Serial.read();
if (received == '\n') {
buffer[index] = '\0';
parse_command(buffer);
} else {
buffer[index++] = received;
}
} else {
Serial.println('666'); // buffer overflow
}
}
}
The commands are like A123 B123 C123 D123\n
Basically a sequence of space separated instructions, were each instruction starts by a letter and follows by a number. A command ends with a "\n".
Reading this seems to be very unstable. Sometimes I get the command perfectly, sometimes I miss the first letter, sometimes a pair of them, sometimes it starts by the number,...
I am sending the commands through the serial monitor, set to newline.
Before having this code, I'd simply check for the size using Serial.available, then Id wait a second to fill the buffer, and then I'd copy the buffer to a char*. This worked flawlessly. I am doing now this loop waiting for a \n, which seems more elegant, but it is being very unstable.
Code works by simply adding a delay(100) after the first Serial.available()
This is the code:
void get_command()
{
char received;
if (Serial.available() > 0) {
delay(100); // let the buffer fill up
int index = 0;
while (Serial.available() > 0) {
if (index < BUFFER_SIZE -1) {
received = Serial.read();
if (received != '\n') {
buffer[index] = received;
index++;
} else {
buffer[index] = '\0';
parse_command(buffer);
}
} else {
Serial.println('666'); // buffer overflow
}
}
}
}

Convert buffer array into a useable string using Arduino?( for connecting processing)

for the previous code, the serial monitor will get the message is hexadecimal like"08000AE23BDB",but in Processing those data just show as "NaN".I think maybe only string can be got for processing? but" String buffer(buffer[count])" seems can`t work,how can I convert it?
following is the code of arduino:
#include <SoftwareSerial.h>
SoftwareSerial SoftSerial(2, 3);
unsigned char buffer[64]; // buffer array for data recieve over serial port
int count=0; // counter for buffer array
void setup()
{
SoftSerial.begin(9600); // the SoftSerial baud rate
Serial.begin(9600); // the Serial port of Arduino baud rate.
}
void loop()
{
if (SoftSerial.available()) // if date is comming from softwareserial port ==> data is comming from SoftSerial shield
{
while(SoftSerial.available()) // reading data into char array
{
buffer[count++]=SoftSerial.read(); // writing data into array
if(count == 64)break;
}
Serial.write(buffer,count); // if no data transmission ends, write buffer to hardware serial port
clearBufferArray(); // call clearBufferArray function to clear the storaged data from the array
count = 0; // set counter of while loop to zero
}
if (Serial.available()) // if data is available on hardwareserial port ==> data is comming from PC or notebook
{
SoftSerial.write(Serial.read()); // write it to the SoftSerial shield
}
}
void clearBufferArray() // function to clear buffer array
{
for (int i=0; i<count;i++){
{
buffer[i]=NULL;
}
} // clear all index of array with command NULL
}
and this is the getting massage part of Processing:
void serialEvent(Serial myPort) {
String inString = myPort.readStringUntil('\n');
if (inString != null) {
inString = trim(inString);
float[] data = float(split(inString, ","));
if (data.length >=1)
{
direction1 = data[0];
}
println("data");
println(data[0]);
}
}
Maybe this?
String inString = "08000AE23BDB ";
if (inString != null) {
inString = trim(inString);
String[] data = split(inString, ",");
if (data.length >=1)
{
//direction1 = data[0];
}
println(unhex(data[0]));
}