const int ParkingBrake = 4;
int ParkingBrakeLight = 13;
int ParkingBrakeStatus = 0;
int ParkingBrakeState = LOW;
int ParkingBrakeLastState = LOW;
void setup() {
pinMode(4,INPUT);
pinMode(13,OUTPUT); // declare the LED's pin as output
Serial.begin(9600); // connect to the serial port
}
void loop () {
ParkingBrakeStatus = digitalRead(ParkingBrake);
if (ParkingBrakeStatus != ParkingBrakeLastState) {
Serial.write(1);
digitalWrite(ParkingBrakeLight,ParkingBrakeStatus);
ParkingBrakeState = ParkingBrakeStatus;
ParkingBrakeLastState = ParkingBrakeStatus;
}
delay(1);
}
I don't get it, when the switch is ON the if block always gets evaluated as true and it keeps writing over the serial port until i move the switch to OFF.
Could it be that the problem is in the code? Or maybe it's an electrical issue? I'm using a 1K ohms resistors (the only I have right now).
You want to set ParkingBrakeLastState to ParkingBrakeStatus on every pass through loop, not just when they are different. Using more meaningful names like currentStatus and previosStatus is better, in my opinion. How does ParkingBrakeState differ from ParkingBrakeStatus? Why do you need two variables with such similar names?
I'm using a 1K ohms resistors (the only I have right now).
Using it how? It's far simpler to connect one side of the switch to the pin and the other side to ground, and leave the resistor in the drawer. Turn on the internal pullup resistor, instead.
digitalWrite(ParkingBrake, HIGH); // after the pinMode statement.
What's the difference between ParkingBrakeState and ParkingBrakeStatus? It seems to me that one of them is redundant.
Although you're detecting input changes in a rather round-about way it looks as if it would work. You haven't described the external wiring, and I wonder whether you have a floating input and the state is genuinely flapping when you have the switch 'on'. With the code as it stands, it's hard to guess what's actually happening. Any particular reason you're writing binary values to the serial port instead of useful trace messages?