|
楼主 |
发表于 2011-9-21 22:56:17
|
显示全部楼层
本帖最后由 ypiggy 于 2011-9-22 08:28 编辑
附上传感器的原理图,很简单。乐高的硬件开发手册建议的I2C管脚上拉电阻为82K,这个板子上的是10K,不过没啥影响。
我没有自己从头做,直接淘的现成的,如果手头有风枪能贴片焊的,可以直接买制好的pcb板和全套器件,可能才10、20元。
NXC的代码如下,也很简单,就是最常规的I2C通讯,需要对芯片做一些必要的初始化。
- /************************************************************************/
- /* */
- /* Program Name: Compass-Nx-demo.nxc */
- /* =========================== */
- /* Adopted by ypiggy@tom.com */
- /* 2011/09/21 */
- /************************************************************************/
- #define SensorPort IN_1
- #define ADDR 0x3C
- struct TriAxisData
- {
- int gX,gY,gZ;
- };
- void COMPASS_Init(byte port, byte i2cAddr)
- {
- byte cmdBuf[];
- SetSensorLowspeed(port);
- ArrayBuild(cmdBuf,i2cAddr,0x00,0x70);
- I2CWrite(port,0,cmdBuf);
- int status = I2CCheckStatus(port);
- while (status > NO_ERR)
- status = I2CCheckStatus(port);
- ArrayBuild(cmdBuf,i2cAddr,0x01,0x20);
- I2CWrite(port,0,cmdBuf);
- status = I2CCheckStatus(port);
- while (status > NO_ERR)
- status = I2CCheckStatus(port);
- ArrayBuild(cmdBuf,i2cAddr,0x02,0x00);
- I2CWrite(port,0,cmdBuf);
- status = I2CCheckStatus(port);
- while (status > NO_ERR)
- status = I2CCheckStatus(port);
- }
- byte COMPASS_ReadData(byte port, byte i2cAddr,TriAxisData &triData)
- {
- byte message[];
- byte buf[12];
- int count;
- byte nByteReady = 0;
- byte b;
- SetSensorLowspeed(port);
- ArrayBuild(message, i2cAddr, 0x03);
- while (I2CStatus(port, nByteReady) == STAT_COMM_PENDING);
- count = 6;
- if(I2CBytes(port, message, count, buf)) {
- triData.gX=buf[0]<<8;
- triData.gX |= buf[1];
- triData.gY=buf[2]<<8;
- triData.gY |= buf[3];
- triData.gZ=buf[4]<<8;
- triData.gZ |= buf[5];
- }
- return b;
- }
- task main()
- {
- string msg;
- TriAxisData gData;
- string ax, ay, az;
- COMPASS_Init(SensorPort,ADDR);
-
- while (true ) {
- // read the values from the sensor.
- COMPASS_ReadData(SensorPort, ADDR, gData);
- msg = "X: ";
- ax = NumToStr(gData.gX);
- msg = StrReplace(msg, 2, ax);
- TextOut(0, LCD_LINE2, msg, false);
- msg = "Y: ";
- ay = NumToStr(gData.gY);
- msg = StrReplace(msg, 2, ay);
- TextOut(0, LCD_LINE3, msg, false);
- msg = "Z: ";
- az = NumToStr(gData.gZ);
- msg = StrReplace(msg, 2, az);
- TextOut(0, LCD_LINE4, msg, false);
- Wait(50);
- }
- }
复制代码
|
|