My idea is Arduino sensor will read and pass the values read on android. Then android will calculate and send the control value (PWM) to the Arduino. but android can only get the value from the Arduino but can not send them back to the Arduino ... Can someone please help? This my code:
java code:
+MainActivity
package com.example.tut1;
import java.nio.ByteBuffer;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.example.tut1.Bluetooth;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.GraphView.GraphViewData;
import com.jjoe64.graphview.GraphView.LegendAlign;
import com.jjoe64.graphview.GraphViewSeries;
import com.jjoe64.graphview.GraphViewSeries.GraphViewStyle;
import com.jjoe64.graphview.LineGraphView;
public class MainActivity extends Activity implements View.OnClickListener {
// private StringBuilder recDataString = new StringBuilder();
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
if (Bluetooth.connectedThread != null) {
Bluetooth.connectedThread.write("Q");
}// Stop streaming
super.onBackPressed();
}
// khai bao bien
String x, x1;
int u,u1,adc,adc1;
public String sensor, sensor1;
static boolean f=false;
// toggle Button
static boolean Lock;// whether lock the x-axis to 0-5
static boolean AutoScrollX;// auto scroll to the last x value
static boolean Stream;// Start or stop streaming
// Button init
Button bXminus;
Button bXplus;
Button bConnect, bDisconnect;
Button bStart,bStop;
TextView tvBluetooth, tvpid;
ToggleButton tbLock;
ToggleButton tbScroll;
ToggleButton tbStream;
// GraphView init
static LinearLayout GraphView, GraphView1;
static GraphView graphView, graphView1;
static GraphViewSeries Series, Series1;
// graph value
private static double graph2LastXValue = 0, graph2LastXValue1 = 0;
private static int Xview = 10, Xview1 = 10;
// khai bao bien timer
final Handler thandler = new Handler();
Timer t = new Timer();
TimerTask mTimerTask;
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
switch (msg.what) {
case Bluetooth.SUCCESS_CONNECT:
Bluetooth.connectedThread = new Bluetooth.ConnectedThread(
(BluetoothSocket) msg.obj);
Toast.makeText(getApplicationContext(), "Connected!", 0).show();
String s = "successfully connected";
Bluetooth.connectedThread.start();
break;
case Bluetooth.MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf); // create string from
// bytes array
// if(strIncom.indexOf('s')==0){
// strIncom = strIncom.replace("s", "");
// }
int a = strIncom.indexOf("c");
int b = 4;
int c = 4;
int d = 8;
sensor = (String) strIncom.subSequence(1, 5);
sensor1 = (String) strIncom.subSequence(5, 9);
tvBluetooth.setText(strIncom);
// Bluetooth.connectedThread.write("E");
// adc=Integer.parseInt(sensor);
// adc1=Integer.parseInt(sensor1);
tvpid.setText(sensor + "-" + sensor1+"-"+u+"-"+u1);
// String readMessage = (String)msg.obj;
// recDataString.append(readMessage);
// sensor = recDataString.substring(0, 4);
Log.d("strIncom", sensor);
// if (strIncom.indexOf('.')==2 && strIncom.indexOf('s')==0){
// strIncom = strIncom.replace("s", "");
if((strIncom.indexOf("X")==9)&&(strIncom.indexOf("Y")==0)){
if (isFloatNumber(sensor) && isFloatNumber(sensor1)) {
Series.appendData(new GraphViewData(graph2LastXValue,
Double.parseDouble(sensor)), AutoScrollX);
Series1.appendData(new GraphViewData(graph2LastXValue1,
Double.parseDouble(sensor1)), AutoScrollX);
// X-axis control
if (graph2LastXValue >= Xview && Lock == true) {
Series.resetData(new GraphViewData[] {});
graph2LastXValue = 0;
} else
graph2LastXValue += 0.1;
if (Lock == true)
graphView.setViewPort(0, Xview);
else
graphView.setViewPort(graph2LastXValue - Xview, Xview);
// grap1
if (graph2LastXValue1 >= Xview1 && Lock == true) {
Series1.resetData(new GraphViewData[] {});
graph2LastXValue1 = 0;
} else
graph2LastXValue1 += 0.1;
if (Lock == true)
graphView1.setViewPort(0, Xview1);
else
graphView1.setViewPort(graph2LastXValue1 - Xview1,
Xview1);
// refresh
GraphView.removeView(graphView);
GraphView1.removeView(graphView1);
GraphView.addView(graphView);
GraphView1.addView(graphView1);
dieukhienPPM();
dieukhienPH();
}
}
// if(f)
// t.schedule(mTimerTask, 60, 60);
// u = (int) adc/4;
// u1=(int) adc1/4;
// f=true;
break;
}
}
public boolean isFloatNumber(String num) {
// Log.d("checkfloatNum", num);
try {
Double.parseDouble(num);
} catch (NumberFormatException nfe) {
return false;
}
return true;
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
requestWindowFeature(Window.FEATURE_NO_TITLE);// Hide title
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);// Hide Status bar
setContentView(R.layout.activity_main);
// set background color
LinearLayout background = (LinearLayout) findViewById(R.id.bg);
background.setBackgroundColor(Color.BLACK);
init();
ButtonInit();
}
void init() {
Bluetooth.gethandler(mHandler);
// init graphview
GraphView = (LinearLayout) findViewById(R.id.Graph);
// init example series data-------------------
Series = new GraphViewSeries("Signal", new GraphViewStyle(Color.YELLOW,
2),// color and thickness of the line
new GraphViewData[] { new GraphViewData(0, 0) });
graphView = new LineGraphView(this // context
, "Graph" // heading
);
graphView.setViewPort(0, Xview);
graphView.setScrollable(true);
graphView.setScalable(true);
graphView.setShowLegend(true);
graphView.setLegendAlign(LegendAlign.BOTTOM);
graphView.setManualYAxis(true);
graphView.setManualYAxisBounds(1024, 0);
graphView.addSeries(Series); // data
GraphView.addView(graphView);
GraphView1 = (LinearLayout) findViewById(R.id.Graph1);
// init example series data-------------------
Series1 = new GraphViewSeries("Signal", new GraphViewStyle(
Color.YELLOW, 2),// color and thickness of the line
new GraphViewData[] { new GraphViewData(0, 0) });
graphView1 = new LineGraphView(this // context
, "Graph1" // heading
);
graphView1.setViewPort(0, Xview1);
graphView1.setScrollable(true);
graphView1.setScalable(true);
graphView1.setShowLegend(true);
graphView1.setLegendAlign(LegendAlign.BOTTOM);
graphView1.setManualYAxis(true);
graphView1.setManualYAxisBounds(1024, 0);
graphView1.addSeries(Series1); // data
GraphView1.addView(graphView1);
}
void ButtonInit() {
bConnect = (Button) findViewById(R.id.bConnect);
bConnect.setOnClickListener(this);
bDisconnect = (Button) findViewById(R.id.bDisconnect);
bDisconnect.setOnClickListener(this);
bStart = (Button) findViewById(R.id.bStart);
bStart.setOnClickListener(this);
bStop = (Button) findViewById(R.id.bStop);
bStop.setOnClickListener(this);
// X-axis control button
// bXminus = (Button)findViewById(R.id.bXminus);
// bXminus.setOnClickListener(this);
// bXplus = (Button)findViewById(R.id.bXplus);
// bXplus.setOnClickListener(this);
// //
// tbLock = (ToggleButton)findViewById(R.id.tbLock);
// tbLock.setOnClickListener(this);
// tbScroll = (ToggleButton)findViewById(R.id.tbScroll);
// tbScroll.setOnClickListener(this);
// tbStream = (ToggleButton) findViewById(R.id.tbStream);
// tbStream.setOnClickListener(this);
tvBluetooth = (TextView) findViewById(R.id.tvBluetooth);
tvpid = (TextView) findViewById(R.id.tvpid);
// init toggleButton
Lock = true;
AutoScrollX = true;
Stream = false;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bConnect:
startActivity(new Intent("android.intent.action.BT1"));
break;
case R.id.bDisconnect:
Bluetooth.disconnect();
break;
case R.id.bStart:
if (Bluetooth.connectedThread != null)
Bluetooth.connectedThread.write("E");
doTimerTask();
break;
case R.id.bStop:
if (Bluetooth.connectedThread != null)
Bluetooth.connectedThread.write("Q");
stopTask();
break;
// case R.id.bXminus:
// if (Xview>1) Xview--;
// break;
// case R.id.bXplus:
// if (Xview<30) Xview++;
// break;
// case R.id.tbLock:
// if (tbLock.isChecked()){
// Lock = true;
// }else{
// Lock = false;
// }
// break;
// case R.id.tbScroll:
// if (tbScroll.isChecked()){
// AutoScrollX = true;
// }else{
// AutoScrollX = false;
// }
// break;
// case R.id.tbStream:
// if (tbStream.isChecked()) {
// if (Bluetooth.connectedThread != null)
// Bluetooth.connectedThread.write("E");
// } else {
// if (Bluetooth.connectedThread != null)
// Bluetooth.connectedThread.write("Q");
// }
// break;
}
}
public void doTimerTask() {
mTimerTask = new TimerTask() {
public void run() {
thandler.post(new Runnable() {
public void run() {
// TODO Auto-generated method stub
// dieukhienPPM();
// dieukhienPH();
Bluetooth.connectedThread.write("A");
x = Integer.toString(u);
Bluetooth.connectedThread.write(x);
Bluetooth.connectedThread.write("B");
x1=Integer.toString(u1);
Bluetooth.connectedThread.write(x1);
Bluetooth.connectedThread.write("S");
}
});
}
};
// public void schedule (TimerTask task, long delay, long period)
t.schedule(mTimerTask, 500, 500); // Thoi gian delay va thoi gian lap
// tinh
// bang mili giay
}
public void stopTask() {
if (mTimerTask != null)
mTimerTask.cancel();
}
public void dieukhienPPM() {
u= (Integer.parseInt(sensor)/4);
}
public void dieukhienPH() {
u1 = (Integer.parseInt(sensor1)/4);
}
public static byte[] toByteArray(double value) {
byte[] bytes = new byte[8];
ByteBuffer.wrap(bytes).putDouble(value);
return bytes;
}
}
+Bluetooth
package com.example.tut1;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
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.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class Bluetooth extends Activity implements OnItemClickListener{
public static void disconnect(){
if (connectedThread != null) {
connectedThread.cancel();
connectedThread = null;
}
}
public static void gethandler(Handler handler){//Bluetooth handler
mHandler = handler;
}
static Handler mHandler = new Handler();
static ConnectedThread connectedThread;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000- 00805F9B34FB");
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
ArrayAdapter<String> listAdapter;
ListView listView;
static BluetoothAdapter btAdapter;
Set<BluetoothDevice> devicesArray;
ArrayList<String> pairedDevices;
ArrayList<BluetoothDevice> devices;
IntentFilter filter;
BroadcastReceiver receiver;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
init();
if (btAdapter==null){
Toast.makeText(getApplicationContext(), "No bluetooth detected", 0).show();
finish();
}else{
if (!btAdapter.isEnabled()){
turnOnBT();
}
getPairedDevices();
startDiscovery();
}
}
private void startDiscovery() {
// TODO Auto-generated method stub
btAdapter.cancelDiscovery();
btAdapter.startDiscovery();
}
private void turnOnBT() {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1);
}
private void getPairedDevices() {
devicesArray = btAdapter.getBondedDevices();
if (devicesArray.size()>0){
for(BluetoothDevice device:devicesArray){
pairedDevices.add(device.getName());
}
}
}
private void init(){
listView = (ListView)findViewById(R.id.listView);
listView.setOnItemClickListener(this);
listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,0);
listView.setAdapter(listAdapter);
btAdapter = BluetoothAdapter.getDefaultAdapter();
pairedDevices = new ArrayList<String>();
filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
devices = new ArrayList<BluetoothDevice>();
receiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
devices.add(device);
String s = "";
for(int a=0;a<pairedDevices.size();a++){
if (device.getName().equals(pairedDevices.get(a))){
//append
s = "(Paired)";
break;
}
}
listAdapter.add(device.getName()+" "+s+" "+"\n"+device.getAddress());
}else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
}else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
}else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
if (btAdapter.getState() == btAdapter.STATE_OFF){
turnOnBT();
}
}
}
};
registerReceiver(receiver, filter);
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
registerReceiver(receiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(receiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
unregisterReceiver(receiver);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CANCELED){
Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show();
finish();
}
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
if (btAdapter.isDiscovering()){
btAdapter.cancelDiscovery();
}
if (listAdapter.getItem(arg2).contains("(Paired)")){
BluetoothDevice selectedDevice = devices.get(arg2);
ConnectThread connect = new ConnectThread(selectedDevice);
connect.start();
}else {
Toast.makeText(getApplicationContext(), "device is not paired", 0).show();
}
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
btAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
//connectedThread = new ConnectedThread(mmSocket);
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
static class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
StringBuffer sbb = new StringBuffer();
public void run() {
byte[] buffer; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
try {
sleep(30);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
buffer = new byte[1024];
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(String income) {
try {
mmOutStream.write(income.getBytes());
for(int i=0;i<income.getBytes().length;i++)
Log.v("outStream"+Integer.toString(i),Character.toString((char)(Integer.parseInt(Byte.toString(income.getBytes()[i])))));
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) { }
}
public void write_1(byte[] bytes) {
try {
mmOutStream.write(bytes);
try{
Thread.sleep(20);
}catch(InterruptedException e){
e.printStackTrace();
}
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
}
code arduino
float nhietdo,doam,nhietdotb,doamtb;
float t,p;
char re;
char p1,p2;
int chanlaynhiet=0;
int pwm,pwm1;
String nhan,nhan1;
boolean batdau = false;
void setup()
{
Serial.begin(9600);
pinMode(10,OUTPUT);
pinMode(11,OUTPUT);
pinMode(8,OUTPUT);
}
void loop()
{
if(Serial.available()>0){
re = Serial.read();
switch(re){
case 'S':
Send();
digitalWrite(8,LOW);
break;
case 'A':
nhan=Serial.read();
//digitalWrite(8,LOW);
break;
case 'B':
nhan1=Serial.read();
//digitalWrite(8,LOW);
break;
case 'E' :
batdau = true;
break;
case 'Q':
batdau = false;
break;
}
if(batdau){
start();
}
}
void start()
{
while(1)
{//doc ppm
for(int i=0;i<10;i++)
{
nhietdotb=nhietdotb+analogRead(A0);
delay(1);
}
nhietdo=nhietdotb/10;
nhietdotb=0;
//doc ph
for(int j=0;j<10;j++)
{
doamtb=doamtb+analogRead(A1);
delay(1);
}
doam=doamtb/10;
doamtb=0;
//if (isDigit(pwm1))
//analogWrite(10,pwm1);
//if (isDigit(pwm2))
//analogWrite(11,pwm2);
analogWrite(11,nhan1.toInt);
analogWrite(10,nhan.toInt);
digitalWrite(8,HIGH);
if(Serial.available()>0)
return;
}
}
void Send()
{
Serial.print('s');
Serial.print('Y');
if((nhietdo<1000)&&(nhietdo>=100)){
Serial.print("0");
}else if((nhietdo<100)&&(nhietdo>=10)){
Serial.print("00");
}else if(nhietdo<10){
Serial.print("000");
}
Serial.print(nhietdo,0);
if((doam<1000)&&(doam>=100)){
Serial.print("0");
}else if((doam<100)&&(doam>=10)){
Serial.print("00");
}else if(doam<10){
Serial.print("000");
}
Serial.print(doam,0);
Serial.print('X');
Serial.print(nhan);
Serial.print(nhan1);
}
-
Can you post your Arduino code please, it may help locating the problem. Some more information on your set-up would also be useful. What Bluetooth module are you using?ForgeMonkey– ForgeMonkey2015年03月30日 09:07:24 +00:00Commented Mar 30, 2015 at 9:07
-
i am using module HC-05 and board arduino Uno R3.Lê Thành Đạt– Lê Thành Đạt2015年03月30日 09:42:37 +00:00Commented Mar 30, 2015 at 9:42
3 Answers 3
Your issue is probably this code (and similar) in the Android MainActivity:
x = Integer.toString(u);
Bluetooth.connectedThread.write(x);
Remember that you are sending bytes, not ascii representations of them. For example, if the variable 'u' is 9, you would be sending the value 57. The larger problem is that if 'u' is 10 or higher, you are sending more than one byte, and the code below...
case 'A':
nhan=Serial.read();
//digitalWrite(8,LOW);
break;
...only reads one byte of the number. A better way to approach this is to always send your data in a packet - start each packet with a control or attention byte (255 is a good one), a command for your select, and as many bytes as you need for the data. Then always send and read a complete packet.
Arduino code:
//Defines make your code more readable.
#define PACKET_SIZE 3
#define CONTROL_BYTE 255
#define WHATEVER_A_MEANS 65
#define WHATEVER_B_MEANS 66
//...
void loop()
{
byte buffer[PACKET_SIZE];
if (Serial.available() >= PACKET_SIZE)
{
// Read the first byte
buffer[0] = Serial.read();
// If it's really the start byte (255) ...
if (buffer[0] == CONTROL_BYTE)
{
// ... then get the next two bytes
for (i = 1; i < PACKET_SIZE; i++) buffer[i] = Serial.read();
}
else
{
//Otherwise it isn't a good packet.
return;
}
switch (buffer[1])
{
case WHATEVER_A_MEANS:
nhan = buffer[2];
break;
case WHATEVER_B_MEANS:
nhan1 = buffer[2];
break;
//etc.
}
//...
Android code:
//Class level scope. Note that these don't have to be 'letters' unless you
//need them to be for some other reason.
public static final byte CONTROL_BYTE = (byte)255;
public static final byte WHATEVER_A_MEANS = (byte)65;
public static final byte WHATEVER_B_MEANS = (byte)66;
//...
public void doTimerTask() {
mTimerTask = new TimerTask() {
public void run() {
thandler.post(new Runnable() {
public void run() {
Bluetooth.connectedThread.write(CONTROL_BYTE);
Bluetooth.connectedThread.write(WHATEVER_A_MEANS);
//Note that this is a narrowing cast of u.
Bluetooth.connectedThread.write((byte)u);
If 'u' needs to hold values bigger than 8 bits (you have it declared as an int), you'll need to split it into bytes and then recombine them in the Arduino code.
sr, Arduino code
float nhietdo,doam,nhietdotb,doamtb;
float t,p;
char re;
char p1,p2;
int chanlaynhiet=0;
int pwm,pwm1;
String nhan,nhan1;
boolean batdau = false;
void setup()
{
Serial.begin(9600);
pinMode(10,OUTPUT);
pinMode(11,OUTPUT);
pinMode(8,OUTPUT);
}
void loop()
{
if(Serial.available()>0){
re = Serial.read();
switch(re){
case 'S':
Send();
digitalWrite(8,LOW);
break;
case 'A':
nhan=Serial.read();
// digitalWrite(8,LOW);
break;
case 'B':
nhan1=Serial.read();
// digitalWrite(8,LOW);
break;
case 'E' :
batdau = true;
break;
case 'Q':
batdau = false;
break;
}
if(batdau){
start();
}
}
void start()
{
while(1)
{//doc ppm
for(int i=0;i<10;i++)
{
nhietdotb=nhietdotb+analogRead(A0);
delay(1);
}
nhietdo=nhietdotb/10;
nhietdotb=0;
//doc ph
for(int j=0;j<10;j++)
{
doamtb=doamtb+analogRead(A1);
delay(1);
}
doam=doamtb/10;
doamtb=0;
// if (isDigit(pwm1))
// analogWrite(10,pwm1);
// if (isDigit(pwm2))
// analogWrite(11,pwm2);
analogWrite(11,nhan1.toInt);
analogWrite(10,nhan.toInt);
digitalWrite(8,HIGH);
if(Serial.available()>0)
return;
}
}
void Send()
{
Serial.print('s');
Serial.print('Y');
if((nhietdo<1000)&&(nhietdo>=100)){
Serial.print("0");
}else if((nhietdo<100)&&(nhietdo>=10)){
Serial.print("00");
}else if(nhietdo<10){
Serial.print("000");
}
Serial.print(nhietdo,0);
if((doam<1000)&&(doam>=100)){
Serial.print("0");
}else if((doam<100)&&(doam>=10)){
Serial.print("00");
}else if(doam<10){
Serial.print("000");
}
Serial.print(doam,0);
Serial.print('X');
Serial.print(nhan);
Serial.print(nhan1);
}
-
You shouldn't post this as an answer to the question, instead you should edit your question to include the code above.ForgeMonkey– ForgeMonkey2015年03月30日 09:43:50 +00:00Commented Mar 30, 2015 at 9:43
As Cominterm said, you are doing a lot of mistakes. I would use start and end bytes like:
HEX ASCII
31 3B | "1;" -start of the message
3F 30 | "?0" - end of message
And in arduino check for them.
Also a tip, if you read bytes i would get rid of those 'A', 'S' and so on. These are ascii codes. You can easily do a mistake and this will be pain in the ass. Send byte 10
from Android and read as byte 138
in Arduino, because in Java byte is -127 : 128
and Arduino 0 : 255
I would do in hex representation, this helps in troubleshooting. For ex.: byte 1C
hex in Android is 1C
hex in Arduino.
Also get rid of those byte to string, int to string conversations. They add more points to mistake :) Also check if string is terminated with 0円
and it will be 2 bytes instead of 1.