How to debug Arduino code
My Arduino code does not work as expected. Could anybody tell me how to debug Arduino code?
The possible sources of bugs include:
- Syntax error in the code
- Incorrect logic in the code
- Wrong wiring
- Problems in sensors/actuators (broken, low quality ...).
We need to find the source of bugs and then fix it. Arduino IDE does not support real-time debugging with debugging points (New IDE supports real-time debugging ONLY for SAMD boards).
If it is a syntax error, Arduino IDE will outputs an error message. You can read the message and fix it. You can google it for solution.
If it is NOT a syntax error, we have to debug Arduino code. Below is a way to find the bug and fix it.
- Modularize the code: In the case, your code includes code for several sensors/actuators, separate the code into small parts for each single sensor/actuator. Run one by one. You will find where the bug comes from.
- Locate the bug position: by commenting line by line of code, from bottom to top. If your code is big, comment block by block of code, from bottom to top.
- Use Serial.println(): We can use it for two purposes:
- Use it to print the value of variables. You can see the value is normal or not (e.g state of a digital input pin when a button is pressed)
Several special bugs that is difficult to find
- If your Arduino code has switch-case statment, see Why Switch-Case statement does not work correctly?
- If your Arduino auto reboots, see Why Arduino automatically reboots?
- Wrong data type. For example" int time_ms = millis();. The correct data type should be: unsigned long time_ms = millis();
|1 × Arduino UNO Buy on Amazon|
|1 × USB 2.0 cable type A/B Buy on Amazon|
|1 × Jumper Wires Buy on Amazon|