Hello,
I have written a program in C# that can read the distance from an SRF08 ultrasonic sensor.
The SRF08 is connected to a USB-I2C module and communicates via rs232.
I have attached my code below. But i think there is some problem with the program, but im not sure.
Any help would be most appreciated.
Thanks
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO.Ports;
namespace ConsoleApplication1
{
class Program
{
const byte I2C_CMD = 0x55;
int n;
byte device_addr = 0xe0;
byte[] sbuf;
private System.IO.Ports.SerialPort port;
public void run()
{
n = 0;
device_addr = 0xe0;
sbuf = new byte[100];
setupCommPort("COM4");
sbuf[0] = I2C_CMD;
sbuf[1] = device_addr;
sbuf[2] = 0x00;
sbuf[3] = 0x01;
port.Write(sbuf, 0, 4);
port.Read(sbuf, 0, 1);
if(sbuf[0]<20) {
Console.WriteLine("Found tool ver. {0}", sbuf[0]);
sbuf[0] = I2C_CMD; // send gain limit
sbuf[1] = device_addr;
sbuf[2] = 0x01;
sbuf[3] = 0x01;
sbuf[4] = 20;
port.Write(sbuf, 0, 5);
port.Read(sbuf, 0, 1);
sbuf[0] = I2C_CMD; // send sonar rangeing (uS) command
sbuf[1] = device_addr;
sbuf[2] = 0x00;
sbuf[3] = 0x01;
sbuf[4] = 0x52;
port.Write(sbuf, 0, 5);
port.Read(sbuf, 0, 1);
while(true) {
Thread.Sleep(100);
sbuf[0] = I2C_CMD; // send sonar read command
sbuf[1] = device_addr;
sbuf[2] = 0x00;
sbuf[3] = 0x04;
port.Write(sbuf, 0, 4);
port.Read(sbuf, 0, 4);
//Console::WriteLine(L"Prectena verze {0}", sbuf[0]);
//Console::WriteLine(L"Prectene svetlo {0}", sbuf[1]);
Console.Write(sbuf[2]);
Console.Write(" ");
Console.Write(sbuf[3]);
Console.WriteLine();
//Console.WriteLine("Prectene {0} {1}", sbuf[2], sbuf[3]);
//n = sbuf[2]<<8;
//n |= sbuf[3];
//Console::WriteLine(L"Prectene uS {0}",n);
//Console.WriteLine("Prectene cm {0}", n/58);
//Console::WriteLine(L"Prectene inche {0}", n/148);
sbuf[0] = I2C_CMD; // send gain limit
sbuf[1] = device_addr;
sbuf[2] = 0x01;
sbuf[3] = 0x01;
sbuf[4] = 0x14;
port.Write(sbuf, 0, 5);
port.Read(sbuf, 0, 1);
sbuf[0] = I2C_CMD; // send sonar rangeing (uS) command
sbuf[1] = device_addr;
sbuf[2] = 0x00;
sbuf[3] = 0x01;
sbuf[4] = 0x52;
port.Write(sbuf, 0, 5);
port.Read(sbuf, 0, 1);
}
} else {
Console.WriteLine("Tool not found");
}
}
static void Main(string[] args)
{
Program prog = new Program();
prog.run();
}
private void setupCommPort(String comport)
{
port = new SerialPort();
this.port.BaudRate = 19200;
this.port.Parity = Parity.None;
this.port.StopBits = StopBits.One;
this.port.Handshake = Handshake.None;
this.port.RtsEnable = false;
this.port.ReadTimeout = 5000;
this.port.WriteTimeout = 5000;
port.PortName = comport;
port.Open();
if (port.IsOpen)
{
Console.WriteLine("Com Port 4 setup");
}
}
}
}