Author Topic: C Code Questions  (Read 2776 times)

0 Members and 1 Guest are viewing this topic.

Offline MilesTopic starter

  • Full Member
  • ***
  • Posts: 49
  • Helpful? 1
C Code Questions
« 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)???

Offline Webbot

  • Expert Roboticist
  • Supreme Robot
  • *****
  • Posts: 2,165
  • Helpful? 111
    • Webbot stuff
Re: C Code Questions
« Reply #1 on: February 04, 2009, 08:15:04 PM »
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)'

Quote
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
Webbot Home: http://webbot.org.uk/
WebbotLib online docs: http://webbot.org.uk/WebbotLibDocs
If your in the neighbourhood: http://www.hovinghamspa.co.uk

Offline robotcoder

  • Full Member
  • ***
  • Posts: 53
  • Helpful? 0
    • www.RobotCoder.com (underconstruction)
Re: C Code Questions
« Reply #2 on: February 05, 2009, 12:43:48 AM »
You can also use ">=" (greater than or equal), "<=" (less than or equal), or "!=" (not equal) in your if statements.

Offline Dscrimager

  • Full Member
  • ***
  • Posts: 57
  • Helpful? 0
Re: C Code Questions
« Reply #3 on: February 05, 2009, 07:35:58 AM »
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

Offline jka

  • Full Member
  • ***
  • Posts: 78
  • Helpful? 4
Re: C Code Questions
« Reply #4 on: February 05, 2009, 07:41:57 AM »
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.

 

SMF spam blocked by CleanTalk