Donnovan -3 Newbie Poster

hi guys,

i'm trying to write a program in C# to read a SRF04, through a USB I2C connnector. this is my first time working wiht I2C and usb and i need some help.

http://http://www.robot-electronics.co.uk/htm/usb_i2c_tech.htm

im using the I/O settings to write to the Sonar. Can someone provide me wiht a sample of how to communicate.

thanx in advance.

Dani AI

Generated

— short, practical guidance for the SRF04 situation.

The SRF04 needs microsecond-accurate pulses: a ~10 µs trigger and measuring the echo pulse width in microseconds. Most USB↔I2C modules expose GPIO over a USB protocol that has USB/driver latency and cannot reliably capture microsecond pulse widths by polling from a PC. Two robust approaches are recommended.

  1. Let a small microcontroller do the timing, and send the measured range to the PC.
    This is the simplest and most reliable workflow: MCU handles trigger + echo timing (hardware/tight software timing), computes distance, and reports a numeric value over Serial or I2C. Example Arduino flow (conceptual):
    digitalWrite(triggerPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(triggerPin, LOW);
    duration = pulseIn(echoPin, HIGH);        // blocks until echo finished
    distance_cm = duration / 58.0;
    Serial.println(distance_cm);
  2. If you want to stick to your USB adapter GPIO, first verify the adapter supports hardware-timed pulse capture or bit-bang modes with µs resolution. If it does not, readings will be noisy or wrong.

Quick C# sketch to read values over a serial link (PC side):

using System.IO.Ports;
var sp = new SerialPort("COM3", 9600);
sp.Open();
string line = sp.ReadLine();
if (float.TryParse(line, out float cm)) Console.WriteLine("Distance: " + cm + " cm");
sp.Close();

Troubleshooting and cautions:

  • Ensure common ground between sensor and MCU/adapter and correct Vcc (SRF devices typically use 5V). Use level shifting if your adapter is 3.3V.
  • Don’t trigger faster than ~20 Hz; allow sensor settling (~50–60 ms).
  • Calibrate with a known-distance target; formula variations (duration/58 or duration*0.0343/2) are equivalent.
  • If you must use the USB-I2C board’s I/O, check its datasheet for GPIO latency, bit-bang support, or hardware capture features before relying on it for timing.
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.