-1

I have the following code:

#include <SoftwareSerial.h>
#include <Keyboard.h>

SoftwareSerial ttySerial(10, 11); // RX, TX
void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Native USB only
  }

  Serial.println("Serial Initialized");

  //Set the data rate for the SoftwareSerial port
  ttySerial.begin(115200);
  ttySerial.println("tty Initialized");

  Keyboard.begin();
}

void loop() 
{
  while (ttySerial.available())
    //Serial.write();
    Keyboard.write(ttySerial.read());

//    if (Serial.available())
//      ttySerial.write(Serial.read());
}

my problem is that ttySerial.read() is an int and I thought that the Keyboard.write method could hand integer arguments: Keyboard.write(32) should write "< space >" not "32".

Any ideas what is going on?

16
  • i do not see Keyboard.write(32) in your code ... what are you doing to send byte 32 to the sketch? Commented Mar 4, 2020 at 2:46
  • @jsotola thats because I am writing byte 32 to the RX Pin using SoftwareSerial. The ttySerial.read() is where I recover that and want it to be written using Keyboard.write. Simply put ttySerial.read() == byte 32 (but can also take on the form of other bytes) Commented Mar 4, 2020 at 2:53
  • And what is the problem? Is this program misbehaving? If so, what it it doing? What behavior do you expect instead? Commented Mar 4, 2020 at 12:47
  • 2
    you could use parseInt. or send bytes not text. what is the sender? send ' ' not "32" Commented Mar 4, 2020 at 15:48
  • 1
    You can send arbitrary data with a JavaScript buffer. For instance, both Buffer.from([32]) and Buffer.from(' ') will give you a buffer holding a single byte with the numeric value 32. Commented Mar 4, 2020 at 17:34

1 Answer 1

-1

write will treat an int as a number and assume you want it converted to ascii. Try casting that to char:

Keyboard.write((char)ttySerial.read());

The print class treats char variables as if they are already ascii codes.

4
  • Are you saying I should try Keyboard.print(...)? Or .write as you have? Commented Mar 5, 2020 at 2:58
  • I'm saying that either way you have to feed it a char if it is an ascii code. And yeah, I'd probably use print there. Commented Mar 5, 2020 at 3:12
  • Well I tried (char)... at one point but the behavior still wasn't write but I didn't do it using .print not sure if that would make the difference - I'll have to try it out next week but I'll let you know Commented Mar 5, 2020 at 3:30
  • Delta_G, read the comments please Commented Mar 5, 2020 at 5:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.