Society of Robots - Robot Forum
Software => Software => Topic started by: Miles on February 04, 2009, 07:56:57 PM
-
Hello,
Just some questions about what i can/can't do with C.
I have built $50 robot and now making my own robots to do different things.
In the case that a sensor is greater than a value this symbol is used ">" e.g if(sensor > 87)
What symbol do i use to get the sensor on a particular value? because i have already tried " if (sensor = 87) " but AVR Studio won't let me write that.
Also how do i get the servo speeds e.g servo_left(25); to change due to sensor values? Do i put something like this servo_left(sensor - 20)???
-
The '=' sign is an assignment: ie 'int var = 1' wiil assign the value 1 to the variable called var. You are trying to do a comparison in which case use '==' ie 'if(sensor == 87)'
Also how do i get the servo speeds e.g servo_left(25); to change due to sensor values? Do i put something like this servo_left(sensor - 20)???
.
Yes
-
You can also use ">=" (greater than or equal), "<=" (less than or equal), or "!=" (not equal) in your if statements.
-
In fact = Versus == is a mistake that people make for a long time, even experienced coders. It pays to go back through your code and inspect to make sure that you have the right case that you are seeking.
You will see things like
if(blah = getsomething())
and they are being clever since it's an assignment and a logica statement in one. I would steer clear of that and use
blah = getsomething()
if(blah)
until you are really comfortable with C.
I think many compilers will warn of the assignment usage in logical contexts.
Doug
-
You can avoid this mistake when comparing with a constant and use if (2 == x) instead of if (x == 2). The point is, that if you miss one =, you get if (2 = x), which is an illegal statement and it will get caught by the compiler.