0

我正在开发一个应用程序来从 Arduino 接收 Android 设备上的数据。当我将其转换为整数时,它仅显示高达 255 的值,但我想要那些由 Arduino 板发送的值。我曾尝试将它们转换为字符串,但这也不起作用。

我怎么解决这个问题?

这是在 Android 设备上运行的代码:

package pkg.MultipleDataReceiveFromArduinoArray;

import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import pkg.MultipleDataReceiveFromArduino.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.future.usb.UsbAccessory;
import com.android.future.usb.UsbManager;

public class MultipleDataReceiveFromArduinoActivity extends
    Activity implements  Runnable {

    private TextView txtReceivedBytes;
    private TextView txtWaterLitres;
    private TextView txtSensor1;
    private TextView txtSensor2;
    private TextView txtSensor3;
    private EditText etCallibrationValue;
    private Button btnSetCallibrationValue;
    private static final String ACTION_USB_PERMISSION =
        "com.google.android.DemoKit.action.USB_PERMISSION";
    private UsbManager mUsbManager;
    private PendingIntent mPermissionIntent;
    private boolean mPermissionRequestPending;
    private UsbAccessory mAccessory;
    private ParcelFileDescriptor mFileDescriptor;
    private FileInputStream mInputStream;
    private FileOutputStream mOutputStream;
    int countWaterVol = 0;
    private int intCallibrationValue = 270;

    private static final int MESSAGE_TEMPERATURE = 1;
    private static final int MESSAGE_HUMIDITY = 2;
    private static final int MESSAGE_WATERLEVEL = 3;
    private static final byte COMMAND_OPEN_DOOR = 0x01;
    private static final byte COMMAND_CLOSE_DOOR = 0x02;

    protected class TelemetryPacket {
        private int value;

        public TelemetryPacket(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }
    }

    private int composeInt(byte hi, byte lo) {
        int val = (int) hi & 0xff;
        val *= 256;
        val += (int) lo & 0xff;
        return val;
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        txtReceivedBytes=(TextView)findViewById(R.id.txtReceivedBytes);
        txtWaterLitres =(TextView)findViewById(R.id.txtWaterLitres);
        txtSensor1 = (TextView) findViewById(R.id.txtSensor1);
        txtSensor2 =(TextView)findViewById(R.id.txtSensor2);
        txtSensor3 =(TextView)findViewById(R.id.txtSensor3);
        etCallibrationValue = (EditText)findViewById(R.id.etCallibrationValue);
        btnSetCallibrationValue =
            (Button)findViewById(R.id.btnSetCallibrationValue);
        setupAccessory();

        btnSetCallibrationValue.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                intCallibrationValue =
                    Integer.parseInt(etCallibrationValue.getText().toString());
                    Toast.makeText(getApplicationContext(), 
                        "Callibration Value:" + intCallibrationValue, 
                        Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public Object onRetainNonConfigurationInstance() {
        if (mAccessory != null) {
            return mAccessory;
        } else {
            return super.onRetainNonConfigurationInstance();
        }
    }

    @Override
    public void onResume() {
        super.onResume();

        if (mInputStream != null && mOutputStream != null) {
            // streams were not null");
            return;
        }

        // streams were null");
        UsbAccessory[] accessories = mUsbManager.getAccessoryList();
        UsbAccessory accessory = (accessories == null ? null : accessories[0]);
        if (accessory != null) {
            if (mUsbManager.hasPermission(accessory)) {
                openAccessory(accessory);
            } else {
                synchronized (mUsbReceiver) {
                    if (!mPermissionRequestPending) {
                        mUsbManager.requestPermission(
                            accessory, mPermissionIntent);
                        mPermissionRequestPending = true;
                    }
                }
            }
        } else {
            // null accessory
        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        unregisterReceiver(mUsbReceiver);
        super.onDestroy();
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //TelemetryPacket p = (TelemetryPacket) msg.obj;
            ValueMsg t = (ValueMsg) msg.obj;
            txtReceivedBytes.setText("Received Bytes: "+t.getRet());
            if (t.getReading4()==1) {
                countWaterVol = countWaterVol+1;
                txtWaterLitres.setText("Water Produced in Litres:"+
                    (countWaterVol+"\n"+"Interrupt Signal"+t.getReading3());
            } else {

            }

            txtSensor1.setText("S 1: "+t.getReading1()+","+
                "Reading 2: "+t.getReading2());
            txtSensor2.setText("S 3: "+t.getReading3()+","+
                "Reading 4: "+t.getReading4());
            txtSensor3.setText("S 5: "+t.getReading5()+","+
                "Reading 6: "+t.getReading6());
            Alets alerts = new Alets();
        }
    };

    private void setupAccessory() {
        mUsbManager = UsbManager.getInstance(this);
        mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(
            ACTION_USB_PERMISSION), 0);
        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
        registerReceiver(mUsbReceiver, filter);
        if (getLastNonConfigurationInstance() != null) {
            mAccessory = (UsbAccessory) getLastNonConfigurationInstance();
            openAccessory(mAccessory);
        }
    }

    private void openAccessory(UsbAccessory accessory) {
        mFileDescriptor = mUsbManager.openAccessory(accessory);
        if (mFileDescriptor != null) {
            mAccessory = accessory;
            FileDescriptor fd = mFileDescriptor.getFileDescriptor();
            mInputStream = new FileInputStream(fd);
            mOutputStream = new FileOutputStream(fd);
            Thread thread = new Thread(null, this, "OpenAccessoryTest");
            thread.start();
            // Accessory opened
        } else {
            // failed to open accessory
        }
    }

    private void closeAccessory() {
        try {
            if (mFileDescriptor != null) {
                mFileDescriptor.close();
            }
        } catch (IOException e) {

        } finally {
            mFileDescriptor = null;
            mAccessory = null;
        }
    }

    public void run() {
        int ret = 0;
        //byte[] buffer = new byte[16384];
        byte[] buffer = new byte[65536];
        int i;

        while (true) { // read data
            try {
                ret = mInputStream.read(buffer);
                //ret= ret/3;

            } catch (IOException e) {
                break;
            }

            i = 0;

            while (i < ret) {
                int len = ret - i;
                //    if (len >= 1) {
                int value = (int) buffer[0];
                Message m = Message.obtain(mHandler);
                m.obj = new ValueMsg('f',value,ret,buffer[1],buffer[2],
                buffer[3],buffer[4],buffer[5]);
                mHandler.sendMessage(m);

                i += 1;
            }
        }
    }

    public static final long unsignedIntToLong(byte[] b)
    {
        long l = 0;
        l |= b[0] & 0xFF;
        l <<= 8;
        l |= b[1] & 0xFF;
        l <<= 8;
        l |= b[2] & 0xFF;
        l <<= 8;
        l |= b[3] & 0xFF;
        return l;
    }

    public static int unsignedByteToInt(byte b) {
        return (int) b & 0x10;
    }

    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    UsbAccessory accessory = UsbManager.getAccessory(intent);
                    if (intent.getBooleanExtra(
                        UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                            openAccessory(accessory);
                    } else {
                        // USB permission denied
                    }
                }
        } else if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) {
                UsbAccessory accessory = UsbManager.getAccessory(intent);
                if (accessory != null && accessory.equals(mAccessory)) {
                    // accessory detached
                    closeAccessory();
                }
            }
        }
    };
}

这是Arduino代码(草图):

#include <Usb.h>
#include <adk.h>

uint8_t b;
USB Usb;
ADK adk(&Usb,
    "Ashok Kateshiya", // Manufacturer Name
    "analog TEST", // Model Name
    "TDS test ", // Description (user-visible string)
    "0.1", // Version
    "http://www.ashokkateshiya.co.cc", 
    "123456789"); // Serial Number (optional)

#define tds_pin A15
#define flow_pin 22
#define LLS_pin 49

float avg[10];
float value = 0;

int count;
int pin_state = 0, pin_old_state = 0;
int pulse_counter = 0;
int LLS_state;
int LLS_flag = 0;
int sensor_flag = 0;
int timer_flag = 0;

uint8_t msg[7] = { 0x00 };
uint16_t len = sizeof(msg);
uint8_t rcode;

void setup()
{
    Serial.begin(115200);
    Serial.print("\r\nADK demo start");

    if (Usb.Init() == -1)
    {
        Serial.print("\r\nOSCOKIRQ failed to assert");
        while(1); // halt
    }

    pinMode(tds_pin, INPUT);
    pinMode(flow_pin, INPUT);
    pinMode(LLS_pin, INPUT);
    digitalWrite(LLS_pin, HIGH);
    digitalWrite(flow_pin, HIGH);
    TIMSK1 = 0x01;
    TCCR1A = 0x00;
    TCNT1 = 0x85EF;
    TCCR1B = 0x05;
}

void loop()
{
    Usb.Task();

    if (adk.isReady() == false)
    {
        return;
    }

    TDS();
    flow();
    LLS();
}

void TDS()
{
    for (count = 0; count < 10; count++)
    {
        avg[count] = analogRead(tds_pin);
    }

    for (count = 0; count < 10; count ++)
    {
        if (count == 0)
        {
            value = avg[count];
        }
        else
        {
            value = value + avg[count];
        }
    }

    if (len > 0)
    {
        msg[0] = 0x1;
        msg[1] = value/10;
        rcode = adk.SndData (6, msg );
        Serial.print("TDS 0 : ");
        Serial.println(msg[0]);
        Serial.print("TDS 1 : ");
        Serial.println(msg[1]);
        delay(10);
    }

    if (rcode && rcode != hrNAK)
        USBTRACE2("DATA rcv :", rcode);
}

void flow()
{
    pin_state = digitalRead(flow_pin);

    if (pin_state == LOW)
    {
        pin_old_state = pin_state;
    }

    if ((pin_state == HIGH) && (pin_old_state == LOW))
    {
        pin_old_state = pin_state;
        pulse_counter = (pulse_counter + 1);
        sensor_flag = 1;
    }

    if ((pulse_counter / 25 == 1) && (sensor_flag == 1))
    {
        pulse_counter = 0;
        sensor_flag = 0;
        msg[2] = 0x2;
        msg[3] = 1;
        rcode = adk.SndData (6, msg );
        Serial.print("value :");
        Serial.println(msg[3]);

        if (rcode && rcode != hrNAK)
        {
            USBTRACE2 ("USB DATA : ", rcode);
        }
    }
    else
    {
        msg[2] = 0x2;
        msg[3] = 0;
        rcode = adk.SndData (6, msg );
        Serial.print("value :");
        Serial.println(msg[3]);

        if (rcode && rcode != hrNAK)
        {
            USBTRACE2 ("USB DATA : ", rcode);
        }
    }

    delay(10);
}

void LLS()
{
    LLS_state = digitalRead(LLS_pin);

    if (LLS_state != 0)
    {
        if (len > 0)
        {
            msg[4] = 0x3;
            msg[5] = 0x0;
            rcode = adk.SndData (6, msg );
            Serial.print("LLS 4 : ");
            Serial.println(msg[4]);
            Serial.print("LLS 5 : ");
            Serial.println(msg[5]);
        }
    }
    else
    {
        msg[4] = 0x3;
        msg[5] = 0x1;
        rcode = adk.SndData (6, msg );
        Serial.print("LLS 0 : ");
        Serial.println(msg[4]);
        Serial.print("LLS 2 : ");
        Serial.println(msg[5]);
    }

    if (rcode && rcode != hrNAK)
    USBTRACE2("DATA rcv :", rcode);
    delay(10);
}

/****** timer overflow *******/
ISR(TIMER1_OVF_vect)
{
    TCNT1 = 0x85EF;

    if (pin_state == pin_old_state )
    {
        timer_flag = 1;
    }
}
4

1 回答 1

2

看起来问题出在Arduino草图中。该msg数组包含(无符号)字节,最大值为 255。

该行:

msg[1] = value/10

隐式截断value/10(这是一个介于 0 和 1023 之间的整数 - 请参阅http://arduino.cc/en/Reference/analogRead)最多为 255。

要发送value/10,您需要将其拆分为 2 个字节。例如:

msg[1] = (uint8_t) (i & 0xFF);
msg[2] = (uint8_t) ((i >> 8) & 0xFF);

并且msg必须长一个字节才能容纳。

在 Android (Java) 方面,您需要执行以下操作:

int value = (int) buffer[0];
// ...
int tds = buffer[1] + (buffer[2] << 8);
m.obj = new ValueMsg('f', value, ret, tds,
    buffer[3], buffer[4], buffer[5], buffer[6]);

这将需要更改 的定义ValueMsg以适应。

SndData此外,调用(假设这里使用的库是USB_Host_Shield_2.0 )可能存在问题,因为它们总是发送 6 个字节,即使在第一次通过loop所有 6 个字节时msg都不会被初始化。

于 2012-04-19T13:51:06.287 回答