Stap 4: De code
Het idee achter de code is vrij eenvoudig: wacht totdat voldoende beweging wordt gedetecteerd en vervolgens de leds oplichten gedurende 30 seconden.
#include <Wire.h><br>
const int MPU=0x68;
int16_t GyX,GyY,GyZ,oldGyX,oldGyY,oldGyZ;
const float a = 0.7; const float b= 1.3;
void setup(){ // setup Wire Wire.begin(); Wire.beginTransmission(MPU); Wire.write(0x6B); Wire.write(0); Wire.endTransmission(true); // setup leds for(int i = 3; i < 11; i++) { pinMode(i, OUTPUT); digitalWrite(i, LOW); } pinMode(A1, OUTPUT); pinMode(A2, OUTPUT); pinMode(A3, OUTPUT); digitalWrite(A1, LOW); digitalWrite(A2, LOW); digitalWrite(A3, LOW); Serial.begin(9600); }
void loop(){ // store previous values oldGyX = GyX; oldGyY = GyY; oldGyZ = GyZ; Wire.beginTransmission(MPU); Wire.write(0x43); Wire.endTransmission(false); Wire.requestFrom(MPU,6,true); GyX=Wire.read()<<8|Wire.read(); GyY=Wire.read()<<8|Wire.read(); GyZ=Wire.read()<<8|Wire.read(); GyX = map(GyX, -5000, 5000, 0, 1000); GyY = map(GyY, -5000, 5000, 0, 1000); GyZ = map(GyZ, -5000, 5000, 0, 1000); Serial.print(GyX); Serial.print("-"); Serial.print(GyY); Serial.print("-"); Serial.println(GyZ); if(oldGyX*a > GyX || oldGyX*b < GyX || oldGyY*a > GyY || oldGyY*b < GyY || oldGyZ*a > GyZ || oldGyZ*b < GyZ) { cycleLeds(); } delay(500); }
void cycleLeds() { // analog pins uint8_t aPins[] = {A1, A2, A3}; unsigned long exec_time = 0; unsigned long start = millis(); while(exec_time < 30000) { for(int j = 0; j < 3; j++) { digitalWrite(aPins[j], HIGH); for(int i = 3; i < 11; i++) { digitalWrite(i, HIGH); digitalWrite(i, LOW); } } exec_time = millis() - start; } }