Audio controlled slot cars.

Hi.

I'm building a slot car track that is controlled by audio or rather by blowing on the microphone.
My problem is that the car runs very choppy sort of, like first not moving at all then going full speed
then really slow etc. Right now I'm not really sure why this is happening, if it's a problem with the
code, the track itself/powersupply or if my sound sensor isn't sensitive enough.

My circuit is kind of like this.

This is the the sound sensor I'm using.

And this is the code. Could the problem be that the code is sort of just sending current in an
on/off fashion and not scaleing like a dimmer for example.

int DO=2;  //Pin for Digital Output - DO
int DA=A1;  // Pin for Analog Output - AO
int led = 12;
int threshold = 520; //Change this
int sensorvalue=0;

void setup(){
  Serial.begin(9600);
  pinMode(led, OUTPUT);     
}

int v = 0;

void loop(){
  sensorvalue = analogRead(DA);  //Read the analog value
  Serial.print("Analog: ");  
  Serial.print(sensorvalue);  //Print the analog value
  Serial.print("  ");
  Serial.print("Digital: ");
  Serial.println(digitalRead(DO));  //Print the digital value
  
  
  if (sensorvalue >= threshold){
     analogWrite(led, sensorvalue / 4);
  }
  else
     analogWrite(led, 0);
}

Like always any help is appreciated. Thanks.

Try smoothing it. A simple way would be to just increment the PWM value by one if the sensor value is over your threshold and decrement if below.

You may need to read less frequently too - either delay with small values or better of course, the blink without delay technique.

Thanks for the help! Going to try it out right away. The PWM instance in this instance is the value I get from the
analog output right?

Not exactly - you're dividing it by four to get something in the PWM range - 0-255. For my suggestion, you can keep a variable in that PWM range and forget the division. Make sure you ensure that it is in that range though.