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:

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.

  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 Amazon affiliate links. If you buy the components through these links, We will get a commission at no extra cost to you. We appreciate it.

    The Best Arduino Starter Kit

    ※ OUR MESSAGES