Saturday, January 21, 2023

Python Flask Buttons to send serial command

 You can use Python Flask to create buttons on a web page that send serial commands to a device connected to your computer. Here's an example of how you might do this:

from flask import Flask, render_template import serial app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/send_command/<command>') def send_command(command): ser = serial.Serial('COM3', 9600) # Change the port name and baud rate as per your device ser.write(command.encode()) # send the command over the serial connection ser.close() return 'Command sent: {}'.format(command) if __name__ == '__main__': app.run(debug=True)

In this example, the index route renders an HTML template (index.html) that contains buttons. Each button has a link to the /send_command/<command> route, where <command> is a placeholder for the command to be sent over the serial connection. When a button is clicked, the browser sends a request to the corresponding /send_command/<command> route, which sends the command to the device using the serial library.

You can also pass the command from the HTML template using POST method and handling it in the flask app.

The HTML template might look something like this:

<button><a href="{{ url_for('send_command', command='on') }}">Turn On</a></button> <button><a href="{{ url_for('send_command', command='off') }}">Turn Off</a></button>


You can customize this example to send different commands based on the button clicked and also change the design of the buttons as per your requirement. Please let me know if you have any questions or any specific requirement.

No comments:

Post a Comment