Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法在Android设备上从Arduino接收大于255的值_Android_Arduino - Fatal编程技术网

无法在Android设备上从Arduino接收大于255的值

无法在Android设备上从Arduino接收大于255的值,android,arduino,Android,Arduino,我正在开发一个应用程序,在Android设备上从Arduino接收数据。当我将其转换为整数时,它最多只能显示255个值,但我希望这些值是由Arduino板发送的。我曾尝试将它们转换为字符串,但也没有成功 我怎样才能解决这个问题 以下是Android设备上运行的代码: package pkg.MultipleDataReceiveFromArduinoArray; import java.io.FileDescriptor; import java.io.FileInputStream; imp

我正在开发一个应用程序,在Android设备上从Arduino接收数据。当我将其转换为整数时,它最多只能显示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();
                }
            }
        }
    };
}
package pkg.multipleDarReceivefromArduinoArray;
导入java.io.FileDescriptor;
导入java.io.FileInputStream;
导入java.io.FileOutputStream;
导入java.io.IOException;
从Arduino.R导入多数据包;
导入android.app.Activity;
导入android.app.AlertDialog;
导入android.app.pendingent;
导入android.content.BroadcastReceiver;
导入android.content.Context;
导入android.content.Intent;
导入android.content.IntentFilter;
导入android.os.Bundle;
导入android.os.Handler;
导入android.os.Message;
导入android.os.ParcelFileDescriptor;
导入android.util.Log;
导入android.view.view;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.TextView;
导入android.widget.Toast;
导入com.android.future.usb.UsbAccessory;
导入com.android.future.usb.UsbManager;
从ArduinoActivity接收的公共类多路数据扩展
活动实现可运行{
私有文本视图txtReceivedBytes;
私有文本视图TXT;
私有文本视图txtSensor1;
私有文本视图txtSensor2;
私有文本视图txtSensor3;
私有EditText etCallibrationValue;
专用按钮BTNSetCalibrationValue;
私有静态最终字符串操作\u USB\u权限=
“com.google.android.DemoKit.action.USB_权限”;
私人UsbManager mUsbManager;
私人悬而未决的侵权意图;
私有布尔mPermissionRequestPending;
私人美国特许经营权;
专用ParcelFileDescriptor mFileDescriptor;
私有文件输入流mInputStream;
私有文件输出流mOutputStream;
int countWaterVol=0;
私有int intCallibrationValue=270;
专用静态最终int信息_温度=1;
专用静态最终int信息_湿度=2;
专用静态最终int消息_水位=3;
专用静态最终字节命令\打开\门=0x01;
专用静态最终字节命令\关闭\门=0x02;
保护类遥测数据包{
私有int值;
公共遥测数据包(int值){
这个值=值;
}
public int getValue(){
返回值;
}
}
专用整数成分(字节hi,字节lo){
int val=(int)高&0xff;
val*=256;
val+=(int)低电平&0xff;
返回val;
}
/**在首次创建活动时调用*/
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtReceivedBytes=(TextView)findViewById(R.id.txtReceivedBytes);
txtwaterlls=(TextView)findViewById(R.id.txtwaterlls);
txtSensor1=(TextView)findViewById(R.id.txtSensor1);
txtSensor2=(TextView)findViewById(R.id.txtSensor2);
txtSensor3=(TextView)findViewById(R.id.txtSensor3);
etCallibrationValue=(EditText)findViewById(R.id.etCallibrationValue);
BTNSetCalibrationValue=
(按钮)findViewById(R.id.BTNSETCalibrationValue);
设置附件();
btnsetCalibrationValue.setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图v){
内部振动值=
整数.parseInt(etCallibrationValue.getText().toString());
Toast.makeText(getApplicationContext(),
“校准值:”+intCallibrationValue,
吐司。长度(短)。show();
}
});
}
@凌驾
公共对象OnRetainOnConfiguration实例(){
if(mAccessory!=null){
归还特许权;
}否则{
返回super.onRetainonConfiguration实例();
}
}
@凌驾
恢复时公开作废(){
super.onResume();
if(mInputStream!=null&&mOutputStream!=null){
//数据流不为空”);
返回;
}
//数据流为空);
UsbAccessory[]附件=mUsbManager.getAccessoryList();
usb附件=(附件==null?null:附件[0]);
如果(附件!=null){
if(mUsbManager.hasPermission(附件)){
开放式附件(附件);
}否则{
已同步(mUsbReceiver){
如果(!mPermissionRequestPending){
mUsbManager.requestPermission(
从犯(意图);
mPermissionRequestPending=true;
}
}
}
}否则{
//零配件
}
}
@凌驾
公共无效暂停(){
super.onPause();
}
@凌驾
公共空间{
未注册接收人(mUsbReceiver);
super.ondestory();
}
Handler mHandler=新处理程序(){
@凌驾
公共无效handleMessage(消息消息消息){
//遥测数据包p=(遥测数据包)msg.obj;
ValueMsg t=(ValueMsg)msg.obj;
setText(“接收字节:+t.getRet());
if(t.getReading4()==1){
countWaterVol=countWaterVol+1;
txtwaterls.setText(“以升为单位产生的水:+
(countWaterVol+“\n”+“中断信号”+t.getReading3());
}否则{
}
txtSensor1.setText(“s1:+t.getReading1()+”,”+
“阅读2:”+t.getReading2());
txtSe
#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;
    }
}
msg[1] = value/10
msg[1] = (uint8_t) (i & 0xFF);
msg[2] = (uint8_t) ((i >> 8) & 0xFF);
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]);