2012-04-18 3 views
0

私はArduinoからAndroidデバイスでデータを受信するアプリケーションを開発しています。整数に変換すると最大255の値しか表示されませんが、Arduinoボードから送信された値が必要です。私は文字列に変換しようとしましたが、それはどちらもうまくいきませんでした。ArduinoからAndroidデバイスで255以上の値を受け取ることができません

どうすればこの問題を解決できますか?ここで

は、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; 
    } 
} 
+0

arduino code – MrD

+0

エラーが発生していると思われる場所にアンドロイドコードを貼り付けてください。 – MrD

+0

どのようにデバイスを接続しましたか? – MrD

答えて

2

問題はArduinoのスケッチであるように見えます。の最大 -

msg[1] = value/10 

が暗黙的value/10を切り捨て(http://arduino.cc/en/Reference/analogRead参照0から1023の整数である):msgアレイ255

線の最大値を有する(符号なし)バイトを含みます255.

value/10を送信するには、2バイトに分割する必要があります。たとえば、

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

msgは、1バイト以上の長さが必要です。

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の定義に変更が必要になります:あなたのような何かをする必要がありますアンドロイド(Java)の側では

。また

SndDataの呼び出し(ここで使用 USB_Host_Shield_2.0ですされているライブラリを想定) loopを通じて初めてで msgのすべての6つのバイトはありませんにもかかわらず、彼らは常に6つのバイトを送信するように問題がある可能性があり初期化されました。

+0

素晴らしい作品です! – ashokk

+1

この回答に満足している場合は、「受け入れ済み」としてマークしてください。ありがとう! –

関連する問題