Hello all, I'm trying to figure out how to use my current Tinkercad configuration to have the distance read from an ultrasonic sensor and cause a DC motor to spin faster based on this distance. I've experimented with it and used the digitalWrite command but I understand that this does not change the RPM of the motor of PWM, so I am sort of lost because analogWrite has not worked either (I've tried connecting to the analog pins too). I am only two weeks into using anything related to Arduino and Tinkercad so I apologize if my ignorance is showing here. I would appreciate any help! Below is my circuit and my code.
#define echoPin 2 // attach pin D2 Arduino to pin Echo of HC-SR04
#define trigPin 3 //attach pin D3 Arduino to pin Trig of HC-SR04
long duration;
int distance;
int pinNum = 13;
const int pinPi = 12;
const int motor = 7;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(pinNum, OUTPUT);
pinMode(pinPi, OUTPUT);
pinMode(motor, OUTPUT);
Serial.begin(9600);
Serial.println("Ultrasonic Sensor HC-SR04 Test");
Serial.println("with Arduino UNO R3");
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
if(distance <= 80) {
digitalWrite(pinNum, HIGH);
delay(300);
digitalWrite(pinNum, LOW);
delay(300);
digitalWrite(pinNum, HIGH);
delay(300);
digitalWrite(pinNum, LOW);
tone(12 ,200 ,200);
delay(100);
}
else if (distance <= 140) {
digitalWrite(pinNum, HIGH);
delay(750);
digitalWrite(pinNum, LOW);
delay(750);
digitalWrite(pinNum, HIGH);
delay(750);
digitalWrite(pinNum, LOW);
tone(12 ,200 ,100);
delay(300);
}
else {
digitalWrite(pinNum, HIGH);
delay(1200);
digitalWrite(pinNum, LOW);
tone(12 ,200 ,100);
delay(500);
}
}