Script runs properly only if on USB power supply AND holding a finger on the USB

Hi all,

I am trying to setup a circuit where a brief 5V signal is sent to a DC motor as output after breaking one of two IR beams.
I am using Arduino UNO, IR LED and light-dependent resistors to create the IR beam circuit. The output is connected to a green LED at the moment to test the circuit.

The code is attached below, just for reference, but I am pretty sure the code is OK.

The reason I think that the code is OK (and the actual issue) is the following:

The code works only if I supply power through the USB and have my finger on top of the Arduino USB port.
If I have the USB cable plugged in but I do not touch the Arduino, the output gets triggered randomly now and then, without breaking the IR beams.

If I plug in a 9V/2amp power supply in the barrel jack, or if I use a 9V battery, the output is almost constantly ON, but flickering, again, without breaking of the IR beams.

Since the performance depends on the source of power and me holding a finger over the USB port (grounding issue?) I believe there is something wrong with the Arduino hardware itself.

Any suggestions are greatly appreciated!

int gatePin1 = 3; // gatePin refrs to the pin sendin the 5V to the transistor controlling the feeder DC motor
//int gatePin2 = 4;  //extra gatePin for two outputs
int LDR1 = A2;
int LDR2 = A3;
long LDR1value1, LDR1value2;
long LDR2value1, LDR2value2;

//trying to avoid delay()

unsigned long LDR1startMillis;
unsigned long LDR2startMillis;
//unsigned long Pin1startMillis;
unsigned long currentMillis;
const unsigned long period1 = 50;
//const unsigned long period2 = 75; //can use another timer to control the 5V output duration, but not necessary at this point

void setup(){
pinMode(gatePin1, OUTPUT);
//pinMode(gatePin2, OUTPUT);
pinMode(LDR1, INPUT);
pinMode(LDR2, INPUT);
Serial.begin(9600);
LDR1startMillis = millis();// avoiding delay()
LDR2startMillis = millis();
// Pin1startMillis = millis();
}

void loop(){

  currentMillis = millis();

  LDR1value1 = analogRead(LDR1);
  //delay(50);
  if (currentMillis - LDR1startMillis >= period1) //avoid delay()
  {
  LDR1value2 = analogRead(LDR1);
  LDR1startMillis = currentMillis;
  }
  
  LDR2value1 = analogRead(LDR2);
  //delay(50);
  if (currentMillis - LDR2startMillis >= period1) //avoid delay()
  {
  LDR2value2 = analogRead(LDR2);
  LDR2startMillis = currentMillis;
  }
 
  if (LDR1value2 - LDR1value1 > 10 || LDR2value2 - LDR2value1 > 10)
  {
    digitalWrite(gatePin1, HIGH);
    delay(75);
    digitalWrite(gatePin1, LOW);
  }
}

It does sound more like a wiring issue from what you say.
A schematic might prove useful.

You may also have a loose USB port but a fine soldering iron would normally fix that.
Have had a Chinese clone with a bad USB port that actually fell off the first time I used it.

Bob.