Software Serial to ASCII

Just starting with Software Serial.
I found that in order to print out an ASCII character from the incoming byte I need to substract 128 from it. Why is that?

#include <SoftwareSerial.h>

// Pin 0 connected to pin 3
// Pin 1 connected to pin 2
SoftwareSerial SWSerial(2, 3); // RX, TX

void setup()
{
  Serial.begin(9600);

  SWSerial.begin(9600);
  SWSerial.write("SW Serial here"); 
}

void loop()
{
  int incomingByte;
 
  if (Serial.available())
  {
    incomingByte = Serial.read();
    
    // say what you got:
    Serial.print("I received: ");

  	Serial.write(incomingByte-128); 
    
    Serial.println();
  }  
}

I received: S
I received: W
I received:
I received: S
I received: e
I received: r
I received: i
I received: a
I received: l
I received:
I received: h
I received: e
I received: r
I received: e

![image|147x171](upload://o3uo5B8Zadj9SFyiEGFlCTibPjs.png)

Serial.write is different from Serial.print
Read up, it’s there to help you.

Regards,

Michael Coop
mcoop@SL4P.net
0402 257 265

I am not even using Serial.print
The code does write -> read -> write
write is in bytes and read is in integers, so I guess that's why I need to substract or truncate the incoming data?

Use SWSerial.print() instead, and declare incomingByte as "char", not "int".

SWSerial.write("SW Serial here");

From the Arduino Reference:

Serial.write()

Description

Writes binary data to the serial port. This data is sent as a byte or series of bytes; to send the characters representing the digits of a number use the print() function instead.

My guess is that whatever is sending to your Serial input is sending 7 data bits. By default, Serial reads 8 data bits. That would cause the Stop Bit to be read as an 8th data bit. Try changing "Serial.begin(9600);" to "Serial.begin(9600, 7N1);". Then you should remove the "-128"

Your sketch sets up SoftwareSerial and then doesn't use it at all.

@johnwasser I am letting the Arduino talk to itself SW serial to HW serial, just to see how it works. So hopefully, I shouldn't need to worry about stop bits?


I am running the original sketch in TinkerCad. Maybe it is a glitch on that website?
I should try this setup with a physical board next.

I left out the wire between Pin 1 and Pin 2 and got good data by removing the "- 128". Maybe sending while receiving is causing problems?

It works as expected with real hardware.
-128 is only for TinkerCad website . That got me so confused.
I'll report it back to them.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.