1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
| #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h>
#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h>
#include <wiringPiI2C.h> #include <wiringPi.h>
#define Device_Address 0x68 #define PWR_MGMT_1 0x6B #define SMPLRT_DIV 0x19 #define CONFIG 0x1A #define GYRO_CONFIG 0x1B #define INT_ENABLE 0x38 #define ACCEL_XOUT_H 0x3B #define ACCEL_YOUT_H 0x3D #define ACCEL_ZOUT_H 0x3F #define GYRO_XOUT_H 0x43 #define GYRO_YOUT_H 0x45 #define GYRO_ZOUT_H 0x47 #define pin1 7 #define pin2 21
int fd;
void MPU6050_Init() { fd = wiringPiI2CSetup(Device_Address); wiringPiI2CWriteReg8(fd, SMPLRT_DIV, 0x07); wiringPiI2CWriteReg8(fd, PWR_MGMT_1, 0x01); wiringPiI2CWriteReg8(fd, CONFIG, 0); wiringPiI2CWriteReg8(fd, GYRO_CONFIG, 24); wiringPiI2CWriteReg8(fd, INT_ENABLE, 0x01); if(wiringPiSetup() == -1){ printf("setup wiringPi failed!\n"); exit(0); } pinMode(pin1,INPUT); pinMode(pin2,INPUT); }
short read_raw_data(int addr) { short high_byte, low_byte, value; high_byte = wiringPiI2CReadReg8(fd, addr); low_byte = wiringPiI2CReadReg8(fd, addr + 1); value = (high_byte << 8) | low_byte; return value; }
char* MPU6050_Get_Data() { char *buf = (char *)malloc(45 * sizeof(char)); float Ax = 0, Ay = 0, Az = 0; float Gx = 0, Gy = 0, Gz = 0;
Ax = read_raw_data(ACCEL_XOUT_H) / 16384.0; Ay = read_raw_data(ACCEL_YOUT_H) / 16384.0; Az = read_raw_data(ACCEL_ZOUT_H) / 16384.0; Gx = read_raw_data(GYRO_XOUT_H) / 131; Gy = read_raw_data(GYRO_YOUT_H) / 131; Gz = read_raw_data(GYRO_ZOUT_H) / 131; int button1 = digitalRead(pin1); int button2 = digitalRead(pin2); sprintf(buf, "%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%d,%d", Gx, Gy, Gz, Ax, Ay, Az,button1,button2);
return buf; }
int main() {
MPU6050_Init(); int port = 5150;
int udp_socket = socket(AF_INET, SOCK_DGRAM, 0); if (udp_socket == -1) { perror("socket failed!\n"); return -1; }
struct sockaddr_in address = { 0 }; address.sin_family = AF_INET; address.sin_port = htons(port); address.sin_addr.s_addr = inet_addr("192.168.13.37");
while (1) { char* buf = MPU6050_Get_Data(); printf("%s\n",buf); sendto(udp_socket, buf, strlen(buf), 0, (struct sockaddr*)&address, sizeof(address));
free(buf); }
close(udp_socket); return 0; }
|