Code can run on tinkercad but not in arduino board

// C++ code
//
#include <Servo.h>

int DistanceIN = 0;

int DistanceOut = 0;

long readUltrasonicDistance(int triggerPin, int echoPin)
{
pinMode(triggerPin, OUTPUT); // Clear the trigger
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
// Sets the trigger pin to HIGH state for 10 microseconds
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
pinMode(echoPin, INPUT);
// Reads the echo pin, and returns the sound wave travel time in microseconds
return pulseIn(echoPin, HIGH);
}

Servo servo_9;

void setup()
{
pinMode(A0, OUTPUT);
servo_9.attach(9, 500, 2500);

}

void loop()
{
DistanceIN = 0.01723 * readUltrasonicDistance(12, 12);
DistanceOut = 0.01723 * readUltrasonicDistance(10, 11);
if (DistanceIN <= 30) {
tone(A0, 523, 5000); // play tone 60 (C5 = 523 Hz)
} else {
noTone(A0);
}
if (DistanceOut <= 30) {
servo_9.write(90);
} else {
servo_9.write(0);
}
delay(10); // Delay a little bit to improve simulation performance
}

I'm using this code to execute my project but nothing happened on my arduino yet in run on tinkercad.

Looks better this way

1 Like

Have you verified all hardware connections? How is your circuit powered? Can you post a schematic and clear photos of your circuit?

Have you tried putting in a Serial.print after the first if-statement in the main loop to verify you get there and one before it to see what kind of distance measurements you get?
Have you tried println-ing the raw values you get through readUltrasonicDistance?

Have you tried a very simple sketch that drives the servo without any if-conditions to verify you can successfully drive it from your Arduino?

1 Like

Hello @iceax, your topic has been moved to a more suitable location on the forum.

Can you please take some time to read How to get the best out of this forum and apply what you learned / read.

1 Like

Using the same pin for trigger and echo won't work.

What is connected to pin A0 to play the tone?

A schematic of the project would be helpful.

   DistanceIN = 0.01723 * readUltrasonicDistance(12, 12);
   DistanceOut = 0.01723 * readUltrasonicDistance(10, 11);

You need some temporal separation between pings or you are likely to get false echos. One rangefinder cannot distinguish its ping from an other's. I use 30 to 50 milliseconds between successive pings.

1 Like

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.