NaroxEG

HC05 Flask LED Control

Jan 25th, 2025
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.85 KB | None | 0 0
  1. from flask import Flask, render_template, jsonify
  2. import serial
  3.  
  4. app = Flask(__name__)
  5.  
  6. bluetooth_port = 'COM3'
  7. baud_rate = 9600
  8.  
  9. try:
  10.     ser = serial.Serial(bluetooth_port, baud_rate)
  11. except serial.SerialException as e:
  12.     ser = None
  13.     print(f"Error: Could not open port {bluetooth_port}. {e}")
  14.  
  15.  
  16. @app.route('/')
  17. def index():
  18.     return render_template('index.html')
  19.  
  20.  
  21. @app.route('/led/on')
  22. def turn_led_on():
  23.     if ser:
  24.         ser.write(b'1')
  25.         return jsonify(status='LED On')
  26.     else:
  27.         return jsonify(status='Error: Could not open serial port'), 500
  28.  
  29.  
  30. @app.route('/led/off')
  31. def turn_led_off():
  32.     if ser:
  33.         ser.write(b'0')
  34.         return jsonify(status='LED Off')
  35.     else:
  36.         return jsonify(status='Error: Could not open serial port'), 500
  37.  
  38.  
  39. if __name__ == '__main__':
  40.     app.run(debug=True)
  41.  
Add Comment
Please, Sign In to add comment