Over the past week, I revamped the code for the Arduino switch box project I started in April of last year. Before I talk about the improvements in XArduino 2.0, it is important to understand the motivations behind these changes. At some point between April and the end of the 2012, I stopped using my Arduino switch box due to performance issues. Those issues were as follows:
- Generally poor performance causing low FPS
- Intermittent lag between switch action, and dataref change or command execution (multiple seconds)
- High frequency of malformed output
I’ll talk about how I addressed each of these problems below.
Bitwise functions in lieu of string manipulation
While comma-separated text may offer a simple solution for spreadsheet standardization, parsing comma-separated data every frame can cause some lag. In the first release of XArduino, the output looked something like this:
1 |
H,0,0,0,1,0,0,0,0 |
Once the “H” was detected, the Python code would read all the data between that letter and the carriage return at the end of the string. Next, Python would check the integrity of the string by ensuring there was a comma every other character, and the line length was the appropriate number of characters. Each value in the string represented the switch position (0 = first position, 1 = second position, etc.).
Only one piece of this methodology was reused in XArduino 2.0. The string still starts with a single letter and ends with a carriage return, but instead of displaying each switch position in a comma-separated string, the switch positions are stored in a 16-bit number on multiple lines (if necessary). Multiple lines are necessary when using more than 16 two-position switches because the Arduino Uno and Mega are both limited to 16-bit numbers. The switch positions are decoded from the number using bitwise operators.
Continuous output vs. event-driven output
In XArduino 1.0, a new line was outputted every 50 ms regardless of whether or not a change had occurred. In XArduino 2.0, a new line is only generated when a switch position changes. This prevents the intermittent, but significant, lag associated with Arduino’s internal caching mechanism. To deal with the limited potential for malformed lines, each time a change occurs, the string is outputted three times. Increasing the baud rate also helped deal with the frequency of malformed lines. Together, these changes also generally improved performance.
What’s new in XArduino 2.0
- Improved performance by 50-100% (i.e. no measurable impact on FPS)
- Allow multiple commands per switch position
- COM port and baud rate set in configuration file instead of code
- Moved from string-based output to 16-bit numbers
- Fixed majority of malformed lines in communication between Arduino and pyserial
- Fixed delay in switch command/dataref by preventing endless polling
- Increased default baud rate to 56K
Source Code: https://github.com/cstrosser/XArduino/tree/release-2.0