Tominboston
Posts: 14
Joined: Thu Dec 10, 2015 4:32 pm

Sending Ascii String from Java

Mon Feb 22, 2016 4:31 pm

Hello again,

I am making good progress with my Pi and serial communications (thanks to the Pi4J example code ! ). My ultimate goal is to communicate to a small servo amplifier I have here . It is possible to do this over the serial port on the amplifier, but messages must be in Ascii format.

I have managed to convert (using someone else's example code) what I want to send (for example the amplifier wants to see an ascii message "termon" in ascii to enter control from serial port, and I can print the ascii codes for each character. I am just not sure how I can package it up to transmit out the serial port in the correct ascii format. I always get stuck in these situations where the compiler is "expecting " something different than I am thinking ...
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
String str = "termon";

StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray())
sb.append((int)c);

BigInteger mInt = new BigInteger(sb.toString());
System.out.println(mInt);
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

Since there seems to be a class and methods for almost everything in java ... is there something anyone could suggest?

Thank you

Tom

-rst-
Posts: 1316
Joined: Thu Nov 01, 2012 12:12 pm
Location: Dublin, Ireland

Re: Sending Ascii String from Java

Mon Feb 29, 2016 4:59 pm

Not 100% sure what the required 'ascii format' means: is it ascii characters or ascii character codes :roll:

If the first, something like:

Code: Select all

...
// open serial port
...
OutputStream out = serialPort.getOutputStream();
for (char c: s.toCharArray()) {
    out.write(c);
}
...
which would write the ascii characters: t e r m o n

If the second:

Code: Select all

...
// open serial port
...
OutputStream out = serialPort.getOutputStream();
for (char c: s.toCharArray()) {
    out.write((int)c);
}
...
which would write the ascii codes: 116 101 114 109 111 110
http://raspberrycompote.blogspot.com/ - Low-level graphics and 'Coding Gold Dust'

Tominboston
Posts: 14
Joined: Thu Dec 10, 2015 4:32 pm

Re: Sending Ascii String from Java

Tue Mar 01, 2016 3:22 pm

Thank you RST, from the documentation I have for the device I am sending to I believe it is the first case , sending the ascii characters. I was trying to do a loop back to be sure what I am sending is correct but I have a ways to go as I am getting garbage back.....

I am assuming that I can set the RPi baud rate to 19200 at least that is what I am trying to do before starting to communicate.

Thanks again, I think I just need to dig in a bit more... and experiment a bit and learn more.

Tom

Return to “Java”