MMC CARD
[usefulcode.git] / devchar / gsensor.c
blobc55d0b5ea08f18729e2d57d394629c63debbeceb
1 #include <stdio.h>
2 #include <fcntl.h>
3 #include <string.h>
4 #include <unistd.h>
6 typedef struct {
7 int x;
8 int y;
9 int z;
10 int delay_time;
11 } gsensor_accel_t;
13 enum DIRECTION{
14 DIRECTION_UP = 0,
15 DIRECTION_DN,
16 DIRECTION_LF,
17 DIRECTION_RT,
18 DIRECTION_FT,
19 DIRECTION_BK,
20 DIRECTION_MAX
23 #define READ_SIZE sizeof(gsensor_accel_t)
24 #define DEV_PATH "/dev/gsensor"
26 int getXYZ(gsensor_accel_t *bufData)
28 int fd;
29 int i;
30 memset(bufData, 0, READ_SIZE);
31 fd = open(DEV_PATH, O_RDONLY);
32 if(fd == -1)
34 printf("open ##DEV_PATH failed!\n");
35 return -1;
37 i = read(fd, bufData, READ_SIZE);
38 close(fd);
39 if(i == 0)
40 i = READ_SIZE; /*See the programmer's manual*/
41 printf("Read %d bytes from DEV_PATH, Intended size is %d\n", i, READ_SIZE);
42 printf("x = %d\n" , bufData->x);
43 printf("y = %d\n" , bufData->y);
44 printf("z = %d\n" , bufData->z);
45 printf("g = %d\n" , bufData->x*bufData->x + bufData->y*bufData->y + bufData->z*bufData->z);
46 return 0;
49 void msleep(int i){
50 usleep(1000*i);
53 enum DIRECTION isDirection(int x, int y, int z)
55 if((x*x + y*y < 32) && z*z > 225)
57 if(z > 0)
58 return DIRECTION_UP;
59 else
60 return DIRECTION_DN;
63 if((x*x + z*z < 32) && y*y > 225)
65 if(y > 0)
66 return DIRECTION_RT;
67 else
68 return DIRECTION_LF;
71 if((y*y + z*z < 32) && x*x > 225)
73 if(x > 0)
74 return DIRECTION_FT;
75 else
76 return DIRECTION_BK;
79 return DIRECTION_MAX;
82 int waitDirection(enum DIRECTION tempDir, int max_Time)
84 gsensor_accel_t tempData;
85 int i;
86 for(i = 0; i< max_Time; i++)
88 getXYZ(&tempData);
89 if(isDirection(tempData.x, tempData.y, tempData.z) == tempDir)
90 return 1;
91 else
92 msleep(100);
94 return 1;
97 void usage()
99 printf("usage:\n");
100 printf("*******************************************\n");
101 printf("** gsensor DIRECTION **\n");
102 printf("** DIRECTION: up down **\n");
103 printf("** left right **\n");
104 printf("** front back **\n");
105 printf("*******************************************\n");
108 int main(int argc, char *argv[]){
109 unsigned int i;
110 unsigned int foundDir;
111 unsigned char *dirChar[DIRECTION_MAX]={
112 "up",
113 "down",
114 "left",
115 "right",
116 "front",
117 "back"
120 if(argc == 1)
122 usage();
123 return 0;
126 for(i = 0; i < DIRECTION_MAX; i++)
128 if(!strcmp(dirChar[i], argv[1]))
129 break;
131 foundDir = waitDirection((enum DIRECTION)i, 200);
132 if(foundDir)
133 printf("Direction Detected!\n");
134 else
135 printf("Time out occured! please check!\n");