// STM32 Nucleo-C031C6 SPI LCD Example
// Simulation: https://wokwi.com/projects/365549388158011393
#include "SPI.h"
#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"
#include "stdlib.h"
// Pin definitions
int trigpin = 4; // Trigger pin
int echopin = 5; // Echo pin
#define TFT_DC 2
#define TFT_CS 3
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
int pingTraveltime; // Echo travel time
float targetdistance; // Measured distance
const float thresholdDistance = 50.0; // Threshold in cm
void setup() {
pinMode(trigpin, OUTPUT);
pinMode(echopin, INPUT);
Serial.begin(115200);
Serial.println("Hello, WOKWI");
tft.begin();
tft.setCursor(20, 120);
tft.setTextColor(ILI9341_RED);
tft.setTextSize(3);
tft.println("Hello STM2");
tft.setCursor(24, 160);
tft.setTextColor(ILI9341_GREEN);
tft.setTextSize(2);
tft.println("I can do SPI :-)");
}
char ftext[30];
void loop() {
// Trigger the ultrasonic pulse
digitalWrite(trigpin, LOW);
delayMicroseconds(2);
digitalWrite(trigpin, HIGH);
delayMicroseconds(10);
digitalWrite(trigpin, LOW);
// Read echo time
pingTraveltime = pulseIn(echopin, HIGH);
// Convert time to distance
targetdistance = (pingTraveltime * 0.0343) / 2;
sprintf(ftext,"%d",(int)(targetdistance));
// dtostrf(targetdistance, 4, 2, ftext);
// Buzzer ON if object too close
if (targetdistance > 0 && targetdistance <= thresholdDistance) {
tft.fillScreen(ILI9341_BLACK);
tft.setCursor(30, 260);
tft.println("Hello Echo");
} else {
tft.fillScreen(ILI9341_BLACK);
tft.setCursor(30, 260);
tft.println("------------");
}
tft.println(ftext);
Serial.println(ftext);
delay(200); // stable plotting
}