how to clear the junk characters in arduino output serial window? I need to send and receive characters using software serial [duplicate] - c++

This question already has answers here:
How should character arrays be used as strings?
(4 answers)
Closed 3 years ago.
I have used software serial for serial communication, below are the sender's and receiver's code which sends and receives 3 characters. The characters received has extra junk characters. I need assistance to remove those junk characters. Along with sending and receiving i have section of code which receives acknowledgement after successfully sending the characters. Kindly assist
************ SENDER CODE **************
#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 3); // RX, TX(Receiver and transmitter)
char mystr_0[4] = "CAT"; //serial message to be communicated
char txt_msg[3]; //Initialized buffer/array to store received acknowledgement
#define SIZE_OF_RCV (sizeof(txt_msg))
void setup() {
Serial.begin(9600);
// Begin the Serial at 1000 Baud or data transfer rate
mySerial.begin(1000);
}
void loop() {
mySerial.write(mystr_0, 4); //Write the serial data
delay(1000);
if(mySerial.available() == 3)
{
for(int i = 0; i < SIZE_OF_RCV; ++i){
char rcv = mySerial.read(); // to read the received char by char
txt_msg[i] = rcv;
//digitalWrite(13, HIGH); // configuring LED for confirmation
}
Serial.println(txt_msg); // printing it on serial monitor to check the message
}
}
************ RECEIVER'S CODE **************
#include <SoftwareSerial.h>
SoftwareSerial mySerial_1(2, 3); // RX, TX
char mystr[3]; //Initialized buffer/array to store received data
char data[3];
#define SIZE_OF_PACKET (sizeof(mystr))
void setup() {
Serial.begin(9600); // Begin the Serial at 9600 Baud
mySerial_1.begin(1000); // Input signal (message) rate at 1000
}
void loop() {
int j;
// Serial.println(SIZE_OF_PACKET);
if (mySerial_1.available() > 0)
{
char b = mySerial_1.read();
if (b == 'C')
{
mystr[0] = b;
}
char c = mySerial_1.read();
if(c == 'A'){
mystr[1] = c;
}
char d = mySerial_1.read();
if(d == 'T'){
mystr[2] = d;
}
//Serial.println(mystr);
}
if(sizeof(mystr) == 3)
{
char msg_check[4] = "YES"; // message confirming that data is transferred successfully.
//Serial.println(msg_check);
Serial.println(mystr);
mySerial_1.write(msg_check, 4); // writing the acknowledged message
}
}
Serial port output
12:56:46.846 -> CAT
12:56:46.879 -> CAT
12:56:46.914 ->
12:56:46.914 -> CAT
12:56:46.948 -> CAT
12:56:47.017 -> CAT#
12:56:47.052 -> CAT+

I am not sure if this causes your bug, but it is definitely wrong
if(sizeof(mystr) == 3)
iirc sizeof(mystr) is determined at compile time, meaning that sizeof(mystr) is ever 3.
So that if statement is actually saying
if(3 == 3)

Related

Serial.write(5) not able to send decimal?

I am trying, as a test to Serial.write the int value: 5, to serial monitor, and if received, i want to print the the text "SUCCESS!" to the serial monitor.
But when writing Serial.write((int)5); All i get in the serial monitor is:
I have tried using Serial.println(5); which works fine, but then i am not able to read it.
My code:
enum read_states {
Modtag_Adresse,
Modtag_Bit_Position_I_Adresse,
Modtag_Bit_Position_Vaerdi
};
enum read_states state;
void setup() {
state = Modtag_Adresse;
Serial.begin(9600);
}
void loop() {
if(state == Modtag_Adresse) {
Serial.write((int)5);
delay(1000);
if(Serial.available() > 0) {
int serialReceived = Serial.read();
if(serialReceived >= 0) {
// Receive value 5
Serial.print("SUCCESS!!");
}
}
}
else if(state == Modtag_Bit_Position_I_Adresse) {
//
}
else if(state == Modtag_Bit_Position_Vaerdi) {
//
}
else {
// Failure.
}
}
Serial.write(5) sends the byte 5 to the computer. It appears as a square, because it's not an ASCII code of a letter or number or symbol.
Serial.print(5) sends the ASCII code for 5 (which is 53).
The reason you can't read what you wrote is because Serial.write sends data to the computer and Serial.read returns data received from the computer. If it read data from the Arduino program, it would be pointless because you don't need to use serial for that.

SDI12 library doesn't display measurements with + or - sign in it

Arduino library source: https://github.com/joranbeasley/SDISerial
The problem I'm having is when I'm trying to get the measurement from sensor using SDI12 I only receive first digit which is channel number of the device.
This is how it should work:
Master: 1M! (Measure)
Sonde: 10617[CR][LF] (ch1, 061s to measure,7 sensors).
Sonde: 1[CR][LF] (Measurement ready)
Master: 1D0! (Send data)
Sonde: 1+17.5+12.05+98.7+8.25+6.45[CR][LF]
Master: 1D1! (Send rest of the data)
Sonde: 1-325+10[CR][LF]
The only thing I'm receiving after 1D0! command is "1". I think that it must be because of the + - operator in the measurement data device sends (1+17.5+12.05+98.7+8.25+6.45). I've tried to understand the library code (.cpp and .h), but had no luck with solving this problem. Any thoughts on how this could be fixed?
Arduino code:
#define DATALINE_PIN 2
#define INVERTED 1
#define MAX_TIMEOUT 1000
//see: http://arduino.cc/en/Reference/attachInterrupt
//for pins that support interupts (2 or 3 typically)
SDISerial connection(DATALINE_PIN, INVERTED);
char b_in[125];
char output_buffer[255];
char tmp_buffer[10];
void wait_for_message(char* buffer,char terminal){
Serial.println("Waiting For input...");
int i=0;
while( true){
if(!Serial.available())delay(500);
else{
buffer[i] = Serial.read();
if(buffer[i] == terminal){
buffer[i+1] = '\0';
return;
}
i+=(buffer[i] >= 32 && buffer[i] <= 127);
}
}
}
void setup(){
Serial.begin(9600);
connection.begin();
delay(1000);
Serial.println("Initialization Complete");
}
void loop(){
wait_for_message(b_in,'!');
sprintf(output_buffer,"[out]:%s",b_in?b_in:"No Output");
Serial.println(output_buffer);
char *response =connection.sdi_query(b_in,MAX_TIMEOUT);
//sprintf(output_buffer,"[in]:%s",response?response:"No Response");
Serial.println(response);
Serial.flush();
delay(1000);
}

Incoming values to serial port are sometime corrupted or missing

I have written simple bluetooth transmitter and receiver on two arduino nano v3 boards. Bluetooth modules are HM-10 connected into hardware serial ports. It works, but on receiver side I often receive corrupted values and many values are missing. Where is a problem:
I am beginner in arduino. If it is possible a need to explain deeply. Thanks.
Transmitter code:
const long waitingInterval = 20000;
unsigned long lastSend = micros();
void setup()
{
Serial.begin(19200);
Serial.println("Started");
}
bool delay() {
if(micros() >= lastSend + waitingInterval) {
lastSend = micros();
return true;
}
return false;
}
void loop()
{
if(delay()) {
String mil = String(millis());
String sendingText = mil + ";" + mil + ";" + mil + ".";
Serial.println(sendingText);
}
}
Output of transmitter serial monitor interface:
10548;10548;10548.
10568;10568;10568.
10589;10589;10589.
10609;10609;10609.
10629;10629;10629.
10649;10649;10649.
10670;10670;10670.
10690;10690;10690.
10711;10711;10711.
10730;10730;10730.
10750;10750;10750.
10771;10771;10771.
10791;10791;10791.
10812;10812;10812.
10831;10831;10831.
10852;10852;10852.
10872;10872;10872.
10893;10893;10893.
10913;10913;10913.
10933;10933;10933.
10953;10953;10953.
10974;10974;10974.
10994;10994;10994.
11014;11014;11014.
11034;11034;11034.
11055;11055;11055.
11075;11075;11075.
11096;11096;11096.
11115;11115;11115.
Receiver code:
void setup() {
Serial.begin(19200);
Serial.println("Started");
}
void loop() {
if(Serial.available()) {
String incomingData = String();
char incomingChar = Serial.read();
if(incomingChar == '.') {
incomingData = bufferString;
Serial.print(bufferString);
bufferString = String();
} else {
bufferString += String(incomingChar);
return;
}
}
Output of receiver serial monitor interface:
10548;10548;10548
10568;10568;10568
10589;10589;10589
10609;10609;10609
10629;10629;10629
106410771
10791;10791;10791
10812;10812;10812
10831;10831;10831
10852;10852;10852
10872;10872;10872
10893;10893;11034;11034;11034
11055;11055;11055
11075;11075;11075
11096;11096;11096
11115;11115;11115
One problem is simply calling Serial.available() simply returns the number of bytes available to be read in the buffer; it could be exactly the number of bytes you need, it could be less, or more. Because of this, you might read extra data, too little, or too much data. More so, in higher level transmission protocols sometimes after a device receives data it will send an ACK(acknowledgement) back to the sender, saying it is ready for more data.
Edit** It should also be noted that the comment talking about mutex's isn't correct. Mutexes are typically used to synchronize code across multiple threads of execution on the same device. The key is that they are a shared resource across the thread's heap space. This is NOT the case when using two different arduino devices; thus, even if you could use them, it would be useless.
For your code, I would suggest the following edits to the transmitter:
#define MIN_TIMEOUT 3
void recieveAck(){
bool validAck = false;
uint8_t timeout_cnt = 0x00;
while(timeout_cnt < MIN_TIMEOUT){
//Wait for receiving device to respond with two bytes then send next
char incomingBytes[2];
Serial.readBytes(incomingBytes, 0x02);
if(incomingBytes[0] == 0xBB && incomingBytes[1] == 0xCC)
break;
timeout_cnt++;
}
}
void loop()
{
if(delay()) {
String mil = String(millis());
String sendingText = mil + ";" + mil + ";" + mil + ".";
Serial.println(sendingText);
recieveAck();
}
}
And to the receiver:
#define NEXT_INC_SIZE 2 //Expects one byte at a time
void sendAck(){
char outData[2];
outData[0] = 0xBB;
outData[1] = 0xCC;
Serial.write(outData, 2); //Write the ack data
}
void loop() {
if(Serial.available() >= NEXT_INC_SIZE){
char incomingBytes[2];
Serial.readByte(incomingBytes, NEXT_INC_SIZE); //Read exactly how many bytes you need
//Do stuff with the data here....
sendAck();
}
}

Arduino XBee sending data API

I want to send data from an end device to a coordinator with XBee and Arduino. But, the Arduino reboots when sending data (sending data was aborted). What could the problem be?
/* Transmit */
#include <SoftwareSerial.h>
#include <XBee.h>
int end = 1;
int alim_XbeeRS = A7;
int RX_XBee = 14;
int TX_XBee = 15;
XBee xbee = XBee();
//Allume le périphérique
void powerOn(SoftwareSerial portcom)
{
portcom.begin(57600);
digitalWrite(alim_XbeeRS, HIGH);
}
void setup ()
{
SoftwareSerial XbeeRS(RX_XBee,TX_XBee);
Serial.begin(57600);
XbeeRS.begin(57600);
pinMode(RX_XBee, INPUT); // Rx
pinMode(TX_XBee, OUTPUT); // Tx
pinMode(alim_XbeeRS, OUTPUT);
powerOn(XbeeRS);
xbee.setSerial(XbeeRS);
delay(5000);
Serial.println("XBee OP");
}
void loop()
{
if (end == 1)
{
Serial.println("sending");
ZBTxRequest _zbTx;
uint8_t payload[] = {'Y','E','S','\0'};
XBeeAddress64 address = XBeeAddress64 (0x13A200,0x4081B77C );
_zbTx = ZBTxRequest(address, payload, sizeof(payload));
Serial.println("sending");
xbee.send(_zbTx); // The program blocks here
}
else
{
Serial.println("waiting");
xbee.readPacket(100);
if (xbee.getResponse().isAvailable())
{
Serial.println("waiting 1");
if( xbee.getResponse().getApiId() == ZB_RX_RESPONSE)
{
Serial.println("waiting 2");
ZBRxResponse _rx;
xbee.getResponse().getZBRxResponse(_rx);
uint8_t* response= new uint8_t[50];
for(int i=0; i<_rx.getDataLength(); i++)
{
response[i] = _rx.getData()[i];
Serial.println(char(response[i]));
}
}
}
}
}
EDIT (additional information):
It doesn't change anything if I change the value type in the payload. About the baud rate, both of XBees are configured to 57600 baud. Here is the XBee's configuration:
ENDEVICE
COORDINATOR
The result from the serial port of this device is:
Finally, I use the Arduino ATmega 1284P. I really have no idea what kind of problem could do this.
There is some trouble :/
First, the default coordinator ADD is 0x0 0x0, so the line where
XBeeAddress64 address = XBeeAddress64 (0x13A200,0x4081B77C );
should be
XBeeAddress64 address = XBeeAddress64 (0x0,0x0 );
Then, is the Xbee at 57600 baud too?
To get an ACK, you can use:
if (xbee.readPacket(1000))
{
if (xbee.getResponse().getApiId() == ZB_TX_STATUS_RESPONSE)
{
xbee.getResponse().getZBTxStatusResponse(txStatus);
if (txStatus.getDeliveryStatus() == SUCCESS)
{
//It's sent
}
}
It could be from you payload too. You better use a hexadecimal value or int to be sure of what you send.
EDIT:
I see you don't use the last version of Xctu. Try it and test the direct communication between them to see if you can have direct contact between Coordinator and Routeur/End device.

interfacing c++ to control motor stepper with arduino

I have tried to control motor stepper via arduino uno board with slider in visual C++.
but the servo didnot move at all.
here the program at PC side:
void CENVSConfigDlg::OnBnClickedButton1()
{
SetTimer(cTimer1,80,NULL);
}
void CENVSConfigDlg::OnTimer(UINT_PTR ID)
{
if(ID==cTimer1){
DWORD nbytes;
char buf[5];
sprintf(buf, "%d \n", val_test);
/* Open serial port. */
if(!WriteFile( hnd_serial, (void*)buf, 5, &nbytes, NULL )){MessageBox(L"Write Com Port fail!");return;}
}
and the program in arduino:
#include <Servo.h>
Servo servoMain;
int index=0;
String inputString;
void setup()
{
Serial.begin(9600);
servoMain.attach(9);
}
void loop()
{
int data;
while (Serial.available())
{
char inChar = (char)Serial.read();
if (inChar == '\n' || inChar == 'z')
{
data=stringToInt(inputString);
Serial.println(data); //
inputString="";
servoMain.write(data); //tambahannya
delay(50);
break;
}
if (inChar != 0)
{
inputString += inChar;
}
}
}
int stringToInt(String s)
{
char char_string[s.length()+1];
s.toCharArray(char_string, s.length()+1);
return atoi(char_string);
}
the pc i think is sending the data, but why the motor didnot working? any idea?
First off, does the serial link work at all? The number of ways that an RS232 link can not work, for both hardware and software reasons, is legendary. Unless you can show that the hardware can transfer data, it's pointless to look at your dedicated software. If you have a scope, use that to see if anything is being transmitted and then check that it arrives at the correct pin on the arduino input. If you have no access to a scope, a small LED and a 4.7K resistor can be used to indicate that there is data on the line - it will flicker with the data.