2
HC-05 블루투스 모듈을 통해 Arduino Mega 2560에 연결된 앱을 만들었습니다. 나는 블루투스를 통해 Arduino에게 명령을 내리는 데 성공하지만, 그 반대의 통신은 분명히 작동하지 않는다. 문제가 Arduino 또는 Android 측에 있는지 나는 모른다.Arduino Android 블루투스 통신
Arduino는 다음과 같은 간단한 지침으로 메시지를 보냅니다. #include ... SoftwareSerial 블루투스 (12, 11);
void setup(){
Serial.begin(9600);
bluetooth.begin(9600);
...
}
void loop(){
...
bluetooth.listen();
while (bluetooth.available() > 0) {
char inByte = bluetooth.read();
if(inByte == '0') {
bluetooth.print('a');
delay(500);
}
}
...
}
대신 안드로이드 코드는 다음과 같습니다 :
package com.example.arduo;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends Activity implements OnClickListener {
Button Connect;
ToggleButton OnOff;
TextView Result;
private String dataToSend;
private static final String TAG = "Jon";
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
private static String address = "00:14:02:13:00:10";
private static final UUID MY_UUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
private InputStream inStream = null;
Handler handler = new Handler();
byte delimiter = 10;
boolean stopWorker = false;
int readBufferPosition = 0;
byte[] readBuffer = new byte[1024];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Connect = (Button) findViewById(R.id.connect);
OnOff = (ToggleButton) findViewById(R.id.tgOnOff);
Result = (TextView) findViewById(R.id.msgJonduino);
Connect.setOnClickListener(this);
OnOff.setOnClickListener(this);
CheckBt();
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
Log.e("Jon", device.toString());
}
@Override
public void onClick(View control) {
switch (control.getId()) {
case R.id.connect:
Connect();
break;
case R.id.tgOnOff:
if (OnOff.isChecked()) {
dataToSend = "1";
writeData(dataToSend);
} else if (!OnOff.isChecked()) {
dataToSend = "0";
writeData(dataToSend);
}
break;
}
}
private void CheckBt() {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
Toast.makeText(getApplicationContext(), "Bluetooth Disabled !",
Toast.LENGTH_SHORT).show();
}
if (mBluetoothAdapter == null) {
Toast.makeText(getApplicationContext(),
"Bluetooth null !", Toast.LENGTH_SHORT)
.show();
}
}
public void Connect() {
Log.d(TAG, address);
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
Log.d(TAG, "Connecting to ... " + device);
mBluetoothAdapter.cancelDiscovery();
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
btSocket.connect();
Log.d(TAG, "Connection made.");
Toast.makeText(getApplicationContext(), "Connessione effettuata",
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
Log.d(TAG, "Unable to end the connection");
Toast.makeText(getApplicationContext(), "Impossibile terminare la connessione",
Toast.LENGTH_SHORT).show();
}
Log.d(TAG, "Socket creation failed");
Toast.makeText(getApplicationContext(), "Creazione socket fallita.",
Toast.LENGTH_SHORT).show();
}
beginListenForData();
}
private void writeData(String data) {
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
Log.d(TAG, "Bug BEFORE Sending stuff", e);
Toast.makeText(getApplicationContext(), "Bug prima di mandare i dati",
Toast.LENGTH_SHORT).show();
}
String message = data;
byte[] msgBuffer = message.getBytes();
try {
outStream.write(msgBuffer);
Toast.makeText(getApplicationContext(), "Dati inviati correttamente",
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Log.d(TAG, "Bug while sending stuff", e);
Toast.makeText(getApplicationContext(), "Bug mandando i dati",
Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
try {
btSocket.close();
} catch (IOException e) {
}
}
public void beginListenForData() {
try {
inStream = btSocket.getInputStream();
} catch (IOException e) {
}
Thread workerThread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopWorker)
{
try
{
int bytesAvailable = inStream.available();
if(bytesAvailable > 0)
{
byte[] packetBytes = new byte[bytesAvailable];
inStream.read(packetBytes);
for(int i=0;i<bytesAvailable;i++)
{
byte b = packetBytes[i];
if(b == delimiter)
{
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable()
{
public void run()
{
// if(Result.getText().toString().equals("..")) {
Result.setText(data);
// } else {
// Result.append("\n"+data);
//}
/* You also can use Result.setText(data); it won't display multilines
*/
}
});
}
else
{
readBuffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex)
{
stopWorker = true;
}
}
}
});
workerThread.start();
}
}
안드로이드 아두 이노가 보낸 문자를 수신하거나 표시하지 않는 이유아무도 알고 있나요? 감사합니다 모두!