How to debug Arduino code
My Arduino code does not work as expected. Could anybody tell me how to debug Arduino code?
Answer
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)
- 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();
Example code:
const int buttonPin = 2; // the number of the pushbutton pin
int buttonState = 0;
void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT);
Serial.println(F("##### SYSTEM STARTED #####"));
}
void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH) {
Serial.println(F("DEBUG: inside if"));
} else {
Serial.println(F("DEBUG: inside else"));
}
Serial.print(F("DEBUG: button state = "));
Serial.println(buttonState);
}
Several special bugs that is difficult to find
Buy Arduino
1 × Arduino UNO Buy on Amazon | |
1 × USB 2.0 cable type A/B Buy on Amazon | |
1 × Jumper Wires Buy on Amazon |
Disclosure: Some links in this section are Amazon affiliate links. If you make a purchase through these links, we may earn a commission at no extra cost to you.
Additionally, some links direct to products from our own brand, DIYables.
Additionally, some links direct to products from our own brand, DIYables.