Why solenoid changes when I upload program to arduino or open serial monitor

I use BDW93C transistor control the states of 12DCV solenoid. Why the states of solenoid changes twice( turn on /off ) automatically when I upload the program to arduino mega 2560 or when I open serial monitor. I hope it can stay at LOW state before it is asked.

int H3PO4Solenoid=13;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(H3PO4Solenoid, OUTPUT);
digitalWrite(H3PO4Solenoid, LOW);
delay(2000);
}

void loop() {
// put your main code here, to run repeatedly:
digitalWrite(H3PO4Solenoid, HIGH);
}

when you upload or open the serial monitor, your Arduino resets

So unless you pull low or high your pins, when your Arduino resets you are in somewhat unchartered territory

Thanks for your reply, I am newb, I don't understand what you mean 'somewhat unchartered territory', how could I pull low or high your pins, when my Arduino resets?

Your sketch is setting the output pin LOW, waiting two seconds, and setting the output pin HIGH. If you don't want it to do that, DON'T DO THAT.

To put your pin in a known state while the Arduino resets: Add a 10K resistor between your output pin and Ground (LOW) or +5V (HIGH) depending on what state you want.

Thanks for your reply, I tried to connect 10K resistor between Pin 13 and GND, but it did work. the solenoid is still be turned on and turned off automatically. :frowning:

On my Uno, pin 13 (on board LED) flashes on reset. Maybe try the solenoid on a different pin?

Thanks !!! I change to Pin 12,it works correctly now !!!You really saved me !!

groundfungus:
On my Uno, pin 13 (on board LED) flashes on reset. Maybe try the solenoid on a different pin?