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

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.

Related

Arduino serial monitor lagging and cant get it to work

I wrote this program to check some things m but for me it is not working
` #define outputA 7
#define outputB 3
int counter = 0;
int aState;
int aLastState;
int StateAreTheSamePrinted = 0;
int StatePrinted = 0;
void setup() {
// put your setup code here, to run once:
pinMode(outputA, INPUT);
pinMode(3, INPUT);
Serial.begin(115200);
aLastState = digitalRead(outputA);
Serial.print("Arduino started");
}
void loop() {
// put your main code here, to run repeatedly:
aState = digitalRead(outputA);
if(StatePrinted == 0)
{
Serial.print(aState);
StatePrinted = 1;
}
if(aState == aLastState && StateAreTheSamePrinted == 0)
{
Serial.print("States are the same");
StateAreTheSamePrinted = 1;
}
if(aState != aLastState)
{
if(aState == 1){
Serial.print("A is high \n");
}
else
{
Serial.print("A is low \n");
}
StateAreTheSamePrinted = 0;
StatePrinted = 0;
}
aLastState = aState;
}
It always prints once arduino started, 1 (state of input), and states are the same, when I wire 5v from arduino into port 7, sometimes it react once, sometimes n ot, after few minutes it start priting output like 50-100 lines of messages and stops and lags again. Does anyone got into this problem?
`
I was expecting that after giving power into arduino 7 port it would print A is high or A is low and toggle between them
Sounds like you need to "debounce" after the state changes. When you hook 5v into the pin, it might not make a stable connection right away so it changes state very quickly a few times. A simple fix is to put a ~10ms delay after it detects a state change.

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

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)

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

How to make an arduino serial loop (receive numbers continuously)

New to coding! I am trying to get text on my LED Matrix through serial data that is being sent in from processing.
My code works but the only problem is that though the serial data on processing is constant, the arduino code only reads the number once. This makes it so that the text will not scroll all the way through. How do I loop a serial read on arduino?
Here is the relevant portion of my code:
void loop()
{
if (Serial.available() > 0)
{
int matrixPinState = Serial.read();
// stage = Serial.read();
// analogWrite(matrixPin, stage);
if (matrixPinState == 1)
{
matrix.fillScreen(0);
matrix.setCursor(x, 0);
matrix.print(F("Im kind"));
if (--x < -30)
{
x = matrix.width();
if (++pass >= 8) pass = 0;
matrix.setTextColor(colors[pass]);
}
matrix.show();
delay(30);
}
}
}
When a byte(or you call it character, a data that is 8 bit long) is fetched by uart block(the hardware), it is buffered to input buffer so that programmer can read and process it.
In your case, when you send a character, it is fetched and put to the buffer and when you read it there is no more byte available to read unless you send to new one.
In short, read the pin state once. You can do something like:
int matrixPinState = 0
void setup() {
// do all your setup settings first
while (Serial.available() < 0) {
// wait here for the input
delay(30);
}
// got your input, read it
matrixPinState = Serial.read();
}
void loop()
{
if (matrixPinState == 1)
{
matrix.fillScreen(0);
matrix.setCursor(x, 0);
matrix.print(F("Im kind"));
if (--x < -30)
{
x = matrix.width();
if (++pass >= 8) pass = 0;
matrix.setTextColor(colors[pass]);
}
matrix.show();
delay(30);
}
}

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.