[教學] Hitechnic 加速度感應器 I2C讀值

昨天介紹完hitechnic的color sensor之後, 接著介紹加速度感應器。

按照官網的介紹, 0x42, 0x43, 0x44 分別是X, Y ,Z軸的加速度值, 大小為 8 bits = 1 bytes.

重點在於 I2CBytes(S1, inI2Ccmd, count, outbuf);  其中:

   inI2Ccmd是指要送出指令的陣列. 

       count是讀回的資料長度.
 
       outbuf 則是存放讀取資料的矩陣, 

       我們依序將outbuf[0]~ outbuf[2] 分別存入xval~ zval, 再顯示在螢幕上, 如上圖所示.================================================================
#include "NXCDefs.h"
void checkI2C()
{
	byte status;
	do{
		status= I2CCheckStatus(IN_1);
	}while(status == STAT_COMM_PENDING);
}

task main()
{
  SetSensorLowspeed(IN_1);
  int count = 6;       

int xval;
int yval;
int zval;

byte inI2Ccmd[];
byte outbuf[];
while (true)
{
ArrayBuild(inI2Ccmd, 0x02, 0x42); //Rebuild the Array
checkI2C();
I2CBytes(IN_1, inI2Ccmd, count, outbuf); //read the acceleration sensor on port 1

xval=outbuf[0]; //load x axis upper 8 bits
yval=outbuf[1]; //load Y axis upper 8 bits
zval=outbuf[2]; //load z axis upper 8 bits
if (xval > 127) xval-=256; //convert x to 10 bit value
xval=xval*4 + outbuf[3];
if (yval > 127) yval-=256; //convert y to 10 bit value
yval=yval*4 + outbuf[4];
if (zval > 127) zval-=256; //convert z to 10 bit value
zval=zval*4 + outbuf[5];


ClearScreen();
TextOut(0,30,"X: ");NumOut(50,30,xval);
TextOut(0,20,"Y: ");NumOut(50,20,yval);
TextOut(0,10,"Z: ");NumOut(50,10,zval);
Wait(200);
}
}
About CAVEDU 阿吉 - 雜工 (2520 Articles)
CAVEDU 教育團隊 打雜
Contact: Website

Leave a comment

Your email address will not be published.


*