1.  connect() false


 java.io.IOException: read failed, socket might closed, read ret: -1.


안드로이드 기본 예제인 bluetooth chat을 활용하여 개발하였으나 다음과 같은 에러가 발생하였다.


<해결방법>


①createBluetoothSocket 함수를 선언한다.

private BluetoothSocket createBluetoothSocket(BluetoothDevice device)
    throws IOException {
    if(Build.VERSION.SDK_INT >= 10){
        try {
            final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
            return (BluetoothSocket) m.invoke(device, mMyUuid);
        } catch (Exception e) {
            Log.e(TAG, "Could not create Insecure RFComm Connection",e);
        }
    }
    return  device.createRfcommSocketToServiceRecord(mMyUuid);
}


② 다음과 같이 수정한다.


이 코드를 지우고

tmp = device.createRfcommSocketToServiceRecord(MY_UUID);

아래 코드로 수정한다.

tmp = createBluetoothSocket(mmDevice);



출처 : https://stackoverflow.com/questions/18657427/ioexception-read-failed-socket-might-closed-bluetooth-on-android-4-3/25647197#25647197

   http://solderer.tv/data-transfer-between-android-and-arduino-via-bluetooth/






2. connect() false


1번을 하니 에러 내용이 조금 바뀌였다.


bluetoothsocket.connect read failed, socket might closed or timeout



<해결 방법>


①아두이노와 블루투스 통신을 하는 안드로이드 앱 개발시 UUID는 다음과 같이 지정해주어야 한다.


private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");



샘플 코드는 언제 분석하지.


기본기가 너무 부족하다.


안드로이드 앱 블루투스 연결 가이드

http://dsnight.tistory.com/36 


0. 개요


이번 포스팅의 목표는 아두이노로 mySQL에 접속하는 것 입니다.


아두이노에 esp8266을 달아서 와이파이에 접속하고, php와 연동하여 mySQL의 데이터에 접근할 것입니다.


다음과 같은 사항은 이미 준비되어 있다는 가정 하에 진행하도록 하겠습니다.


AT명령어를 통해 와이파이에 연결이 가능한지는 코드로도 확인할 수 있습니다.



  • esp8266 펌웨어 완료
  • AT명령어를 통해 와이파이에 연결하기
  • 웹 호스팅 되어있음



다른 분들이 설명을 잘 해주셔서 링크 걸어 두겠습니다.


①김민정님 <ESP8266 사용을 위한 펌웨어 업데이트하기>

esp8266 펌웨어 - http://www.makewith.co/page/project/1004/story/2358/



②코코아팹 <esp8266으로 wifi 연결하기>

AT명령오를 통해 와이파이 연결하기 - https://kocoafab.cc/tutorial/view/625



③웹 호스팅

저는 닷홈에서 무제한 웹호스팅 을 사서 썼습니다.







1. 코드 작성하기



newfile.php를 작성합니다. 


해당 페이지를 접속하게 되면 example이라는 테이블에 GET방식으로 전달받은 num값이 추가되게 됩니다.


데이터베이스에 테이블(example)과 속성을 미리 만들어 놓아야 하겠지요.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?php
 
$db_host = "localhost";
$db_user = "유저명 ";
$db_passwd = "비밀번호";
$db_name = "디비 명";
 
 
// MySQL - DB 접속.
 
$conn = mysqli_connect($db_host,$db_user,$db_passwd,$db_name);
 
if (mysqli_connect_errno()){
    
    echo "MySQL 연결 오류: " . mysqli_connect_error();
    
    exit;
    
else {
    
    echo "DB : \"$db_name\"에 접속 성공.<br/>";
    
    $num=$_GET["num"];
    $sql = "INSERT INTO example VALUES($num)";
    $result = mysqli_query($conn, $sql);
    
    mysqli_close($conn);
    
}
cs







②아두이노에 다음과 같은 코드를 업로드합니다.


아두이노 메가를 기준으로 적성되었습니다. 


우노를 쓰고 계시거나 다른 핀을 RX/TX 로 사용하고 싶으신 분은 소프트웨어 시리얼을 사용하여 코드의 일부를 수정하여야 합니다. 


메가를 기준으로 esp8266의 TX는 아두이노의 RX1에, 아두이노의 TX1는 esp9266의 RX에 교차하여 꼽으세요.


코드를 보면 아시겠지만, 아두이노와 esp8266이 시리얼 통신을 통해 데이터를 주고 받고 있습니다.


아두이노에서 시리얼통신을 통해 esp8266에 AT커멘드를 전송하고 esp8266의 응답을 대기합니다. 응답이 온다면 아두이노의 시리얼창에 출력하는 구조입니다.


천천히 따라가면서 공부하면 금방 이해하실 수 있습니다.


자세한 사항은 AT명령어를 확인해가면서 공부해보시길 바랍니다.


잘 정리되어 있어 링크 걸어둡니다.

esp8266 AT명령어 - https://room-15.github.io/blog/2015/03/26/esp8266-at-command-reference/



※주의사항

1. sendData함수에서 딜레이 시간을 조금씩 줄여가면서 맞춰주세요. 너무 짧은 시간을 주면 연결이 되지 않을 수 있습니다.


2. 명령어에 띄어쓰기가 틀리지 않게 주의해주세요.


3. newfile.php는 php폴더에 포함된 파일이므로 GET /php/newfile.php?num=20 로 작성되었습니다. 자신이 만든 php폴더의 위치에 맞게 경로를 수정하세요.

                                     (파일 위치 ==>도메인/php/newfile.php)


4. 업로드가 중단되면 RX, TX 핀을 뽑은 후 업로드하고 업로드가 완료되면 꼽으세요.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <string.h>  
  
///////////////////////////////////////////  
#include <SoftwareSerial.h>  // 소프트웨어 시리얼 라이브러리
    
///////////////////////////////////////////  
 
#define DEBUG true
 
void setup() {
 
  Serial.begin(9600);
  
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial1.begin(9600);
  sendData("AT+RST\r\n"5000, DEBUG); // rst
  sendData("AT+CWJAP=\"와이파이 이름\","와이파이 비밀번호\"\"\r\n"15000, DEBUG); //enter name and password
}
 
void loop() {
  int key;
  sendData("AT+CWMODE=3\r\n"11000, DEBUG); //  access point
  sendData("AT+CIFSR\r\n"7000, DEBUG); // get ip address
  sendData("AT+CIPMUX=1\r\n"7000, DEBUG); // configure for multiple connections
  sendData("AT+CIPSTART=4, \"TCP\",\"도메인\",80\r\n"5000, DEBUG); // turn on server on port 80
  
  String web = "GET /php/newfile.php?num=20 ";
 
  web += "HTTP/1.0\r\n";
  web += "Host: 도메인\r\n";
  web += "\r\n";
  web += "\r\n";
  
  String cipsend = "AT+CIPSEND=";
  cipsend += 4;
  cipsend += ",";
  cipsend += String(web.length());
  cipsend += "\r\n";
  sendData(cipsend, 5000, DEBUG);
  sendData(web, 5000, DEBUG);
  String closeCommand = "AT+CIPCLOSE=";
  closeCommand += 4;// append connection id
  closeCommand += "\r\n";
  sendData(closeCommand, 3000, DEBUG);
}
 
String sendData(String command, const int timeout, boolean debug) {
  String response = "";
  Serial1.print(command); // send the read character to the esp8266
  long int time = millis();
  while ( (time + timeout) > millis()) {
    while (Serial1.available()) {
      // output to the serial window
      char c = Serial1.read(); // read the next character.
      response += c;
    }
  }
  if (debug) {
    Serial.print(response);
  }
  return response;
}
 
cs






③결과 화면





2. 마침


이상으로 포스팅 마칩니다.


esp8266은 저렴한 가격 대신 굉장히 까다로운 모듈입니다. 게다가 자료도 충분하지 않습니다. 중국산이라 그런지 되고싶을때 되고 되기 싫을땐 안됩니다.


가장 많이 시도한 해결법은 선 뺐다가 꼽기였습니다. 실제로 뺐다가 꼽으면 다 해결 됩니다. 


언제 망가질지 모르니 여분의 모듈을 챙겨두는 것도 방법이라고 생각합니다.


부족한 글 읽어주셔서 감사합니다. 질문사항이나 피드백, 지적은 감사히 받겠습니다.

+ Recent posts