Arduino中显示的数据不正确,通过USB传输到Android数据

时间:2016-06-29 12:38:57

标签: java android arduino

我正在尝试通过USB主机模式将数字形式的数据从我的Arduino UNO R3发送到我的Nexus 7平板电脑。单击按钮后,将在MainActivity java文件中调用CheckStatus()函数:

public void CheckStatus(View v)
{
    handler = new Handler();    //allocate memory for handler
    MyThread2 checkthread = new MyThread2();
    checkthread.start();

    synchronized (this)
    {
        if (usbDeviceConnection != null)
        {
            byte[] message = new byte[1];
            message[0] = (byte) (101);  //Sening any no. to Arduino, so that it responds.

            usbDeviceConnection.bulkTransfer(endpointOut, message, message.length, 0);

        }
    }

}

class MyThread2 extends Thread
{
    @Override
    public void run()
    {
        byte x;
        String string=null;
        final ByteBuffer buffer = ByteBuffer.allocate(1);

        UsbRequest request = new UsbRequest();
        request.initialize(usbDeviceConnection, endpointIn);
        while (true)
        {
            request.queue(buffer, 1);
            if (usbDeviceConnection.requestWait() == request)
            {
                try
                {
                    x = buffer.get(0);
                    string = Byte.toString(x);
                    handler.post(new newthread(string));

                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }

            }
            else break;
        }

    }

}

class newthread implements Runnable
{
    String str;
    public newthread(String STR)
    {
        str=STR;
    }
    @Override
    public void run()
    {
        tv2.setText(str);           
    }
}

这是Arduino部分:

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

void loop()
{
  if(Serial.available())
  Serial.write(7);  //Sending no. 7...
}

这里的问题是,无论我尝试从Arduino端发送任何数字(无论是7还是其他任何东西),数字0都会显示出来。我认为这可能是数据类型的问题。我可以提一下我可能出错的地方。

0 个答案:

没有答案