Certainly! To properly interrupt and close the serial port, you can incorporate functionality that allows the user to signal when they want to stop reading and close the port. A common way to achieve this is by listening for a specific event (like a button click) to stop the reading loop.
Here's an updated version of the code that includes a way to interrupt the reading process and close the port properly:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Serial Port Example</title>
</head>
<body>
<button id="startButton">Open Serial Port</button>
<button id="stopButton" disabled>Close Serial Port</button>
<pre id="output"></pre>
<script>
let port;
let reader;
let reading = false; // Flag to control the reading loop
const decoder = new TextDecoder();
document.getElementById('startButton').addEventListener('click', async () => {
if (!navigator.serial) {
console.error('Web Serial API not supported in this browser.');
return;
}
// Request a port and open a connection
port = await navigator.serial.requestPort();
await port.open({ baudRate: 9600 });
// Get a reader from the port's readable stream
reader = port.readable.getReader();
reading = true;
document.getElementById('startButton').disabled = true;
document.getElementById('stopButton').disabled = false;
readSerial();
});
document.getElementById('stopButton').addEventListener('click', async () => {
reading = false; // Stop the reading loop
await closePort(); // Close the serial port
});
async function readSerial() {
try {
while (reading) {
const { done, value } = await reader.read();
if (done) {
console.log('Stream closed');
break;
}
const chunk = decoder.decode(value, { stream: true });
document.getElementById('output').textContent += chunk; // Display received data
}
} catch (error) {
console.error('Error reading from serial port:', error);
} finally {
if (reading) {
await closePort();
}
}
}
async function closePort() {
if (reader) {
reader.releaseLock();
}
if (port && port.readable) {
await port.close();
}
document.getElementById('startButton').disabled = false;
document.getElementById('stopButton').disabled = true;
console.log('Port closed');
}
</script>
</body>
</html>
Explanation of Changes:
- HTML Structure: Added two buttons (
Open Serial Port and Close Serial Port) to control opening and closing the serial port.
reading Flag: A boolean flag (reading) is used to control whether the loop should continue reading data from the serial port.
- Button Handlers:
- The
startButton handler opens the serial port, starts reading, and disables itself while enabling the stopButton.
- The
stopButton stops the reading loop by setting reading to false and calls closePort() to close the port.
readSerial Function: This function handles reading from the serial port and updates the display with received data. It exits the loop cleanly if reading is set to false.
closePort Function: This function releases the reader lock and closes the serial port, resetting the button states afterward.
Usage:
- Click the "Open Serial Port" button to start reading data from the selected serial port.
- Click the "Close Serial Port" button to stop reading and close the port properly.
This setup ensures that you can interrupt the reading process cleanly and manage the serial port's lifecycle correctly.