Sensor Ultrasonic -Serial USB

Hi guys, I’m trying to connect the ultrasound sensor using the USB port to view it in the web application but it doesn’t work. Can somebody help me

#define BLYNK_DEVICE_NAME           "jjj"
#define BLYNK_AUTH_TOKEN            "vSVLVXD_jjFbpxHNZlAkxwsT9D64Zt-p"


// Comment this out to disable prints and save space
#define BLYNK_PRINT SwSerial


#include <SoftwareSerial.h>
SoftwareSerial SwSerial(0, 1); // RX, TX

#include <BlynkSimpleStream.h>

#define echoPin 11
#define trigPin 10

long duration;
int distance; 

char auth[] = BLYNK_AUTH_TOKEN;

BlynkTimer timer;

void sendSensor()
{
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = duration * 0.034 / 2; //formula to calculate the distance for ultrasonic sensor
    Serial.print("Distance: ");
    Serial.println(distance);
    Blynk.virtualWrite(V0, distance);
    delay(1000);
}

void setup()
{
  // Debug console
  SwSerial.begin(9600);
  pinMode(trigPin, OUTPUT); 
  pinMode(echoPin, INPUT);
  // Blynk will work through Serial
  // Do not read or write this serial manually in your sketch
  Serial.begin(9600);
  Blynk.begin(Serial, auth);



  // Setup a function to be called every second
  timer.setInterval(1000L, sendSensor);
}

void loop()
{
  Blynk.run();
  timer.run();
}

please edit your post, using the pencil icon at the bottom, and add triple backticks at the beginning and end of your code so that it displays correctly. Triple backticks look like this: ```

1 Like

I’m guessing that you’re doing two things wrong…

  1. you probably haven’t edited the Blynk USB script to point it to the correct cloud server for Blynk IoT

  2. you’ve created a software serial port for debug messages, but you’ve used pins 0 and 1. You haven’t said what hardware you are using, but if it’s an Uno or Nano then pins 0 and 1 are connected internally to the USB port on the board, so the debug messages will be getting jumbled-up with the communication data to/from Blynk via your PC.

You should read this…

Especially the section called “Connecting an Uno/Nano or Mega via a USB connection to a computer (BlynkSimpleStream)”

Pete.