autonomous car

Hi All, I am doing a class project to successfully build a car to go around a track. Our first part of the project is to make the car stop when it senses a surface in front of it. I am having a little trouble with the code. We are using the GP2Y0A41SK0F sensor from sharp.

Here is my code so far.

int switchstate=0;
void setup()
{
pinMode(9,INPUT);
pinMode(10,INPUT);
Serial.begin (9600);
pinMode(pin,INPUT);
}

void loop()
{
switchstate= digitalRead(9);

if (switchstate=0)
{
analogWrite (9,100);
}

if (switchstate=1)
{
analogWrite(9,0);
}
}

Thanks

  if (switchstate=0)

You didn't say what trouble you were having, but that's likely to be it.

Please use code tags when posting code.

What is not happening? What should happen?

They shouldn't be assigning 0 and 1 to their variable :wink:

Well you don't say what trouble you're having but:

  • You're trying to write to pins that you had previously set as inputs; they need to be outputs
  • When you do a comparison like this, if (switchstate=0), you need a == thus: if (switchstate==0)
  • This: pinMode(pin,INPUT); tries to access a pin called pin but you didn't give the value pin a number.

Hi guys thanks for the quick response. My trouble is actually writing the code for the sensor to make the car stop. What is exactly the code to make the car stop.

We don't know, because we don't know how your car is wired.

BTW, if a digitalRead didn't return a zero, you can bet good money (assuming high school students are allowed to bet) that it returned a one; it isn't necessary to retest it, and a simple "else" will suffice.

You're trying to write to pins that you had previously set as inputs; they need to be outputs

The analogWrite() function makes the pin an OUTPUT pin.

switchstate= digitalRead(9);


  if (switchstate=0)
  {
    analogWrite (9,100);
  }

Aside from the problem with the = that should be an ==, you REALLY need to decide what is attached to pin 9. Is it an input device, where reading the pin makes sense? Or, is it an output device, where changing the duty cycle of the pin makes sense.

Both doesn't cut it.

PaulS:
The analogWrite() function makes the pin an OUTPUT pin.

Yeah my bad on that sorry. Just this very day I say a post which showed a snippet of the analogWrite code which shows the pinMode setting it as output.