BASIC4MCU | 질문게시판 | 아두이노 블루투스모듈(HC-06) 모바일 값 전송 질문
페이지 정보
작성자 소오금 작성일2023-08-13 18:03 조회8,083회 댓글3건본문
현재 제가 만들고있는것은 아두이노 블루투스 센서 값을 모바일로 전송하여 화면에 나타내는 것입니다
지금 완료된 것은 아두이노 에서 성공적으로 알코올 센서를 통해 알코올 값을 확인하여 시리얼 모니터에서 확인이 가능하며
핸드폰(안드로이드 스튜디오) 에서는 성공적으로 블루투스 모듈을 통해 블루투스 연동이 성공하였습니다
하지만 아직까지 블루투스 연동은 하였지만 블루투스 센서값을 받아와 화면에 나타내는것은 못하고있는 상태입니다
아두이노코딩을 잘못한 것인지 핸드폰(안드로이드 스튜디오) 코딩을 잘못한 것인지 구분이 안가 질문 드립니다
아두이노 코딩
#include <SoftwareSerial.h>
SoftwareSerial BTSerial(10, 11);
const int buttonPin = 4; // 버튼 핀 번호
const int redLedPin = 7; // 빨간색 LED 핀 번호
const int greenLedPin = 6; // 초록색 LED 핀 번호
const int alcoholSensorPin = A5; // 알코올 센서 핀 번호
const int motorPin1 = 2; // 모터 드라이버의 IN1에 연결된 핀 번호
const int motorPin2 = 3; // 모터 드라이버의 IN2에 연결된 핀 번호
const int enablePin = 8; // 모터 드라이버의 ENA에 연결된 핀 번호
bool buttonState = false; // 버튼 상태를 저장하는 변수
void setup() {
pinMode(buttonPin, INPUT_PULLUP);
pinMode(redLedPin, OUTPUT);
pinMode(greenLedPin, OUTPUT);
pinMode(motorPin1, OUTPUT);
pinMode(motorPin2, OUTPUT);
pinMode(enablePin, OUTPUT);
BTSerial.begin(9600);
Serial.begin(9600);
}
void loop() {
int alcoholValue = analogRead(alcoholSensorPin);
Serial.println(alcoholValue);
// 알코올 수치를 검사하여 임계값을 초과하는 경우
if (alcoholValue > 300) {
digitalWrite(redLedPin, HIGH); // 빨간색 LED 켜기
digitalWrite(greenLedPin, LOW); // 초록색 LED 끄기
buttonState = false; // 버튼 상태 초기화
} else {
digitalWrite(redLedPin, LOW); // 빨간색 LED 끄기
digitalWrite(greenLedPin, HIGH); // 초록색 LED 켜기
}
// 버튼 상태에 따라 모터 동작 제어
if (buttonState) {
digitalWrite(motorPin1, HIGH);
digitalWrite(motorPin2, LOW);
analogWrite(enablePin, 255); // 모터 속도 설정 (0-255 범위)
} else {
digitalWrite(motorPin1, LOW);
digitalWrite(motorPin2, LOW);
analogWrite(enablePin, 0); // 모터 정지
}
// 버튼 상태 감지
if (digitalRead(buttonPin) == HIGH) {
buttonState = true;
} else {
buttonState = false;
}
// 알코올 값 전송
BTSerial.print(alcoholValue);
BTSerial.print(",");
BTSerial.println();
delay(2000); // 약간의 딜레이 추가하여 센서 측정 간격을 조정 (선택적)
}
안드로이드 스튜디오 코딩
package com.example.alco20172274;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.Image;
import android.os.Bundle;
import android.os.Handler;
import android.os.Process;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import org.w3c.dom.Text;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_ENABLE_BT = 10; // 블루투스 활성화 상태
private BluetoothAdapter bluetoothAdapter; // 블루투스 어댑터
private Set<BluetoothDevice> devices; // 블루투스 디바이스 데이터 셋
private BluetoothDevice bluetoothDevice; // 블루투스 디바이스
private BluetoothSocket bluetoothSocket = null; //블루투스 소켓
private OutputStream outputStream = null; //블루투스에 데이터를 출력하기 위한 출력 스트림
private InputStream inputStream = null; //블루투스에 데이터를 입력하기 위한 입력 스트림
private Thread workerThread = null; //문자열 수신에 사용되는 쓰레드
private byte[] readBuffer; //수신된 문자열 저장 버퍼
private int readBufferPosition; //버퍼 내 문자 저장 위치
private BackPressCloseHandler backkeyclickhandler;
String[] array = {"0"};
int pairedDeviceCount; //페어링 된 기기의 크기를 저장할 변수
private TextView textView_alcohol;
private TextView textViewDeviceName;
int alcohol;
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
backkeyclickhandler = new BackPressCloseHandler(this);
//위치권한 허용 코드
String[] permission_list = {
android.Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
};
ActivityCompat.requestPermissions(MainActivity.this, permission_list, 1);
textView_alcohol = findViewById(R.id.alcohol);
textViewDeviceName = findViewById(R.id.textView_device_name);
String deviceName = null;
//블루투스 활성화 코드
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); //블루투스 어댑터를 디폴트 어댑터로 설정
if (bluetoothAdapter == null) { //기기가 블루투스를 지원하지 않을때
Toast.makeText(getApplicationContext(), "Bluetooth 미지원 기기입니다.", Toast.LENGTH_SHORT).show();
//처리코드 작성
} else { // 기기가 블루투스를 지원할 때
if (bluetoothAdapter.isEnabled()) { // 기기의 블루투스 기능이 켜져있을 경우
selectBluetoothDevice(); // 블루투스 디바이스 선택 함수 호출
} else { // 기기의 블루투스 기능이 꺼져있을 경우
// 블루투스를 활성화 하기 위한 대화상자 출력
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
// 선택 값이 onActivityResult함수에서 콜백
startActivityForResult(intent, REQUEST_ENABLE_BT);
selectBluetoothDevice();
}
}
}
public void selectBluetoothDevice() {
//이미 페어링 되어있는 블루투스 기기를 탐색
devices = bluetoothAdapter.getBondedDevices();
//페어링 된 디바이스 크기 저장
pairedDeviceCount = devices.size();
//페어링 된 장치가 없는 경우
if (pairedDeviceCount == 0) {
//페어링 하기 위한 함수 호출
Toast.makeText(getApplicationContext(), "먼저 Bluetooth 설정에 들어가 페어링을 진행해 주세요.", Toast.LENGTH_SHORT).show();
}
//페어링 되어있는 장치가 있는 경우
else {
//디바이스를 선택하기 위한 대화상자 생성
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("페어링 된 블루투스 디바이스 목록");
//페어링 된 각각의 디바이스의 이름과 주소를 저장
List<String> list = new ArrayList<>();
//모든 디바이스의 이름을 리스트에 추가
for (BluetoothDevice bluetoothDevice : devices) {
list.add(bluetoothDevice.getName());
}
list.add("취소");
//list를 Charsequence 배열로 변경
final CharSequence[] charSequences = list.toArray(new CharSequence[list.size()]);
list.toArray(new CharSequence[list.size()]);
//해당 항목을 눌렀을 때 호출되는 이벤트 리스너
builder.setItems(charSequences, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//해당 디바이스와 연결하는 함수 호출
connectDevice(charSequences[which].toString());
}
});
//뒤로가기 버튼 누를때 창이 안닫히도록 설정
builder.setCancelable(false);
//다이얼로그 생성
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
@Override
public void onBackPressed() { //뒤로가기 눌렀을때
//super.onBackPressed();
backkeyclickhandler.onBackPressed(); //2번누르면 종료
}
public void connectDevice(String deviceName) {
//페어링 된 디바이스 모두 탐색
for (BluetoothDevice tempDevice : devices) {
//사용자가 선택한 이름과 같은 디바이스로 설정하고 반복문 종료
if (deviceName.equals(tempDevice.getName())) {
bluetoothDevice = tempDevice;
break;
}
}
Toast.makeText(getApplicationContext(), bluetoothDevice.getName() + " 연결 완료!", Toast.LENGTH_SHORT).show();
//UUID생성
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
//Rfcomm 채널을 통해 블루투스 디바이스와 통신하는 소켓 생성
try {
bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);
bluetoothSocket.connect();
outputStream = bluetoothSocket.getOutputStream();
inputStream = bluetoothSocket.getInputStream();
receiveData();
} catch (IOException e) {
e.printStackTrace();
}
// 연결된 블루투스 기기명을 textViewDeviceName에 설정
textViewDeviceName.setText("블루투스 기기명: " + bluetoothDevice.getName());
}
public void receiveData() {
final Handler handler = new Handler();
//데이터 수신을 위한 버퍼 생성
readBufferPosition = 0;
readBuffer = new byte[1024];
//데이터 수신을 위한 쓰레드 생성
workerThread = new Thread(new Runnable() {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
//데이터 수신 확인
int byteAvailable = inputStream.available();
//데이터 수신 된 경우
if (byteAvailable > 0) {
//입력 스트림에서 바이트 단위로 읽어옴
byte[] bytes = new byte[byteAvailable];
inputStream.read(bytes);
//입력 스트림 바이트를 한 바이트씩 읽어옴
for (int i = 0; i < byteAvailable; i++) {
byte tempByte = bytes[i];
//개행문자를 기준으로 받음 (한줄)
if (tempByte == '\n') {
//readBuffer 배열을 encodeBytes로 복사
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
//인코딩 된 바이트 배열을 문자열로 변환
final String text = new String(encodedBytes, "UTF-8");
readBufferPosition = 0;
handler.post(new Runnable() {
@Override
public void run() {
// textView_alcohol에 텍스트 설정
array = text.split(",", 3);
textView_alcohol.setText("알코올 농도:" + array[0]);
alcohol=Integer.parseInt(array[0]);
}
});
} // 개행문자가 아닐경우
else {
readBuffer[readBufferPosition++] = tempByte;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//1초 마다 받아옴
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
workerThread.start();
}
}
activity_main 에서 알코올 농도 textview 에 id는 alcohol 로 지정하였습니다
댓글 3
조회수 8,083master님의 댓글
master 작성일
analogWrite()는 PWM핀을 사용해야 합니다.
//const int enablePin=8; // 모터 드라이버의 ENA에 연결된 핀 번호
const int enablePin=5; // 모터 드라이버의 ENA에 연결된 핀 번호
5번핀 또는 9번핀을 사용해보세요
master님의 댓글
master 작성일
아두이노 코딩
#include <SoftwareSerial.h>
SoftwareSerial BTSerial(10,11);
//
const int buttonPin=4; // 버튼 핀 번호
const int redLedPin=7; // 빨간색 LED 핀 번호
const int greenLedPin=6; // 초록색 LED 핀 번호
const int alcoholSensorPin=A5; // 알코올 센서 핀 번호
const int motorPin1=2; // 모터 드라이버의 IN1에 연결된 핀 번호
const int motorPin2=3; // 모터 드라이버의 IN2에 연결된 핀 번호
const int enablePin=5; // 모터 드라이버의 ENA에 연결된 핀 번호
//
bool buttonState=false; // 버튼 상태를 저장하는 변수
//
void setup(){
pinMode(buttonPin,INPUT_PULLUP);
pinMode(redLedPin,OUTPUT); pinMode(greenLedPin,OUTPUT);
pinMode(motorPin1,OUTPUT); pinMode(motorPin2,OUTPUT); pinMode(enablePin,OUTPUT);
BTSerial.begin(9600);
Serial.begin(9600);
}
//
void loop(){
int alcoholValue=analogRead(alcoholSensorPin);
Serial.println(alcoholValue);
// 알코올 수치를 검사하여 임계값을 초과하는 경우
if(alcoholValue>300){
digitalWrite(greenLedPin,0); digitalWrite(redLedPin,1); // 빨간색 LED 켜기
buttonState=false; // 버튼 상태 초기화
}
else{
digitalWrite(redLedPin,0); digitalWrite(greenLedPin,1); // 초록색 LED 켜기
}
// 버튼 상태에 따라 모터 동작 제어
if(buttonState){
digitalWrite(motorPin1,1); digitalWrite(motorPin2,0); digitalWrite(enablePin,255); // 모터 속도 설정(0-255 범위)
}
else{
digitalWrite(motorPin1,0); digitalWrite(motorPin2,0); analogWrite(enablePin,0); // 모터 정지
}
// 버튼 상태 감지
buttonState=digitalRead(buttonPin);
// 알코올 값 전송
BTSerial.print(alcoholValue); BTSerial.println();
//
delay(2000); // 약간의 딜레이 추가하여 센서 측정 간격을 조정(선택적)
}
남들이 많이 사용하는 블루투스 앱을 찾아서 제대로 표시되는지 먼저 확인하시고
정상적으로 표시되는 것을 확인 한 후에 만든 앱으로 확인해야지 어느쪽에 문제가 있는지 쉽게 찾을 수 있습니다.
소오금님의 댓글
소오금
답변감사합니다 다시한번 시도해보겠습니다