fbpx

6.4 Coding

 


Steps to do coding in Arduino IDE

1. Open Arduino IDE and write the code.

 

Complete Code:

In this code, we will read the signal from the sound sensor and then give the count of the claps in the code.

  • If 1 time clap then the car will move forward.
  • If 2 time clap then the car will move backward.
  • If 3 time clap then the car will move in left direction.
  • If 4 time clap then the car will move in right direction.

Code as shown below: 

int m1a=10;
int m1b=9;
int m2a=8;
int m2b=7;

int sound = 10;
int st = 0;
int count = 0;

void setup()
{
//put your setup code here,to run once;
pinMode (sound, INPUT);
pinMode (m1a, OUTPUT);
pinMode (m1b, OUTPUT);
pinMode (m2a, OUTPUT);
pinMode (m2b, OUTPUT);
}
void loop()
{
//put your main code here,to run repeatedly;
if (digitalRead(sound) == HIGH) {
delay(10);
if (count == 0)
st = millis();
count = count + 1;
while (digitalRead(sound) != LOW) {
if (millis() – st > 2000) {
Serial.print(count);
Serial.println(” aplausos”);
doOrders(count);
count = 0;
}
}
}
if (millis() – st > 2000 && count != 0) {
Serial.print(count);
Serial.println(” aplausos”);
doOrders(count);
count = 0;
}
}
void doOrders(int apl) {
if (count==1)
{
digitalWrite(m1a,HIGH);

digitalWrite(m1b,LOW);

digitalWrite(m2a,HIGH);

digitalWrite(m2b,LOW);
}
else if (count == 2)
{
digitalWrite(m1a,LOW);

digitalWrite(m1b,HIGH);

digitalWrite(m2a,LOW);

digitalWrite(m2b,HIGH);
}
else if (count == 3)
{
digitalWrite(m1a,LOW);

digitalWrite(m1b,HIGH);

digitalWrite(m2a,LOW);

digitalWrite(m2b,LOW);
}
else if (count == 4)
{
digitalWrite(m1a,LOW);

digitalWrite(m1b,LOW);

digitalWrite(m2a,LOW);

digitalWrite(m2b,HIGH);
}
}

Note: All lines written in “// ” are comments which will not run with the code that is just to understand the statements written in the code.