Sending bytes from Raspberry Pi (using python) to bluetooth java android application

I am working on a project to control a robot using a mobile application. So far, I have been able to send Bluetooth commands to make the robot move as needed. But I was having trouble getting input from the HC-SR04 ultrasonic sensor, which gives the float shaft every second. I wrote code to convert float to bytes, then writes bytes to serial and reads and displays them in textview using java for the application. But I get only a question mark in the textual representation, which, as I suppose, indicates that I can receive data on the channel, or bytes are not filled, or my conversions are incorrect?

Please, help.

########## here is my python script for sending bytes
while True:
        a = ser.read()  #read from the serial  port
        ser.close()
        dist = initio.getDistance()    #distance obtained from ultra sensor       
        d = int(a.encode('hex'), 16) 
        bytSend = struct.pack('f', dist)  #convert the int distance to bytes
        ser.open()
        ser.write(bytSend)

********** here is the java code for reading data by stream and sending it to the handler in my main code ***************

public void run() {
            byte[] buffer = new byte[1024];
            int bytes;
            // Keep listening to the InputStream while connected
            while (true) {
                try {
                    // Read from the InputStream
                    bytes = mmInStream.read(buffer);
                    // Send the obtained bytes to the UI Activity

                    mHandler.obtainMessage(initioActivity.MESSAGE_READ, bytes, -1, buffer)
                            .sendToTarget();

                } catch (IOException e) {
                    //
                    connectionLost();
                    break;
                }
            }
        }

*****, then in my main code (inside the handler) I have ***

case MESSAGE_READ:
                //byte[] readBuf = (byte[]) msg.obj;
                byte[] readBuf = (byte[]) msg.obj;
                //construct a string from valid bytes in buffer
                String distance = new String(readBuf, 0, msg.arg1);
                myLabel.setText(distance);

Any ideas what I can do wrong?

+4
source share
1 answer

suppose the distance d

d = 23.45454

encoded message

encoded_d = struct.pack("f",d)
print repr(encoded_d) # '\xe6\xa2\xbbA'

so when you read a string in java you get this ... since these are invalid characters, you get ?for any invalid character

you need to figure out how decodeto return it to float in java

to solve this easiest way, probably just send it as ascii

d = 23.45454
ser.write(str(d))

, , ,

- python

0

All Articles