질문게시판 > 아두이노 블루투스모듈(HC-06) 모바일 값 전송 질문

TODAY492 TOTAL2,925,355
사이트 이용안내
Login▼/회원가입
최신글보기 질문게시판 기술자료 동영상강좌

아두이노 센서 ATMEGA128 PWM LED 초음파 AVR 블루투스 LCD UART 모터 적외선


BASIC4MCU | 질문게시판 | 아두이노 블루투스모듈(HC-06) 모바일 값 전송 질문

페이지 정보

작성자 소오금 작성일2023-08-13 18:03 조회457회 댓글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 로 지정하였습니다

  • BASIC4MCU 작성글 SNS에 공유하기
  • 페이스북으로 보내기
  • 트위터로 보내기
  • 구글플러스로 보내기

댓글 3

조회수 457

master님의 댓글

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);  // 약간의 딜레이 추가하여 센서 측정 간격을 조정(선택적)
}

남들이 많이 사용하는 블루투스 앱을 찾아서 제대로 표시되는지 먼저 확인하시고
정상적으로 표시되는 것을 확인 한 후에 만든 앱으로 확인해야지 어느쪽에 문제가 있는지 쉽게 찾을 수 있습니다.

소오금님의 댓글

소오금 댓글의 댓글 작성일

답변감사합니다 다시한번 시도해보겠습니다

질문게시판HOME > 질문게시판 목록

MCU, AVR, 아두이노 등 전자공학에 관련된 질문을 무료회원가입 후 작성해주시면 전문가가 답변해드립니다.
ATMEGA128PWMLED초음파
아두이노AVR블루투스LCD
UART모터적외선ATMEGA
전체 스위치 센서
질문게시판 목록
제목 작성자 작성일 조회
공지 MCU, AVR, 아두이노 등 전자공학에 관련된 질문은 질문게시판에서만 작성 가능합니다. 스태프 19-01-15 21054
공지 사이트 이용 안내댓글[29] master 17-10-29 34900
질문 질문있습니다ㅠㅠ 부탁드려요 새글 keldeo 02:57 5
질문 0 ~ 99 이중 for문으로 작성하는법!댓글[2] 새글 상어 23-09-26 11
질문 리튬배터리로 화면 출력 질문드립니다 !댓글[1] 이미지새글 멘탈나간다 23-09-26 9
질문 lcd,바코드,서보모터, 아두이노 질문 드립니다. ㅠㅠ댓글[1] 새글 아두이노개발자 23-09-26 20
질문 stm32에서 변수 값을 유지하는 방법댓글[1] 새글 라칸 23-09-26 15
질문 안녕하세요 스위치로 led 제어 관련 질문이 있습니다댓글[1] 새글 노형빈 23-09-25 17
질문 16X16 도트 매트릭스 구동방법 질문입니다.댓글[1] 새글첨부파일 맹균 23-09-25 16
질문 stm32에서 RTC 시간 함수 쓰는데 의문점댓글[1] 새글 라칸 23-09-25 22
질문 GPS 모듈 관련 질문입니다.댓글[3] 지구과학 23-09-22 29
질문 아두이노 블루투스와 초음파센서를 이용한 장애물 정지댓글[2] 둘둘이 23-09-22 57
답변 답변글 답변 : 아두이노 블루투스와 초음파센서를 이용한 장애물 정지댓글[1] 새글 master 23-09-25 19
질문 stm32 보드에서 시간설정과 불러오기를 하는데댓글[5] 라칸 23-09-22 41
질문 아두이노 인터럽트 질문입니다.댓글[2] Tell 23-09-21 45
답변 답변글 답변 : 아두이노 인터럽트 질문입니다.댓글[1] master 23-09-22 54
질문 아두이노와 거리 감지 센서의 전류 관련댓글[1] hmkim 23-09-21 65
질문 아두이노 코딩 질문있습니다. 도와주세요....댓글[1] 이미지첨부파일 vnpaz 23-09-20 70
질문 아두이노를 사용한 dc모터 위치제어댓글[2] 모터위치 23-09-20 62
질문 stm32 디버깅이나 rst버튼 없이 하는 방법좀댓글[1] 라칸 23-09-20 53
질문 LCD에 숫자 표기법을 바꾸고 싶습니댓글[2] Bs드리프터 23-09-19 125
질문 알코올 측정기(MQ-3) 관련 질문 이미지 소오금 23-09-18 61
답변 답변글 답변 : 알코올 측정기(MQ-3) 관련 질문 master 23-09-19 112
질문 스텝모터 제어하는 소스파일 수정방법 질문드립니다. Bs드리프터 23-09-15 75
답변 답변글 답변 : 스텝모터 제어하는 소스파일 수정방법 질문드립니다.댓글[1] master 23-09-15 109
질문 atmega 128을 이용한 악기 튜너기댓글[1] 아두이노짱 23-09-15 315
질문 stm32 보드 ip주소 찾는법댓글[1] 라칸 23-09-13 67
질문 마이컴 종류 질문댓글[2] stevie8 23-09-12 122
질문 주파수 실수배 체배 관련문의댓글[6] 스쳐두임신 23-09-11 151
질문 스마트 창문 제작 중에 질문 있습니다!댓글[1] 이미지첨부파일 N8008 23-09-09 117
게시물 검색

2022년 1월 2월 3월 4월 5월 6월 7월 8월 9월 10월 11월 12월
2021년 1월 2월 3월 4월 5월 6월 7월 8월 9월 10월 11월 12월
2020년 1월 2월 3월 4월 5월 6월 7월 8월 9월 10월 11월 12월
2019년 1월 2월 3월 4월 5월 6월 7월 8월 9월 10월 11월 12월
2018년 1월 2월 3월 4월 5월 6월 7월 8월 9월 10월 11월 12월
Privacy Policy
MCU BASIC ⓒ 2020
모바일버전으로보기