Arduino code does not work when switching from USB to power supply

My Arduino connects to sensors. It works well when connecting Arduino to PC via USB cable. However, when I disconnect Arduino from PC and power it via 5V power adapter or 5V battery, it does not work. How to solve it?

Answer

There are two possible reasons:

  1. Arduino code run before sensors are initialized.
  2. Power is not enough for sensors.

We need to check one by one. Let's see how to solve them.

Arduino code run before sensors are initialized

Some sensors that communicates with Arduino via SPI, I2C or UART needs time to initialized.

  • When you power Arduino from PC via USB cable, this problem does not happen. That is because the sensor was initialized before you upload Arduino code to Arduino board.
  • When you power Arduino from a power supply (not from PC), Arduino and sensor is started at the same time. However, sensors take longer time to initialize. Arduino code in the setup() function try to connect to sensors when sensors are NOT ready ⇒ it does not work.

Solution

Add a delay at the beginning of the setup() function of Arduino code. It looks like below:

// YOUR CODE void setup() { delay(500); // waiting for sensors initialized // YOUR CODE } void loop() { // YOUR CODE }

Power is not enough for sensors.

If you power Arduino via DC Jack or Vin pin by 5V power adapter or 5V battery, The power will go though a voltage regulator. The voltage in 5V pin of Arduino will be dropped below 5V, because of the voltage regulator ⇒ If sensors are powered from 5V pin of Arduino, it may not work because voltage is not big enough.

Solution

There are two ways:

  • Change power supply: Use a higher voltage power supply (from 7V to 12V).
  • Keep 5V power supply: Power sensors directly from the 5V power supply, not from 5V pin of Arduino

In case you use battery, please make sure that the current is big enough for your system.

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