Search code examples
javascalaserial-portarduinounsigned-integer

How can I get a byte that represents an unsigned int in Java?


I have integers from 0 to 255, and I need to pass them along to an OutputStream encoded as unsigned bytes. I've tried to convert using a mask like so, but if i=1, the other end of my stream (a serial device expecting uint8_t) thinks I've sent an unsigned integer = 6.

OutputStream out;
public void writeToStream(int i) throws Exception {
    out.write(((byte)(i & 0xff)));
}

I'm talking to an Arduino at /dev/ttyUSB0 using Ubuntu if this makes things any more or less interesting.

Here's the Arduino code:

uint8_t nextByte() {
    while(1) {
    if(Serial.available() > 0) {
        uint8_t b =  Serial.read();
      return b;
     }
    }
}

I also have some Python code that works great with the Arduino code, and the Arduino happily receives the correct integer if I use this code in Python:

class writerThread(threading.Thread): 
    def __init__(self, threadID, name):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
    def run(self):
        while True:
            input = raw_input("[W}Give Me Input!")
            if (input == "exit"):
               exit("Goodbye");
            print ("[W]You input %s\n" % input.strip())
            fval = [ int(input.strip()) ]
            ser.write("".join([chr(x) for x in fval]))

I'd also eventually like to do this in Scala, but I'm falling back to Java to avoid the complexity while I solve this issue.


Solution

  • Cast, then mask: ((byte)(i)&0xff)

    But, something is very strange since:

    (dec)8 - (binary)1000
    (dec)6 - (binary)0110

    [edit]
    How is your Arduino receiving 6 (binary)0110 when you send 1 (binary)0001?
    [/edit]