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

TODAY5,025 TOTAL7,751,351
사이트 이용안내
Login▼/회원가입
최신글보기 질문게시판 기술자료 동영상강좌

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


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 로 지정하였습니다

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

댓글 3

조회수 8,083

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
전체 스위치 센서
질문게시판 목록
제목 작성자 작성일 조회
질문 아두이노 서보모터 연결 작동안함댓글[1] 이미지 토뭉이 23-08-19 3414
질문 아두이노 외부전원 인가 문제 해결방안...댓글[3] 나도할수있어아두 23-08-17 9599
질문 Arduino nano 33 iot 모듈 블루투스 통신댓글[5] 이미지첨부파일 senior 23-08-16 28118
질문 아두이노로 전달받은 값을 실시간으로 웹페이지와 연동댓글[1] 스냥 23-08-16 3331
질문 atmega128 여러개 RFID 연결댓글[1] 강민준 23-08-15 3278
질문 ATmega128A UCSR1A Register 질문 mustbe 23-08-14 1959
답변 답변글 답변 : ATmega128A UCSR1A Register 질문 master 23-08-14 2034
현재글 아두이노 블루투스모듈(HC-06) 모바일 값 전송 질문댓글[3] 이미지첨부파일 소오금 23-08-13 8084
질문 I2C통신 연결 시리얼값오류 도와주세요댓글[12] 매드닥터 23-08-12 83387
질문 로드셀, 온습도센서 코드 합치기댓글[2] 생물공학도 23-08-11 5151
질문 stm uart통신 질문댓글[3] stevie8 23-08-11 7964
질문 아두이노 코드 오류 문의댓글[10] 생물공학도 23-08-10 79553
질문 데이터 수신 stm 보드댓글[1] stevie8 23-08-09 3408
질문 lwip tcp server를 할때댓글[6] 라칸 23-08-09 37805
질문 mfc 코드 질문댓글[4] stevie8 23-08-09 19216
질문 UART 통신 질문입니다.댓글[4] 이미지 adoui 23-08-08 20547
질문 NODE MCU AMICA ESP8266 5V연결 가능합니까?댓글[2] 이미지첨부파일 hmkim 23-08-08 6555
질문 통신이 안되는이유 코딩이 잘못된건가요? i2c통신중댓글[1] 매드닥터 23-08-08 3059
질문 stm 매트릭스 키패드댓글[6] stevie8 23-08-07 36675
질문 atmega128 ADC 입력2개 받기 질문댓글[7] 이미지첨부파일 fizzult 23-08-06 46632
질문 i2c 통신댓글[1] 매드닥터 23-08-04 2478
질문 pixy2 사용자입니다댓글[1] 아두이노짱 23-08-02 2186
질문 아두이노 코드 관련 질문댓글[3] 이미지첨부파일 생물공학도 23-08-02 6570
답변 답변글 답변 : 아두이노 코드 관련 질문댓글[1] 알토이드 23-08-03 2110
질문 loop 문 관련댓글[1] 중독아두이노 23-08-02 1878
질문 NEMA17 여러개 구동 이슈댓글[3] 이미지첨부파일 kksp12y 23-08-02 4048
질문 아두이노 서보모터 블루투스 제어댓글[3] rnqudah 23-08-01 7105
질문 코드 합치는것 질문 드립니다.댓글[2] 중독아두이노 23-08-01 2371
질문 ATMEGA128 LED 제어 질문댓글[2] 이미지첨부파일 mango 23-07-22 3940
질문 atmega128 led 제어 질문댓글[2] 이미지 mango 23-07-20 3879
게시물 검색

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
모바일버전으로보기