I am using an Arduino to control servo MX18A by serial, and trying to use computer to communicate with the Arduino by another serial to send commands to Arduino and change the servo control mode. Once the computer send a message to Aruduino, I hope it could response in time because may be there is something emergency like the servo being out of control ,under which circumstance I have to change the control strategy in time.
However, it seems like Arduinos like UNO, MEGA does not have serial interruption, so once the message from computer comes, it could not response in time.
I know that judging serial.available()
in every loop is one solution, but in my different servo control strategy there are many time delays, for
loops and while
loops, which means that I have to put serial.available()
in every time delay or for
loops, making the code hard to write and maintain.
2 Answers 2
It is not a case of "An Arduino" that can do serial interupts. All Arduino boards have serial interrupts, but they are already used to receive the data and store it in a buffer for you to consume when you have the time.
The Arduino API does not define any serial interrupt handling routines. That kind of thing is designed to be handled internally by the API code, not by the user. That's the whole point of the Arduino API - to abstract away such technicalities from the user.
If you want to use the serial interrupt yourself you will have to write your own serial handling code.
Or write your code in such a way that serial interrupts aren't needed.
-
How to write user-defined serial handling code and replace the original default code? Is there any interface for user to do that?scottxiao– scottxiao2018年06月12日 14:42:11 +00:00Commented Jun 12, 2018 at 14:42
-
2@bigxiao: Locate the file named "HardwareSerial.cpp" in the Arduino installation, copy it into your sketch's directory and tweak it to your needs.Edgar Bonet– Edgar Bonet2018年06月12日 14:47:22 +00:00Commented Jun 12, 2018 at 14:47
Why not use a timer to check if any data is in the serial buffer every say 2 seconds. The DUE has interrupts available on ALL pins so that could be a viable alternative solution. You shouldn't use blocking code anyway, e.g. whiles and delays.
-
Arduino DUE has serial interruption, which is open for users?scottxiao– scottxiao2018年06月12日 15:31:15 +00:00Commented Jun 12, 2018 at 15:31
-
It states that ALL digital pins on DUE work with interrupts so if you set an interrupt on a serial RX line it would trigger when data was received.Brian Moreau– Brian Moreau2018年06月13日 09:15:44 +00:00Commented Jun 13, 2018 at 9:15
for
andwhile
loops? They are common in code design, and both of them will takes some time and have the same effect as explicitdelay
.