Hi to all.
I have a sneaky problem with Arduino initial pin settings. When the program starts, it should put a pin to 0 accordingly with the initial program flag status. This signal will change the on/off status (i.e. powered status) of a micro relay activated by a NPN 2222 transistor. The circuit part works perfectly and the initialisation code is the following:
int powerStatus;
void setup() {
pinMode(8, OUTPUT); // Relay ON/OFF
pinMode(7, INPUT); // Power Button
powerStatus = 0; // Initial power status relay
// Power OFF the relay
digitalWrite(8, 0);
}
What I expect is that the relay is intially in the OFF state.
Then in the loop function every time that a pushbutton is pressed the state is changed from ON to OFF and vice versa. This works without problems but when the Arduino board is powered and the program starts, the relay is powered.
The loop test program is the following:
void loop() {
// Check if the button is pressed
if( (digitalRead(7) == 0) {
// Invert the power status of the relay
if(powerStatus == 0)
powerStatus = 1;
else
powerStatus = 0;
// Power ON or OFF the relay
digitalWrite(8, powerStatus);
delay(500);
}
}
Some ideas where I have done mistakes ?
Thanks in advance. Enrico
FOUND THE MISTAKE
The relais works in negative logic driver by the NPN 2222 transistor controlled by pin 8: means that as a matter of fact, when the pin has the logical value 1 there is no activity on the transistor, there is no GND to the relay and it is OFF. The following is the working code including a serial monitor to see how the operation works.
#include <Streaming.h>
int powerStatus;
#define RELAY_ON 0
#define RELAY_OFF 1
void setup() {
pinMode(8, OUTPUT); // Relay ON/OFF
pinMode(7, INPUT); // Power Button
// First, setup the relay
powerStatus = RELAY_OFF; // Initial power status realis
digitalWrite(8, powerStatus);
// Init serial and dump setup status
Serial.begin(19200);
Serial << "setup() - START" << endl;
Serial << "powerStatus = " << powerStatus << " - written to pin 8 (relay)" << endl;
Serial << "setup() - END" << endl << endl;
}
void loop() {
if(digitalRead(7) == 0) {
if(powerStatus == RELAY_ON)
powerStatus = RELAY_OFF;
else
powerStatus = RELAY_ON;
digitalWrite(8, powerStatus);
Serial << "powerStatus = " << powerStatus << " wrtieen on pin 8 (relay)" << endl;
delay(1000);
} // button pressed
} // loop
Message was edited by: Enrico Miglino