[Python] am trying to get bluetooth data from arduino's HC-06. it says succeeded to connect...

Discussão em 'Python' iniciado por Stack, Julho 3, 2025.

  1. Stack

    Stack Membro Participativo

    trying to send and receive 3 float variable data, it says succeeded to connect but it didnt print any received data. I also tried to send and receive single char data but also failed. suceeded receiving data from my app made with mit app inventor so I think its problem of python(vs)

    vs code is here:


    import seriaㅣ
    import time

    bluetooth_port = '/dev/tty.HC-06' # macOS 포트명에 맞게 수정
    baud_rate = 9600

    try:
    bt = serial.Serial(bluetooth_port, baud_rate, timeout=1)
    print(f"[connected] port: {bluetooth_port}")

    while True:
    print(bt.readline())
    if bt.in_waiting > 0:
    line = bt.readline().decode(errors='ignore').strip()
    if line:
    parts = line.split(",")
    if len(parts) == 3:
    try:
    f1 = float(parts[0])
    f2 = float(parts[1])
    f3 = float(parts[2])
    print(f"received: {f1}, {f2}, {f3}")
    except ValueError:
    print("failed converting to real numbers:", parts)
    else:
    print("data type error:", line)
    time.sleep(0.1)

    except Exception as e:
    print("error:", e)

    finally:
    if 'bt' in locals() and bt.is_open:
    bt.close()
    print("port closed")


    and sketch code is here

    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    #include <SoftwareSerial.h>
    #include <DHT11.h>
    #include <Servo.h>
    Servo testservo;

    #define DHT 2
    #define DUST 8
    #define BUZZER 5

    #define BTtx A1
    #define BTrx A2
    SoftwareSerial BT(BTtx, BTrx);

    #if defined(ARDUINO) && ARDUINO >= 100
    #define printByte(args) write(args);
    #else
    #define printByte(args) print(args,BYTE);
    #endif

    //I2C LCD는 일반적으로 0x27혹은 0x3F입니다
    LiquidCrystal_I2C lcd(0x27, 16, 2);

    byte temperatureImage[] = {0x04,0x0A,0x0A,0x0A,0x0E,0x1F,0x1F,0x0E};

    byte humidityImage[] = {0x04,0x0E,0x0E,0x1F,0x1F,0x1F,0x1F,0x0E};
    byte doImage[] = {0x1C,0x14,0x1C,0x00,0x00,0x00,0x00,0x00};

    //LCD "m"
    byte microImage[] = {0x11,0x11,0x11,0x13,0x15,0x18,0x10,0x10};

    //LCD "3"
    byte threeImage[] = {0x18,0x04,0x18,0x04,0x18,0x00,0x00,0x00};


    //=====DHT
    float humidity = 0;
    float temperature = 0;

    DHT11 dht11(DHT);

    //=====DUST
    unsigned long duration;
    unsigned long starttime;
    unsigned long sampletime_ms = 2000;// 먼지센서의 샘플링시간을 2초로 설정합니다.
    unsigned long lowpulseoccupancy = 0;
    float ratio = 0;
    float concentration = 0;
    float dustDensity = 0;
    float dustState = 0;
    boolean DustCalculate_RUN = false;
    boolean DustCalculate_Done = false;
    unsigned int buzzer_count = 0;

    // 핀 초기화
    void initPin() {
    pinMode(DUST, INPUT);
    pinMode(BUZZER, OUTPUT);
    }

    // LCD 초기화
    void initLCD() {
    lcd.init();
    lcd.backlight();
    // 그림아이콘을 등록합니다.
    lcd.createChar(0, humidityImage);
    lcd.createChar(1, temperatureImage);
    lcd.createChar(2, doImage);
    lcd.createChar(3, microImage);
    lcd.createChar(4, threeImage);
    lcd.home();
    lcd.print("Loading...");
    }



    void printLCD() {
    //LCD에 먼지센서와 온습도센서를 출력합니다.
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print(dustDensity);
    lcd.write(3);
    lcd.print("g/m");
    lcd.write(4);
    lcd.setCursor(10, 0);
    if(dustState == 0) {
    lcd.print(" (^_^)");
    testservo.write(0);
    }
    else if(dustState == 1) {
    lcd.print(" (o_o)");
    }
    else if(dustState == 2)lcd.print(" (T.T)");
    else if(dustState == 3)lcd.print(" (ToT)");

    lcd.setCursor(0, 1);
    lcd.write(0);
    lcd.print(" ");
    lcd.print(humidity);
    lcd.print("% ");
    lcd.write(1);
    lcd.print(" ");
    lcd.print(temperature);
    lcd.write(2);
    lcd.print("C ");
    }

    void calcDustDensity() {
    duration = pulseIn(DUST, LOW);
    lowpulseoccupancy = lowpulseoccupancy + duration;

    if ((millis() - starttime) > sampletime_ms) {
    DustCalculate_RUN = false;
    DustCalculate_Done = true;

    ratio = lowpulseoccupancy / (sampletime_ms * 10.0); // Integer percentage 0=>100
    concentration = 1.1 * pow(ratio, 3) - 3.8 * pow(ratio, 2) + 520 * ratio + 0.62; // using spec sheet curve
    dustDensity = concentration * 100 / 13000;
    lowpulseoccupancy = 0;

    if(dustDensity > 150) buzzer_count = 3;
    else if(dustDensity > 80) buzzer_count = 2;
    else if(dustDensity > 30) buzzer_count = 1;
    else buzzer_count = 0;

    dustState = buzzer_count;
    }
    }

    /** 습도,온도 계산
    DHT온습도센서를 이용해서 온도와 습도를 계산합니다.
    */
    void calcHumidityAndTemperature() {
    dht11.read(humidity, temperature);
    }




    void send_bt() { //part for sending variables through bluetooth. every three variables are float
    BT.print(temperature);
    BT.print(",");
    BT.print(humidity);
    BT.print(",");
    BT.println(dustDensity);
    }

    void setup()
    {
    initPin();
    initLCD();
    starttime = millis();
    Serial.begin(9600);
    BT.begin(9600);
    testservo.attach(9);
    }

    void loop()
    {
    if(DustCalculate_RUN == true)
    {
    calcDustDensity();

    //미세먼지 측정 후에 온습도 측정 / LCD 표시
    if(DustCalculate_Done == true) {
    calcHumidityAndTemperature();
    printLCD();
    DustCalculate_Done = false;
    }
    } else {
    if (buzzer_count > 0 ) {
    digitalWrite(BUZZER, HIGH);
    delay(100);
    digitalWrite(BUZZER, LOW);
    delay(200);
    buzzer_count--;
    } else digitalWrite(BUZZER, LOW);

    if((dustState > 0 && buzzer_count == 0) || (dustState == 0))
    {
    DustCalculate_RUN = true;
    starttime = millis();
    }

    Serial.println(dustDensity);
    }
    send_bt();
    }

    Continue reading...

Compartilhe esta Página