Hi all. I've been having some difficulties with this issue and I can't find a good source to explain me what to do in this situation, so I decided to post it here as it has solved some other problems that I had in the past.
What I'm trying to do here is to make work a DC motor by pressing one of the keys of the computer keyboard (number 1), and turning it off with the same key. To do that, what I do is create a variable, and when I press the key, add 1 to that variable.
Now the variable is equal to 1.
Once I press again the same key on the pc computer, the variable should reset to 0 so the motor stops, but this is where I fail to program.
I know there's various options, like when the variable surpases a certain number reset it back to 0 (what I tried), but It doesn't seem to work.
I use Arduino UNO and Motor shield R3 if that helps. If you need anything else, just ask. Thank you!
Here's the code:
void setup()
{
Serial.begin(9600);
pinMode(12, OUTPUT); //Initiates Motor Channel A pin
pinMode(9, OUTPUT); //Initiates Brake Channel A pin
Serial.println("apreta 1 per anar endavant");
Serial.println("apreta 2 per anar endarrere");
}
void loop()
{
char a = 0;
if (Serial.available() > 0)
{
a = Serial.read();
if (a == '1')
{(a++);
if(a=2){
a = 0;}
}
if (a=1) {
digitalWrite(12, LOW); //Establishes forward direction of Channel A
digitalWrite(9, LOW); //Disengage the Brake for Channel A
analogWrite(3, 123); //Spins the motor on Channel A at half speed
}
if (a=0) {
digitalWrite(9, HIGH);
}}}