In several Arduino forums (eg. https://forum.arduino.cc/t/toggling-a-pin-state/115718) I see that one can toggle the state of a GPIO pin by using:
Code: Select all
digitalWrite(pinToToggle, !digitalRead(pinToToggle));
Code: Select all
#define PUMP_ON 0 // Pump on/off output signal on D0 (RX), controls power supply to pump
...
// In Setup...
pinMode(PUMP_ON,OUTPUT); //Pump on control signal is an output
digitalWrite(PUMP_ON,LOW); //start with it off
...
// In keyboard input routine every time I enter a "p"
...
Serial.print("\tPreToggle PUMP_ON: "); Serial.println(digitalRead(PUMP_ON)); //call this line 1
digitalWrite(PUMP_ON,!digitalRead(PUMP_ON)); //call this line 2
Serial.print("\tToggled PUMP_ON to "); Serial.println(digitalRead(PUMP_ON)); //call this line 3
...
PreToggle PUMP_ON: 0
Toggled PUMP_ON to 0
The next time I execute I get:
PreToggle PUMP_ON: 1
Toggled PUMP_ON to 0
The scope shows the pin voltage toggling every time but the digitalRead() in line 3 does not seem to consistently reflect the state of the pin.
I tried it using pin 13 instead of pin 0 to avoid any conflict with the Serial port, but the behavior was the same. I want to use pin 0 as I'm running out of pins. I also want to use this logic for other pins. Could it be a timing issue? Maybe my hardware setup is not holding the HIGH on the pin steady enough (though it appears high on the scope)?
I'm a hardware noob, so I'm not confident in my setup, shown below. Pin 0 (brown wire) goes to the base of a TIP210G NPN transistor. Do I need some sort of pull-down resistor in there somewhere? The collector (red jumper) is connected to a 24V rail with plenty of oomph to drive the pump. The emitter (blue wire) is just connected to the scope right now, eventually it will be to the hot lead of the pump.
Thanks for your thoughts and input...