I have come out the programming, but now new problems encountered: the programming can anyhow run no matter whether i connect the RF04 to my PC or not!! It has ouput "101cm" always and even i moved the obstacle it will still "101cm"!!! It seems like my hardware has nothing to do with this programming.... (the programming has no error).
The following code is my programming, can anyone of u kindly go through it and help me find out the problem and give me some idea??
#include <math.h>
#include <windows.h>
#include <stdio.h>
#include <string>
enum cmds { nop=0, VERSION, NEW_ADDRESS, BATTERY, SCAN1, SCAN2, SCAN3, SCAN4, SCAN6, SCAN8, SCAN12, SCAN16};
#define I2C_CMD 0x55 // direct I2C control command
#define CM02_CMD 0x5a // CM02 command
HANDLE hCom;
BYTE SerialBuf[200];
BYTE BackData=0, Battery, Compass;
void SetupCommPort(LPCTSTR comport);
void ConvertData(void);
void Clean_Screen(void);
int main(void)
{
int k;
DWORD n;
SetupCommPort("COM4");
SerialBuf[0] = I2C_CMD; // send SRF08 setup command
SerialBuf[1] = 0xE0;
SerialBuf[2] = 0x00;
SerialBuf[3] = 0x01;
SerialBuf[4] = 0x51;
WriteFile(hCom, &SerialBuf, 5, &n, NULL);
ReadFile(hCom, &SerialBuf, 1, &n, NULL);
while(1)
{
SerialBuf[0] = CM02_CMD; // send SCAN8 command
SerialBuf[1] = SCAN1;
SerialBuf[2] = 0;
SerialBuf[3] = 0;
WriteFile(hCom, &SerialBuf, 4, &n, NULL);
ReadFile(hCom, &SerialBuf, 6, &n, NULL);
ConvertData();
Clean_Screen();
printf("%d cm \n", BackData);
for(k=0;k<400000000;k++);
}
return 1;
}
void SetupCommPort(LPCTSTR comport)
{
DCB dcb;
COMMTIMEOUTS ct;
CloseHandle(hCom);
hCom = CreateFile(comport, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
GetCommState(hCom, &dcb);
dcb.BaudRate = CBR_19200;
dcb.fParity = FALSE;
dcb.fOutxCtsFlow = FALSE;
dcb.fOutxDsrFlow = FALSE;
dcb.fDtrControl = DTR_CONTROL_DISABLE;
dcb.fDsrSensitivity = FALSE;
dcb.fOutX = FALSE;
dcb.fInX = FALSE;
dcb.fRtsControl = RTS_CONTROL_DISABLE;
dcb.fAbortOnError = FALSE;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
SetCommState(hCom, &dcb);
GetCommTimeouts(hCom, &ct);
ct.ReadIntervalTimeout = 500;
ct.ReadTotalTimeoutMultiplier =500;
ct.ReadTotalTimeoutConstant = 500;
SetCommTimeouts(hCom, &ct);
SetCommMask(hCom, EV_RXCHAR);
}
void ConvertData(void)
{
int x=0;
x = (SerialBuf[4]<<

+ SerialBuf[5]; // range in uS
x /= 58; // convert to cm
if(x==0) x=600; // make max if no echo
BackData = x;
}
void Clean_Screen(void)
{
printf("\n\n");
}
------------------------------------------------------------------------------------------------------------------------------------------
Thanks u all very much and hope someone will help me with this!!!