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);
}}}
There are a few things wrong with this part aside from the previously mentioned errors with the if statement. '1' and 1 are the not the same as far as the micro controller goes, so it would be best not to mix them like you've done here. If a is '1', then you increment it (you don't need the parenthesis surrounding a++ by the way) to '2'. Now you are comparing it to 2. 2 and '2' are not the same. So say that issue is also fixed, you then run into a logical error of what happens the next time you hit the button after your reset a to '0'?
Jaks13:
Okay, this is what I changed, but I'm not sure what you meant by caomparing the 2 and '2'
First off, your coding style makes this very difficult to read. Use the Tools > Auto Format before posting your code to save our sanity.
2 and '2' are not equal. '2' is a character representation of 2 and has the equivalent decimal value of 50. When you fix the later mentioned error, you'll notice that if (a > 1) will always be true because anything you type into the serial monitor will have a binary value greater than 1. http://www.asciitable.com/
a = Serial.read();
if (a == '1')
{
a++;
}
if (a > 1)
{
a == 0;
}
You're mixing = and == again. If you want to set the value of the left side variable, use =. If you want to compare the value on the left side to the value on the right side, use ==.