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 incorrect code, problems in the wiring, or 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. However, we have several ways to debug Arduino code when it does not work as expected.

  1. 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.
  2. 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.
  3. Use Serial.println(): We can use it for two purposes:
    • Use it to print tracks the flow of your code. You can know whether your code runs into some places (inside if, else, for, while...) or not.
    • 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)

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
Please note: These are affiliate links. If you buy the components through these links, We may get a commission at no extra cost to you. We appreciate it.

The Best Arduino Starter Kit

※ OUR MESSAGES