Serial.println() stops randomly

Question: I’m writing a program that controls a servo and reads a PIR sensor at the same time; the servo knocks something over which the PIR sensor can detect. But as I was trying it out a problem emerged: At a random moment the program stops printing the value to the serial monitor. The LED indicating communication with the PC also stops blinking and the reset-button doesn’t work. I’m using Arduino Mega 2560. Does anyone know what I should do?

Here is the code:

#include <Servo.h>

Servo Servo1;

int inputPIR = 9;

int valPIR;

unsigned long servoState = 0;

unsigned long previousPrint = 0;

const long interval = 500;

void setup() {

Serial.begin(9600);

pinMode(inputPIR, INPUT);

Servo1.attach(11);

}

void loop() {

valPIR = digitalRead(inputPIR);

unsigned long currentMillis = millis();

if (currentMillis - previousPrint >= interval) {

previousPrint = currentMillis;

Serial.println(valPIR);

if (servoState == 0) {

servoState = 175;

}

else {

servoState = 0;

}

Servo1.write(servoState);

}

How are you powering the servo?

Does anyone know what I should do?

I'd check the wiring and power supply.

Which servo? How much current does it draw? How do you power it.

AWOL:
I'd check the wiring and power supply.

But we cannot ask about the wiring :frowning:

I'm not asking, I'm telling :smiley:

larryd:
How are you powering the servo?

sterretje:
Which servo? How much current does it draw? How do you power it.

AWOL:
I'm not asking, I'm telling :smiley:

The servo is powered by the board

I know, I should remove the 'don't ask about the wiring', cuz it's probably in the wiring I realise now

Use an external power supply GNDs connected.

QuinlanWolf-Charlie:
The servo is powered by the board

I know, I should remove the 'don't ask about the wiring', cuz it's probably in the wiring I realise now

The fact that you said that is what clued everyone into the fact that it's the wiring. To bad you edited your post though. Now the humor is gone.

ChrisTenone:
The fact that you said that is what clued everyone into the fact that it's the wiring. To bad you edited your post though. Now the humor is gone.

Hahahaha
waves hand
You don't need to see my wiring, move along

larryd:
Use an external power supply GNDs connected.

Why the external power supply? Is it too much for the board to handle if I run both a servo and a sensor/multiple sensors? This is the first time I'm using servo's so I'm a bit clueless about it.

Even small servos take an amp or so, far more than any Arduino board's 5V pin can source.

Also they may put inductive spikes and noise back onto their power supples, not a good idea for
any voltage rail that's also powering logic circuitry.