The user wants working code for an ultrasonic sensor with Raspberry Pi that is compatible with the Wokwi simulator. The previous code is for actual Raspberry Pi hardware using RPi.GPIO, which won't work on Wokwi since Wokwi simulates Arduino and related environments but not Raspberry Pi.
So the key is: Wokwi does not support Raspberry Pi GPIO or Python code. It does support Arduino (C++), including simulation of HC-SR04 ultrasonic sensor.
Hence, to fulfill the request, I should provide a working Arduino code with wiring instructions suitable for the Wokwi simulator environment, where the ultrasonic sensor is simulated. This code can be copied into Wokwi and run successfully.
The user requested Raspberry Pi code that works in Wokwi, which is unrealistic because Wokwi does not support Raspberry Pi simulation. But the closest solution is Arduino code for HC-SR04 that works in Wokwi.
I will create a nice, modern, clean Arduino code for the HC-SR04 sensor for Wokwi. I will also describe how to set up the Wokwi project and run it.
Plan:
- Provide Arduino sketch code for HC-SR04.
- Tell user how to wire it in Wokwi.
- Mention how to simulate & see distance readings on Serial Monitor.
I will produce a single code file for Arduino that they can run as-is in Wokwi.
This approach is consistent since Wokwi supports Arduino but not Raspberry Pi simulation.
`ultrasonic_wokwi.ino`
```ino
/*
HC-SR04 Ultrasonic Sensor Example for Wokwi Simulator
Measures distance and prints it to the Serial Monitor.
Wiring in Wokwi:
- VCC to 5V
- GND to GND
- TRIG to Arduino digital pin 9
- ECHO to Arduino digital pin 10
This code sends Ultrasonic pulses and measures the echo to calculate the distance.
*/
const int trigPin = 9;
const int echoPin = 10;
long duration;
float distanceCm;
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.println("HC-SR04 Ultrasonic Sensor Test");
}
void loop() {
// Clear the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Trigger the sensor by setting the trigPin high for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance:
// Speed of sound wave divided by 2 (go and return)
distanceCm = duration * 0.0343 / 2;
// Print the distance in cm
Serial.print("Distance: ");
Serial.print(distanceCm);
Serial.println(" cm");
delay(500); // Wait 0.5 seconds before next measurement
}
```