TestSRF08 SRF08, I2C

Dependencies:   mbed

Committer:
passionvirus
Date:
Sun Mar 03 11:30:06 2013 +0000
Revision:
0:ae88fe3b5508
create TestSRF08

Who changed what in which revision?

UserRevisionLine numberNew contents of line
passionvirus 0:ae88fe3b5508 1 #include "mbed.h"
passionvirus 0:ae88fe3b5508 2
passionvirus 0:ae88fe3b5508 3 Serial pc(USBTX,USBRX); // Tx, Rx Pin, default boud = 9600
passionvirus 0:ae88fe3b5508 4 I2C i2c(p28, p27); // SDA, SCL
passionvirus 0:ae88fe3b5508 5
passionvirus 0:ae88fe3b5508 6 int main()
passionvirus 0:ae88fe3b5508 7 {
passionvirus 0:ae88fe3b5508 8 char cmd[2]; // Command
passionvirus 0:ae88fe3b5508 9 char echo[2]; // Echo result data (8bit)
passionvirus 0:ae88fe3b5508 10 int addr = 0xE0; // Defalut I2C address of SRF08
passionvirus 0:ae88fe3b5508 11 int range = 0; // Rage data (16bit, cm)
passionvirus 0:ae88fe3b5508 12
passionvirus 0:ae88fe3b5508 13 cmd[0] = 0x02; // Register(RangeValue)
passionvirus 0:ae88fe3b5508 14 cmd[1] = 0x45; // (RangeValue*43)+43 = (69*43)+43 = 3010mm, maximum range
passionvirus 0:ae88fe3b5508 15 i2c.write(addr,cmd,2); // Send I2C data (8bit*2)
passionvirus 0:ae88fe3b5508 16
passionvirus 0:ae88fe3b5508 17 while(1)
passionvirus 0:ae88fe3b5508 18 {
passionvirus 0:ae88fe3b5508 19 cmd[0] = 0x00; // Register(Command)
passionvirus 0:ae88fe3b5508 20 cmd[1] = 0x51; // Ranging mode - Result in centimeters
passionvirus 0:ae88fe3b5508 21 i2c.write(addr,cmd,2); // Send I2C data (8bit*2)
passionvirus 0:ae88fe3b5508 22
passionvirus 0:ae88fe3b5508 23 wait(0.07); // Wait 70ms
passionvirus 0:ae88fe3b5508 24
passionvirus 0:ae88fe3b5508 25 cmd[0] = 0x02; // Register(1st Echo)
passionvirus 0:ae88fe3b5508 26 i2c.write(addr,cmd,1); // Send I2C data (8bit*1)
passionvirus 0:ae88fe3b5508 27 i2c.read(addr,echo,2); // Read I2C data (8bit*2)
passionvirus 0:ae88fe3b5508 28
passionvirus 0:ae88fe3b5508 29 range = (echo[0]<<8)+echo[1]; // 8bit+8bit=16bit
passionvirus 0:ae88fe3b5508 30
passionvirus 0:ae88fe3b5508 31 pc.printf("Range : %d cm\n",range);
passionvirus 0:ae88fe3b5508 32 }
passionvirus 0:ae88fe3b5508 33 }
passionvirus 0:ae88fe3b5508 34