Interrupting While Loop with Keystrokes
In a scenario where you're reading serial data and writing it to a CSV file using a while loop, you may want to provide users with the option to terminate the loop to stop data collection. This article explores techniques to implement such a feature without explicitly using keyboard interrupts.
One straightforward approach is to utilize the try-except block to handle a KeyboardInterrupt exception:
try:
while True:
# Do your serial operations here
except KeyboardInterrupt:
pass
In this case, pressing Ctrl-C (the usual key combination to raise KeyboardInterrupt) will cause the loop to exit gracefully. The exception is caught outside the loop, ensuring the script continues running even after loop termination.
As a note, using the opencv.waitKey() function, as seen in your code, will not work outside of GUI applications and is not recommended for this purpose.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3