I'm using Arduino Uno controller

How it is possible to know if controller connected to PC via USB, to detect if wire is plugged and get condition for variable in sketch.

I've tried Serial.available(), but I'm not sure, if I can do it this way:

if (Serial.available()) 
   val = true; 
   val = false; 

I want use this condition to avoid setup() commands by some unexpected reason in case if controller powered only with adapter

  • I don't know the answer of the problem, but your code can be rewritten to a shorter and equally functional val = Serial.available(); – Michel Keijzers May 31 '19 at 13:47
  • you can do another thing like you continuously send some random data over serial. when arduino is connected to the PC it will receive same data from arduino, indicating arduino is connected to your PC. For reception point of view you can write some python script as well. – Vaibhav May 31 '19 at 16:18

You can't determine if there is a valid USB source on the UNO without modifications, because the Atmega328P just receives serial data when the host sends some data. Some approaches that you can keep in mind.

  1. If you want to determine whether you are connected through the USB or barrel connector, you can connect an analog pin to the Vin pin through a voltage divider (you should calculate the values so that you do not exceed 5V on the analog pin). This way if you detect a voltage greater than 6.6V you will know that you are being powered from the barrel jack.

  2. If you want to detect a particular PC, you can write a SW in the PC which scans for new ports, then opens them and sends a particular string. If you receive that within X seconds, you know that you are connected to the PC

  3. If you want to determine if you are connected to any valid PC, then I think you will need to modify the program in the Atmega16u2 which is used as a serial bridge between the two. I'm not sure whether it is possible or not, but I think that the Atmega16u2 knows when a valid USB session is started, and so can tell the Atmega328 this information (through the serial interface)

  • It's an ATMega16u2, not a ATMega32u4, that's on the Arduino UNO. Other than that, options 3 would be possible. – Gerben May 31 '19 at 14:20
  • 1
    @Gerben I was totally sure it was the same as on the Leonardo.. Goot catch, I fixed it in the answer. Thank you – frarugi87 May 31 '19 at 14:29
  • And older revisions were using ATMega8u2. Knockoffs started 8u2 or FTDI, ended with cheaper CH340G – KIIV May 31 '19 at 15:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.