File transfer add

This commit is contained in:
Blizzard Finnegan 2021-12-16 16:42:51 -05:00
commit 234d8a663b
49 changed files with 3464 additions and 0 deletions

BIN
1-January/lab1.docx Executable file

Binary file not shown.

8
1-January/lab1.md Executable file
View file

@ -0,0 +1,8 @@
How many LEDs?
4
To which pins are they connected?
PB5, PD4, PD5, and one is not connected to the microcontroller except via 5V and ground.

View file

@ -0,0 +1,22 @@
//Lab1_hello_arduino
#define LED_PIN 13
void setup() {
// put your setup code here, to run once:
pinMode(LED_PIN , OUTPUT);
digitalWrite(LED_PIN , LOW);
Serial.begin(9600);
Serial.println("Lab 1: Hello arduino v0.0\n");
delay(10000);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(LED_PIN , HIGH); //turn on LED
Serial.println("On");
delay(500); //wait half second
digitalWrite(LED_PIN , LOW); //turn off LED
Serial.println("Off");
delay(500); //wait half second
}

View file

@ -0,0 +1,56 @@
//Lab_1_hello_arduino
#define LED_PIN 13
char inChar;
boolean isFreshInChar;
void setup() {
pinMode(LED_PIN , OUTPUT);
digitalWrite(LED_PIN , LOW);
// Set serial monitor console termination for 'No line ending'
Serial.begin(9600);
Serial.println(F("Lab 1: hello arduino v0.4\n"));
delay(5000);
}
void loop() {
isFreshInChar = false;
if (Serial.available()) {
inChar = Serial.read();
Serial.print("Serial input detected: ");
Serial.println(inChar);
isFreshInChar = true;
}
if (inChar == 'n') digitalWrite(LED_PIN , HIGH); // oN
if (inChar == 'f') digitalWrite(LED_PIN , LOW); // oFf
if (inChar == 'b') { // blink with 25% duty cycle
digitalWrite(LED_PIN , HIGH);
delay(250);
digitalWrite(LED_PIN , LOW);
delay(750);
}
// function for readability: blink with 75% duty cycle
if (inChar == 'B') blinkLED(750,1000);
// Discover 't' persistence bug by observing high rate LED blink
if (inChar == 't') { // toggle
digitalWrite(LED_PIN , !digitalRead(LED_PIN ));
}
// Add state change detection to get proper toggle action.
if (inChar == 'T') { // toggle
if (isFreshInChar) digitalWrite(LED_PIN , !digitalRead(LED_PIN ));
}
} // loop()
//********************************************************************************
void blinkLED(unsigned int msecT, unsigned int msecOn) {
digitalWrite(LED_PIN , HIGH);
delay(msecOn);
digitalWrite(LED_PIN , LOW);
delay(msecT - msecOn);
}

BIN
1-January/lab2.docx Normal file

Binary file not shown.

34
1-January/lab2a/lab2a.ino Normal file
View file

@ -0,0 +1,34 @@
#define SW1_PIN 8
#define LED1_PIN 11
bool isSwPressed = 0;
bool prevIsSwPressed = 0;
bool isSwJustPressed = 0;
bool isSwJustReleased = 0;
bool isSwChange = 0;
void setup() {
pinMode(SW1_PIN, INPUT_PULLUP);
pinMode(LED1_PIN, OUTPUT); digitalWrite(LED1_PIN, LOW);
Serial.begin(9600);
Serial.println(F("Lab 2: Switch State Decoding v0.0\n"));
}
void loop() {
prevIsSwPressed = isSwPressed;
isSwPressed = !digitalRead(SW1_PIN);
// When the switch is pressed, the SW_PIN is low, so !low is high or true
isSwJustPressed = (isSwPressed && !prevIsSwPressed); // switch edge detection
isSwJustReleased = (!isSwPressed && prevIsSwPressed);
isSwChange = (isSwJustReleased || isSwJustPressed);
// uncomment just one line below at time to see how each input
// condition is detected. (enable just one output function at a time)
// digitalWrite(LED1_PIN, isSwPressed);
digitalWrite(LED1_PIN, isSwJustReleased);
// digitalWrite(LED1_PIN, isSwJustPressed);
// digitalWrite(LED1_PIN, isSwChange);
// digitalWrite(LED1_PIN, !digitalRead(LED1_PIN)); // see the sample rate
delay(100);
}

35
1-January/lab2d/lab2d.ino Normal file
View file

@ -0,0 +1,35 @@
#define SW1_PIN 8
#define LED1_PIN 11
#define QTR_SIG_PIN A3
#define QTR_5V_PIN A4
#define QTR_GND_PIN A5
#define MSEC_SAMPLE 200
boolean isSwPressed;
unsigned int adcQTR;
void setup(){
pinMode(SW1_PIN, INPUT_PULLUP);
pinMode(LED1_PIN, OUTPUT); digitalWrite(LED1_PIN, LOW);
pinMode(QTR_SIG_PIN, INPUT);
pinMode(QTR_GND_PIN, OUTPUT); digitalWrite(QTR_GND_PIN, LOW);
pinMode(QTR_5V_PIN, OUTPUT); digitalWrite(QTR_5V_PIN, HIGH);
//
//
Serial.begin(9600);
Serial.println(F("Lab 2: Analog Sensor Reading\n"));
}
void loop(){
// scan input and condition it (low to hi true)
isSwPressed = !digitalRead(SW1_PIN);
digitalWrite(LED1_PIN, isSwPressed);
adcQTR = analogRead(QTR_SIG_PIN); // 0..1023 output
Serial.println(adcQTR);
delay(MSEC_SAMPLE);
} // loop()

37
1-January/lab2e/lab2e.ino Normal file
View file

@ -0,0 +1,37 @@
#define SW1_PIN 8
#define LED1_PIN 11
#define QTR_SIG_PIN A3
#define QTR_5V_PIN A4
#define QTR_GND_PIN A5
#define MSEC_SAMPLE 200
boolean isSwPressed;
unsigned int adcQTR;
void setup(){
pinMode(SW1_PIN, INPUT_PULLUP);
pinMode(LED1_PIN, OUTPUT); digitalWrite(LED1_PIN, LOW);
pinMode(QTR_SIG_PIN, INPUT);
pinMode(QTR_GND_PIN, OUTPUT); digitalWrite(QTR_GND_PIN, LOW);
pinMode(QTR_5V_PIN, OUTPUT); digitalWrite(QTR_5V_PIN, HIGH);
//
//
Serial.begin(9600);
Serial.println(F("Lab 2: Analog Sensor Reading\n"));
}
void loop(){
// scan input and condition it (low to hi true)
isSwPressed = !digitalRead(SW1_PIN);
digitalWrite(LED1_PIN, isSwPressed);
adcQTR = analogRead(QTR_SIG_PIN); // 0..1023 output
if(isSwPressed){
Serial.println(adcQTR);
};
delay(MSEC_SAMPLE);
} // loop()

78
1-January/lab2f/lab2f.ino Normal file
View file

@ -0,0 +1,78 @@
#define SW1_PIN 8
#define LED1_PIN 11
#define MSEC_SAMPLE 1
enum {STOP, LED_ON, LED_OFF};
boolean isSwPressed, prevIsSwPressed, isSwJustReleased, isSwJustPressed, isSwChange;
int state = STOP, prevState = !state;
int stateTimer;
boolean isNewState;
void setup() {
pinMode(SW1_PIN, INPUT_PULLUP);
pinMode(LED1_PIN, OUTPUT); digitalWrite(LED1_PIN, LOW);
Serial.begin(9600); Serial.println(F("Lab 2: if-then state machine\n"));
Serial.println(STOP); Serial.println(LED_ON); Serial.println(LED_OFF);
}
void loop() {
// Input scan, signal conditioning, history evolution
prevIsSwPressed = isSwPressed;
isSwPressed = !digitalRead(SW1_PIN);
isSwJustPressed = (isSwPressed && !prevIsSwPressed); // switch edge detection
isSwJustReleased = (!isSwPressed && prevIsSwPressed);
isSwChange = (isSwJustReleased || isSwJustPressed);
// update state information
isNewState = (state != prevState); // if state != prevState, then isNewState
prevState = state;
if (state == STOP) {
// Entry housekeeping
if (isNewState) Serial.println("STOP");
// State business
digitalWrite(LED1_PIN, LOW);
// Exit condition is based only on switch changing
if (isSwPressed) state = LED_ON;
}
else if (state == LED_ON) {
// Entry housekeeping
if (isNewState) {
stateTimer = 0; // reset state timer to zero
Serial.println("LED_ON");
digitalWrite(LED1_PIN, HIGH);
}
// State business
stateTimer++;
// Exit condition 1 is based on switch changing
if (isSwJustReleased) {
digitalWrite(LED1_PIN, LOW);
state = STOP;
}
// Exit condition 2 is based on timer expiring
if (isSwPressed) state = LED_OFF;
}
else if (state == LED_OFF) {
// Entry housekeeping
if (isNewState) {
stateTimer = 0; // reset state timer to zero
Serial.println("LED_OFF");
digitalWrite(LED1_PIN, LOW);
}
// State business
stateTimer++;
// Exit condition 1 is based on switch changing
if (isSwJustReleased) {
digitalWrite(LED1_PIN, LOW);
state = STOP;
}
// Exit condition 2 is based on timer expiring
if (isSwPressed) state = LED_ON;
}
else state = STOP;
delay(MSEC_SAMPLE);
} //loop()

135
1-January/lab2g/lab2g.ino Normal file
View file

@ -0,0 +1,135 @@
#define SW1_PIN 8
#define LED1_PIN 10
#define LED2_PIN 11
#define QTR_SIG_PIN A3
#define QTR_5V_PIN A4
#define QTR_GND_PIN A5
#define MSEC_SAMPLE 1
enum {LED_OFF, BLINK_G, BLINK_R, BLINK_GR, BLINK_RATE};
boolean isSwPressed, prevIsSwPressed, isSwJustReleased, isSwJustPressed, isSwChange;
int state = LED_OFF, prevState = !state;
int stateTimer, adcQTR;
boolean isNewState;
void setup() {
pinMode(SW1_PIN, INPUT_PULLUP);// pinMode(SW1_PIN, INPUT); won't work
pinMode(LED1_PIN, OUTPUT); digitalWrite(LED1_PIN, LOW);
pinMode(LED2_PIN, OUTPUT); digitalWrite(LED2_PIN, LOW);
pinMode(QTR_SIG_PIN, INPUT);
pinMode(QTR_5V_PIN, OUTPUT); digitalWrite(QTR_5V_PIN, HIGH);
pinMode(QTR_GND_PIN, OUTPUT); digitalWrite(QTR_GND_PIN, LOW);
Serial.begin(9600);
Serial.println(F("Lab 2 Complex State Machine"));
} // setup()
// ADD loop() HERE - IT IS GIVEN ON THE NEXT PAGE
//****************************************************************************
void redOn(void) {
PORTB = PORTB |(1 << 0); // sets Uno dig_8, PORTB.0, pin to 1 (HIGH)
// physical pin 14 (28 pin DIP)
digitalWrite(LED1_PIN, HIGH); // alternative to PORTB setting
digitalWrite(LED2_PIN, LOW);
}
//****************************************************************************
void greenOn(void) {
digitalWrite(LED1_PIN, LOW);
digitalWrite(LED2_PIN, HIGH);
}
//****************************************************************************
void allOff(void) {
digitalWrite(LED1_PIN, LOW);
digitalWrite(LED2_PIN, LOW);
}
void loop() {
prevIsSwPressed = isSwPressed;
isSwPressed = !digitalRead(SW1_PIN);
isSwJustPressed = (isSwPressed && !prevIsSwPressed); // switch edge detection
isSwJustReleased = (!isSwPressed && prevIsSwPressed);
isSwChange = (isSwJustReleased || isSwJustPressed);
isNewState = (state != prevState);
prevState = state;
switch (state) {
case LED_OFF:
if (isNewState) Serial.println("LED_OFF");
allOff();
if (isSwJustReleased) state = BLINK_G;
break;
case BLINK_G:
if (isNewState) {
stateTimer = 0;
Serial.println("BLINK_G");
}
stateTimer++;
if (stateTimer < 250) greenOn();
else allOff();
if (stateTimer >= 1000) stateTimer = 0;
if (isSwJustReleased) {
allOff();
state = BLINK_R;
}
break;
// ADD BLINK_R STATE HERE. ************
case BLINK_R:
if (isNewState) {
stateTimer = 0;
Serial.println("BLINK_R");
}
stateTimer++;
if (stateTimer < 250) redOn();
else allOff();
if (stateTimer >= 1000) stateTimer = 0;
if (isSwJustReleased) {
allOff();
state = BLINK_GR;
}
break;
case BLINK_GR:
if (isNewState) {
stateTimer = 0;
Serial.println("BLINK_GR");
}
stateTimer++;
if (stateTimer < 500) redOn();
else greenOn();
if (stateTimer >= 1000) stateTimer = 0;
if (isSwJustReleased) {
allOff();
state = BLINK_RATE;
}
break;
case BLINK_RATE:
if (isNewState) {
stateTimer = 0;
Serial.println("BLINK_RATE");
}
stateTimer++;
adcQTR = analogRead(QTR_SIG_PIN);
if (stateTimer < adcQTR/2) redOn();
else greenOn();
if (stateTimer >= adcQTR) stateTimer = 0;
if (isSwJustReleased) {
allOff();
state = LED_OFF;
}
break;
default: state = LED_OFF;
} // switch (state)
delay(MSEC_SAMPLE);
} // loop()

72
1-January/lab2h/lab2h.ino Normal file
View file

@ -0,0 +1,72 @@
enum{fwd, backr, backl, turnr, turnl, stop};
bool rs = false, ls = false;
int state = fwd, prevState = !fwd;
int stateTimer = 0;
#define forward 0xC0
#define rightTurn 0x40
#define leftTurn 0x80
void setup(){
DDRD |= 0xC0; DDRD &= ~(0x03); //setting input/output pins
PORTD |= 0x03; //setting pushbutton pullups
}
void loop(){
rs = !(PIND & 0x02);
ls = !(PIND & 0x01);
isNewState = (state != prevState);
prevState = state;
switch(state){
case fwd:
if(isNewState){
PORTD |= forward;
}
if(rs) state = backr;
else if(ls) state = backl;
break;
case backr:
if(isNewState){
PORTD &= ~(forward);
stateTimer=0;
}
if(!(isNewState)){
stateTimer++;
}
if (stateTimmer >= 500) state = turnr;
break;
case turnr:
if(isNewState){
PORTD |= rightTurn;
}
if (stateTimmer >= 500) state = fwd;
break;
case backl:
if(isNewState){
PORTD &= ~(forward);
stateTimer=0;
}
if(!(isNewState)){
stateTimer++;
}
if (stateTimmer >= 500) state = turnl;
break;
case turnl:
if(isNewState){
PORTD |= leftTurn;
}
if (stateTimmer >= 500) state = fwd;
break;
case stop:
if(isNewState){
PORTD &= ~(forward);
}
break;
default: state = stop;
}
delay(1);
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1,171 @@
// Lab4_Timer1_p1
// Written By: C. Hochgraf
// Date: Feb 2017
// declare variables
enum {TC1_PCFC_DC90_D10};
int state, sreg;
//***********************************************************************************
void setup()
{
Serial.begin(9600);
Serial.println(F("Lab 4: Hardware Timers"));
}
//***********************************************************************************
void loop()
{
// loop() is only executed once because each state contains an infinite loop.
state = TC1_PCFC_DC90_D10;
switch(state)
{
//-------------------------------------------------------------------------------
case TC1_PCFC_DC90_D10:
// Create 90% duty cycle square wave using Timer 1.
Serial.println(F("Print out all the default Timer1 settings"));
Serial.println(F("The settings are all stored in registers"));
Serial.println(F("Later, you will change the values in the registers"));
Serial.println();
Serial.println(F("First, what is in the Timer 1 Control Registers?"));
printTimer1Registers();
delay(8000);
// you can comment out the printWGM function below when you are ready
Serial.println(F("you can comment out the printing of WGM values to save time"));
//printWGMCOMCS1Values();
Serial.println();
delay(1000);
Serial.println(F("Initializing Timer1 in PCFC mode, toggling OC1B on d10"));
sreg = SREG; /* Save global interrupt flag */
cli(); // temporarily stop interrupts while setting register values
TCCR1A = 0; // set to defaults as good practice
TCCR1B = 0; // set to defaults as good practice
TCCR1A = (0 << WGM11)|(0 << WGM10); // first part of setup for PCFC PWM (mode 8)
TCCR1B = (1 << WGM13)|(0 << WGM12); // second part of setup for PCFC PWM (mode 8)
TCCR1A |= (1 << COM1B1)|(0 << COM1B0); // non-inverting PWM on channel B: PORTB2, UNOd10
TCCR1A |= (1 << COM1A1)|(0 << COM1A0); // non-inverting PWM on channel A: PORTB1, UNOd9
//This setup COM1A (10) COM1B (11), gives d9 to be inverted from d10 if OCR1A=OCR1B.
// WGM mode 8 (1000) has ICR1 as top.
//TCCR1B |= (1 << CS12)|(0 << CS11)|(1 << CS10); // clock prescale = 1024 -> 15.625 kHz
//TCCR1B |= (1 << CS12)|(0 << CS11)|(0 << CS10); // clock prescale = 256 -> 62.5 kHz
TCCR1B |= (1 << CS12)|(0 << CS11)|(0 << CS10); // clock prescale = 64 -> 250 kHz
ICR1 = 125000; // period ICR1=10000 gives visible blips
OCR1A = (125000/2); // =10000/16 = 625
OCR1B = (125000/2); // =10000/16 = 625
sei(); // reenable interrupts
SREG = sreg; /* Restore global interrupt flag */
//did it work right? check by printing registers
printTimer1Registers();
//delay(10000);
pinMode(9,OUTPUT); // to drive led on pin 13
pinMode(10,OUTPUT);
pinMode(13,INPUT); // to receive digital signal from pin 9
Serial.println();
Serial.println("I'm ready to blink now. Attach a wire from pin 9 to 13");
while(true) {; // dwell forever
}
break;
} // switch(state)
} // Arduino loop()
//==============================================================================
//void printWGMCOMCS1Values(void) {
//Serial.println();
//delay(8000);
//Serial.println(F("Second, what are these WGM values? Try printing as decimals"));
//Serial.println();
//Serial.print(F("WGM10 DECIMAL: ")); Serial.println(WGM10, DEC);
//Serial.print(F("WGM11 DECIMAL: ")); Serial.println(WGM11, DEC);
//Serial.print(F("WGM12 DECIMAL: ")); Serial.println(WGM12, DEC);
//Serial.print(F("WGM13 DECIMAL: ")); Serial.println(WGM13, DEC);
//delay(8000);
//Serial.println();
//Serial.println(F("The WGM values are #defines that tell you how far"));
//delay(1000);
//Serial.println(F("to shift a bit value to have it land at the right place "));
//delay(1000);
//Serial.println(F("in the register. "));
//Serial.println();
//delay(2000);
//Serial.println(F("Now print the COM1B values."));
//Serial.println(F("Thes are #defines that tell you how far"));
//Serial.println(F("to shift a bit value to have it land at the right place "));
//Serial.println();
//Serial.print(F("COM1B0 DECIMAL: ")); Serial.println(COM1B0, DEC);
//Serial.print(F("COM1B1 DECIMAL: ")); Serial.println(COM1B1, DEC);
//Serial.println();
//delay(8000);
//Serial.println(F("Now print the CS values that help with setting the "));
//Serial.println(F("clock prescaler value (clock divider). "));
//Serial.println();
//delay(2000);
//Serial.print(F("CS10 DECIMAL: ")); Serial.println(CS10, DEC);
//Serial.print(F("CS11 DECIMAL: ")); Serial.println(CS11, DEC);
//Serial.print(F("CS12 DECIMAL: ")); Serial.println(CS12, DEC);
//Serial.println();
//delay(8000);
//};
//==============================================================================
void printHex8(byte data) { // prints 8-bit data in hex with leading zeroes
Serial.print("0x");
if (data<0x10) {Serial.print("0");}
Serial.print(data,HEX);
}
//==============================================================================
void printHex16(uint16_t data) { // prints 16-bit data in hex with leading zeroes
Serial.print("0x");
uint8_t MSB=byte(data>>8);
uint8_t LSB=byte(data);
if (MSB<0x10) {Serial.print("0");} Serial.print(MSB,HEX);
if (LSB<0x10) {Serial.print("0");} Serial.print(LSB,HEX);
}
//==============================================================================
void printBinaryByte(byte value) { // prints 8-bit data in binary with leading 0's
Serial.print("B");
for (byte bitmask = 0x80; bitmask; bitmask >>= 1) {
Serial.print((bitmask & value) ? '1' : '0');
}
}
//==============================================================================
void printBinaryWord(unsigned int value) { // prints 16-bit data in binary with leading 0's
Serial.print("B");
for (unsigned int bitmask = 0x8000; bitmask; bitmask >>= 1) {
Serial.print((bitmask & value) ? '1' : '0');
}
}
//==============================================================================
void printRegister16InDecHexBin(unsigned int registerName) {
Serial.print(F("Binary: ")); printBinaryWord(registerName); Serial.print("\t");
Serial.print(F("Hex: ")); printHex16(registerName); Serial.print("\t");
Serial.print(F("Decimal: ")); Serial.println(registerName);
}
//==============================================================================
void printRegister8InDecHexBin(unsigned int registerName) {
Serial.print(F("Binary: ")); printBinaryByte(registerName); Serial.print("\t\t");
Serial.print(F("Hex: ")); printHex8(registerName); Serial.print("\t");
Serial.print(F("Decimal: ")); Serial.println(registerName);
}
//==============================================================================
void printTimer1Registers() {
Serial.print(F("TCCR1A: ")); printRegister8InDecHexBin(TCCR1A);
Serial.print(F("TCCR1B: ")); printRegister8InDecHexBin(TCCR1B);
Serial.print(F("OCR1A: ")); printRegister16InDecHexBin(OCR1A);
Serial.print(F("OCR1B: ")); printRegister16InDecHexBin(OCR1B);
Serial.print(F("ICR1: ")); printRegister16InDecHexBin(ICR1);
Serial.print(F("TIMSK1: ")); printRegister8InDecHexBin(TIMSK1);
}

Binary file not shown.

View file

@ -0,0 +1,22 @@
// Lab4_BlinkUsingDelay
// Written By: C. Hochgraf
// Date: Feb 2017
unsigned long numberOfLoopsRun=0;
//***********************************************************************************
void setup() {
pinMode(13,OUTPUT);
Serial.begin(9600);
Serial.println(F("Lab 4: BlinkUsingDelay"));
Serial.println(F("I'm ready to blink now."));
}
//***********************************************************************************
void loop() {
digitalWrite(13,HIGH);
delay(1000);
digitalWrite(13,LOW);
delay(1000);
Serial.print(F("The number of times loop code has run is: "));
Serial.println(numberOfLoopsRun);
numberOfLoopsRun++;
} // Arduino loop()

View file

@ -0,0 +1,27 @@
// Lab4_BlinkUsingTimer1
// Written By: C. Hochgraf
// Date: Feb 2017
unsigned long numberOfLoopsRun=0;
//***********************************************************************************
void setup()
{
pinMode(9,OUTPUT); // to drive led on pin 13
pinMode(13,INPUT); // to receive digital signal from pin 9
Serial.begin(9600);
Serial.println(F("Lab 4: BlinkUsingTimer1"));
TCCR1A=0x50; // Configures timer to CTC mode 4 with OCR1A as top
TCCR1B=0x0D; // toggles pin 9 every one second
OCR1A=0x3D09; // one second interval
Serial.println("I'm ready to blink now. Attach a wire from pin 9 to 13");
}
//***********************************************************************************
void loop()
{
// every time numberOfLoopsRun is a multiple of 10000, print the number of loops run so far
if ((numberOfLoopsRun % 10000)==0) {
Serial.print(F("The number of times loop code has run is: "));
Serial.println(numberOfLoopsRun);
}
numberOfLoopsRun++;
} // Arduino loop()

View file

@ -0,0 +1,26 @@
// Lab4 PWM_dim_LED_compact.ino
// Written By: C. Hochgraf
// Date: Feb 2017
int sreg;
unsigned long fadeValue=0;
//***********************************************************************************
void setup()
{
pinMode(9,OUTPUT); // to drive led on pin 13
pinMode(13,INPUT); // to receive digital signal from pin 9
Serial.begin(9600);
Serial.println(F("Lab 4: PWM_dim_LED_compact"));
TCCR1A=0xA3; // configure registers for Timer 1 Mode 7 fast PWM 10bit, clock scale=8x
TCCR1B=0x0A; // configure registers for Timer 1 Mode 7 fast PWM 10bit, clock scale=8x
Serial.println();
Serial.println("I'm ready to blink now. Attach a wire from pin 9 to 13");
}
//***********************************************************************************
void loop()
{ delay(10);
fadeValue++;
OCR1A=fadeValue; // load PWM compare register (OCR1A) with new PWM value (fadeValue)
//OCR1A=512; // generates fixed PWM "analog voltage" of around 2.5 volts dc
if (fadeValue>=1023) fadeValue=0; // PWM counts up to 10 bit value (1023)
} // Arduino loop()

View file

@ -0,0 +1,26 @@
// Lab4 PWM_motor_pos_neg_compact.ino
// Written By: C. Hochgraf
// Date: Feb 2017
unsigned long fadeValue=0;
//***********************************************************************************
void setup()
{
pinMode(9,OUTPUT); // motor lead +
pinMode(10,OUTPUT); // motor lead -
Serial.begin(9600);
Serial.println(F("Lab 4: PWM_motor_pos_neg_compact"));
TCCR1A=0xB3; // configure registers for Timer 1 Mode 7 fast PWM 10bit, clock scale=8x
TCCR1B=0x0A; // configure registers for Timer 1 Mode 7 fast PWM 10bit, clock scale=8x
Serial.println();
Serial.println("I'm ready to blink now. Attach 330 ohm resistor and back to back LEDs");
Serial.println("(just like in lab 2) between pins 9 and 10");
}
//***********************************************************************************
void loop()
{ delay(10);
fadeValue++;
OCR1A=fadeValue; // load PWM compare register (OCR1A) with new PWM value (fadeValue)
OCR1B=fadeValue;
if (fadeValue>=1023) fadeValue=0; // PWM counts up to 10 bit value (1023)
} // Arduino loop()

Binary file not shown.

View file

@ -0,0 +1,78 @@
// Lab5_ISR_INT0
// Written by: Nov 01, 2014, JTSchueckler
// revised: Mar 05, 2017, Clark Hochgraf
// Desc: ++ PLEASE READ ALL COMMENTS ++
// This program demonstrates a simple use of the INTO functionality.
// Review the initialization of the interrupt system.
// Review the setup of the ISR.
// Define volatile global variables for ISR system interface.
volatile long pulseCount = 0, prevpulseCount = -1;
//***********************************************************************************
void setup() {
Serial.begin(9600); Serial.println("Lab 5 ISR INT0 counter");
configurePins();
// Display the bootup values of EICRA, EIFR and EIMSK
Serial.print("EIFR \t"); printlnBinaryByte(EIFR);
Serial.print("EICRA \t"); printlnBinaryByte(EICRA);
Serial.print("EIMSK \t"); printlnBinaryByte(EIMSK);
Serial.println();
initInterrupts();
// Display the programmed values of EICRA, EIFR and EIMSK
Serial.print("EIFR \t"); printlnBinaryByte(EIFR);
Serial.print("EICRA \t"); printlnBinaryByte(EICRA);
Serial.print("EIMSK \t"); printlnBinaryByte(EIMSK);
Serial.println();
}
//***********************************************************************************
void loop() {
if (pulseCount != prevpulseCount) { // only print the pulse count if it has changed
prevpulseCount = pulseCount;
Serial.print("Switch was pressed ");
Serial.print(pulseCount);
Serial.println(" times.");
}
} // Arduino loop()
//===================================================================================
void configurePins(void) {
pinMode(2,INPUT_PULLUP); //Set up PD2 (INT0) as an INPUT w/Pullup;
pinMode(3,INPUT_PULLUP); //Set up PD3 (INT1) as an INPUT w/Pullup;
}
//===================================================================================
void initInterrupts(void) {
/* disable interrupts using cli(); and enable interrupts using sei(); with Arduino IDE
Typical Atmel C code would use __disable_interrupt();
to clear the global interrupt bit in the SREG.
and __enable_interrupt(); to set the global interrupt enable in the SREG.
OR by direct manipulation of the "I" bit in the SREG.
NOTE: The Serial Monitor and other Arduino functions will be directly affected
if you try to manipulate the SREG in the Arduino operation. */
cli(); // Clear the Global INT bit to disable ALL interrrupts
EICRA |=(1<<1); EICRA |= 0x04; // Configure EICRA to detect falling edge for INT0
// ISC0 = 0b10 refers to Interrupt Sense Control for INT0
// the two bits {1 and 0} program the hardware to respond to a falling edge
// at the input pin INT0 (PD2)
EIMSK |= 0x03; // Unmask INT0 in EIMSK so that it is enabled
EIFR |= 0x03; // Clear any pending interrupt flags for INTO by writing a 1 to bit 0
sei(); // Sets the Global INT bit to enable ALL interrrupts
}
//===================================================================================
void printlnBinaryByte(byte value) { // prints 8-bit data in binary with leading 0's
Serial.print("B");
for (byte bitmask = 0x80; bitmask; bitmask >>= 1) {
Serial.print((bitmask & value) ? '1' : '0');
}
Serial.println();
}
//===================================================================================
ISR(INT0_vect){ // the ISR name must match the interrupt (e.g. INT0_vect)
pulseCount++;
// NOTE: NO Extraneous instructions in the ISR
}
ISR(INT1_vect){ pulseCount--; }

View file

@ -0,0 +1,72 @@
// Lab5_ISR_INT0
// Written by: Nov 01, 2014, JTSchueckler
// revised: Mar 05, 2017, Clark Hochgraf
// Desc: ++ PLEASE READ ALL COMMENTS ++
// This program demonstrates a simple use of the INTO functionality.
// Review the initialization of the interrupt system.
// Review the setup of the ISR.
// Define volatile global variables for ISR system interface.
volatile long pulseCount = 0, prevpulseCount = -1;
//***********************************************************************************
void setup() {
Serial.begin(9600); Serial.println("Lab 5 ISR INT0 counter");
configurePins();
// Display the bootup values of EICRA, EIFR and EIMSK
Serial.print("EIFR \t"); printlnBinaryByte(EIFR);
Serial.print("EICRA \t"); printlnBinaryByte(EICRA);
Serial.print("EIMSK \t"); printlnBinaryByte(EIMSK);
Serial.println();
initInterrupts();
// Display the programmed values of EICRA, EIFR and EIMSK
Serial.print("EIFR \t"); printlnBinaryByte(EIFR);
Serial.print("EICRA \t"); printlnBinaryByte(EICRA);
Serial.print("EIMSK \t"); printlnBinaryByte(EIMSK);
Serial.println();
}
//***********************************************************************************
void loop() {
cli();
if (pulseCount != prevpulseCount) { // only print the pulse count if it has changed
prevpulseCount = pulseCount;
Serial.print("Switch was pressed ");
Serial.print(pulseCount);
Serial.println(" times.");
}
sei();
} // Arduino loop()
//============================================================================sei();=======
void configurePins(void) {
DDRC &= (0 << 5 | 0 << 0);
PORTC |= (1 << 5 | 1 << 0);
}
//===================================================================================
void initInterrupts(void) {
cli(); // Clear the Global INT bit to disable ALL interrrupts
PCMSK1 |= (1 << 5 | 1 << 0);
PCICR |= (1 << 1);
sei(); // Sets the Global INT bit to enable ALL interrrupts
}
//===================================================================================
void printlnBinaryByte(byte value) { // prints 8-bit data in binary with leading 0's
Serial.print("B");
for (byte bitmask = 0x80; bitmask; bitmask >>= 1) {
Serial.print((bitmask & value) ? '1' : '0');
}
Serial.println();
}
ISR(PCINT1_vect){
static byte prevPINC;
byte newPINC, changeMap;
newPINC = PINC;
changeMap = newPINC ^ prevPINC;
if (changeMap & 0x01) pulseCount++;
if (changeMap & 0x20) pulseCount--;
//prevPINC = newPINC;
}

View file

@ -0,0 +1,72 @@
// Lab5_ISR_INT0
// Written by: Nov 01, 2014, JTSchueckler
// revised: Mar 05, 2017, Clark Hochgraf
// Desc: ++ PLEASE READ ALL COMMENTS ++
// This program demonstrates a simple use of the INTO functionality.
// Review the initialization of the interrupt system.
// Review the setup of the ISR.
// Define volatile global variables for ISR system interface.
volatile long pulseCount = 0, prevpulseCount = -1;
volatile bool triggered = 0;
//***********************************************************************************
void setup() {
Serial.begin(9600); Serial.println("Lab 5 ISR INT0 counter");
configurePins();
// Display the bootup values of EICRA, EIFR and EIMSK
Serial.print("EIFR \t"); printlnBinaryByte(EIFR);
Serial.print("EICRA \t"); printlnBinaryByte(EICRA);
Serial.print("EIMSK \t"); printlnBinaryByte(EIMSK);
Serial.println();
initInterrupts();
// Display the programmed values of EICRA, EIFR and EIMSK
Serial.print("EIFR \t"); printlnBinaryByte(EIFR);
Serial.print("EICRA \t"); printlnBinaryByte(EICRA);
Serial.print("EIMSK \t"); printlnBinaryByte(EIMSK);
Serial.println();
}
//***********************************************************************************
void loop() {
cli();
if (pulseCount != prevpulseCount) { // only print the pulse count if it has changed
prevpulseCount = pulseCount;
Serial.print("Switch was pressed ");
Serial.print(pulseCount);
Serial.println(" times.");
}
sei();
} // Arduino loop()
//===================================================================================
void configurePins(void) {
DDRC &= (0 << 5 | 0 << 0); //pc0 and pc5
PORTC |= (1 << 5 | 1 << 0);
}
//===================================================================================
void initInterrupts(void) {
cli(); // Clear the Global INT bit to disable ALL interrrupts
PCMSK1 |= (1 << 5 | 1 << 0);
PCICR |= (1 << 1);
sei(); // Sets the Global INT bit to enable ALL interrrupts
}
//===================================================================================
void printlnBinaryByte(byte value) { // prints 8-bit data in binary with leading 0's
Serial.print("B");
for (byte bitmask = 0x80; bitmask; bitmask >>= 1) {
Serial.print((bitmask & value) ? '1' : '0');
}
Serial.println();
}
//===================================================================================
ISR(PCINT1_vect){
static byte prevPINC;
byte newPINC, changeMap;
newPINC = PINC;
changeMap = newPINC ^ prevPINC;
if (changeMap & 0x01) pulseCount++;
if (changeMap & 0x20) pulseCount--;
//prevPINC = newPINC;
}

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1,47 @@
/* Lab7_I2C_gyro_serial_plotter.ino
Written by: Clark Hochgraf, revised: Feb 18, 2019
Description: ++ PLEASE READ ALL COMMENTS ++
Demonstrates calculation of roll, pitch and yaw angles using a gyroscope sensor.
The gyro outputs the rate of rotation in degrees per second.
The gyro signal is the integrated (multipled by sample interval) to get degrees.
Hardware: uses the MPU-6050 6-axis accelerometer and gyro
Software: uses library for MPU6050, on personal machines, you will have to install
*/
#include <Wire.h>
#include <MPU6050.h>
MPU6050 mpu; // declare a variable called mpu of datatype MPU6050
unsigned long timeStampStartOfLoopMs = 0;
float timeStepS = 0.01;
float pitch,roll,yaw = 0.0f; // pitch, roll and yaw values
Vector normalizedGyroDPS; //stores the three gyroscope readings XYZ in degrees per second (DPS)
//==============================================================================
void setup() {
Serial.begin(115200);
// Initialize MPU6050 to have full scale range of 2000 degrees per second
while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G)) {
Serial.println("Could not find a valid MPU6050 sensor, check wiring.");
delay(1000);
}
mpu.calibrateGyro(); // Calibrate gyroscope- must be done with sensor not moving.
mpu.setThreshold(1);// sets level below which changes in gyro readings are ignored.
// helps to reduce noise. 1 = one standard deviation. Range is 0 to 3.
} // setup
//==============================================================================
void loop() {
timeStampStartOfLoopMs = millis(); // mark the time
normalizedGyroDPS = mpu.readNormalizeGyro(); // Read normalized values
// Calculate Pitch, Roll and Yaw
pitch = pitch + normalizedGyroDPS.YAxis * timeStepS;
roll = roll + normalizedGyroDPS.XAxis * timeStepS;
yaw = yaw + normalizedGyroDPS.ZAxis * timeStepS;
Serial.print(pitch);
Serial.print(" ");
Serial.print(roll);
Serial.print(" ");
Serial.println(yaw);
// Wait until a full timeStepS has passed before next reading
delay((timeStepS*1000) - (millis() - timeStampStartOfLoopMs));
} //loop

View file

@ -0,0 +1,62 @@
/* Lab7_I2C_gyro_serial_plotter.ino
Written by: Clark Hochgraf, revised: Feb 18, 2019
Description: ++ PLEASE READ ALL COMMENTS ++
Demonstrates calculation of roll, pitch and yaw angles using a gyroscope sensor.
The gyro outputs the rate of rotation in degrees per second.
The gyro signal is the integrated (multipled by sample interval) to get degrees.
Hardware: uses the MPU-6050 6-axis accelerometer and gyro
Software: uses library for MPU6050, on personal machines, you will have to install
*/
#include <Wire.h>
#include <MPU6050.h>
MPU6050 mpu; // declare a variable called mpu of datatype MPU6050
unsigned long timeStampStartOfLoopMs = 0;
float timeStepS = 0.01;
float pitch,roll,yaw = 0.0f; // pitch, roll and yaw values
Vector normalizedGyroDPS; //stores the three gyroscope readings XYZ in degrees per second (DPS)
volatile bool newDataFlag=false; // boolean flag to indicate that timer1 overflow has occurred
unsigned long startMicroseconds,elapsedMicroseconds; // use for profiling time for certain tasks
//==============================================================================
void setup() {
Serial.begin(115200);
// Initialize MPU6050 to have full scale range of 2000 degrees per second
while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G)) {
Serial.println("Could not find a valid MPU6050 sensor, check wiring.");
delay(1000);
}
mpu.calibrateGyro(); // Calibrate gyroscope- must be done with sensor not moving.
mpu.setThreshold(1);// sets level below which changes in gyro readings are ignored.
// helps to reduce noise. 1 = one standard deviation. Range is 0 to 3.
TIFR1 |= (1 << OCF1A | 1 << TOV1);
TIMSK1 |= (1 <<TOIE1);
TCCR1A = 0b00000010;
TCCR1B = 0b00011100;
ICR1 = 624;
} // setup
ISR(TIMER1_OVF_vect){newDataFlag=true;}
void loop() {
while (!newDataFlag) {}; // stay stuck here until new data arrives, then run loop
// this will occur every 10 millisecond
// elapsedMicroseconds=micros()-startMicroseconds; // check time for Timer 1 OVF
startMicroseconds=micros(); // mark time at start of main loop code
normalizedGyroDPS = mpu.readNormalizeGyro();
// elapsedMicroseconds=micros()-startMicroseconds; // check time for I2C comms
// Calculate Pitch, Roll and Yaw
pitch = pitch + normalizedGyroDPS.YAxis * timeStepS;
roll = roll + normalizedGyroDPS.XAxis * timeStepS;
yaw = yaw + normalizedGyroDPS.ZAxis * timeStepS;
// elapsedMicroseconds=micros()-startMicroseconds; // check time without prints
Serial.print(pitch);
Serial.print(F(" "));
Serial.print(roll);
Serial.print(F(" "));
Serial.println(yaw);
elapsedMicroseconds=micros()-startMicroseconds; // check total time main loop
Serial.print(F("elapsed time in microseconds = "));
Serial.println(elapsedMicroseconds);
newDataFlag=false;
} //loop

BIN
ATmega328-328P_Datasheet_2016.pdf Executable file

Binary file not shown.

BIN
PWM_guide.pdf Normal file

Binary file not shown.

8
classDescription.txt Normal file
View file

@ -0,0 +1,8 @@
CPET-252-O3
Microcontroller Systems Lab
Professor: Ken Garland
Semester: 2195 (2020 Spring)
Time Slot: T 14-15 (2-3pm)
Professor Garland is a very strict professor. He knows what he wants, and he wants it exactly. If at all possible, have as much of your lab work checked by the LA instead of him, if you wish to leave in a timely manner. He is not overly helpful either, simply saying whether your results are correct or incorrect. The LA will be more likely to give you a nudge in the right direction if you and your lab partner are stuck.
This course is incredibly easy. 98% of it is plugging code given to you in the "notes" and making sure that it runs properly, while occasionally replacing a value or two. There is little to no skill needed for this course, except in soldering, which will be necessary as you will be building a small robot. Note that at the time of taking this course, the robot kit required to take this course successfully costs $80, and must be paid for in Tiger Bucks.

View file

@ -0,0 +1,23 @@
MPU6050 Arduino Library 1.0.3 / 03.03.2015
======================================================================
* Added setDLPFMode(mpu6050_dlpf_t dlpf) function
MPU6050_DLPF_0...6 (see datatsheet)
MPU6050 Arduino Library 1.0.2 / 10.02.2015
======================================================================
* Adjustable i2c address
mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G) - default 0x68
mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G, 0x69) - use 0x69
MPU6050 Arduino Library 1.0.1 / 26.10.2014
======================================================================
* Removing examples for Kalman Filter. Moved to KalmanFilter Git repo
* Removing examples for HMC5883L. Moved to HMC5833L Git repo
MPU6050 Arduino Library 1.0.0 / 20.10.2014
======================================================================
* First release

View file

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{project} Copyright (C) {year} {fullname}
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View file

@ -0,0 +1,749 @@
/*
MPU6050.cpp - Class file for the MPU6050 Triple Axis Gyroscope & Accelerometer Arduino Library.
Version: 1.0.3
(c) 2014-2015 Korneliusz Jarzebski
www.jarzebski.pl
This program is free software: you can redistribute it and/or modify
it under the terms of the version 3 GNU General Public License as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include <Wire.h>
#include <math.h>
#include <MPU6050.h>
bool MPU6050::begin(mpu6050_dps_t scale, mpu6050_range_t range, int mpua)
{
// Set Address
mpuAddress = mpua;
Wire.begin();
// Reset calibrate values
dg.XAxis = 0;
dg.YAxis = 0;
dg.ZAxis = 0;
useCalibrate = false;
// Reset threshold values
tg.XAxis = 0;
tg.YAxis = 0;
tg.ZAxis = 0;
actualThreshold = 0;
// Check MPU6050 Who Am I Register
if (fastRegister8(MPU6050_REG_WHO_AM_I) != 0x68)
{
return false;
}
// Set Clock Source
setClockSource(MPU6050_CLOCK_PLL_XGYRO);
// Set Scale & Range
setScale(scale);
setRange(range);
// Disable Sleep Mode
setSleepEnabled(false);
return true;
}
void MPU6050::setScale(mpu6050_dps_t scale)
{
uint8_t value;
switch (scale)
{
case MPU6050_SCALE_250DPS:
dpsPerDigit = .007633f;
break;
case MPU6050_SCALE_500DPS:
dpsPerDigit = .015267f;
break;
case MPU6050_SCALE_1000DPS:
dpsPerDigit = .030487f;
break;
case MPU6050_SCALE_2000DPS:
dpsPerDigit = .060975f;
break;
default:
break;
}
value = readRegister8(MPU6050_REG_GYRO_CONFIG);
value &= 0b11100111;
value |= (scale << 3);
writeRegister8(MPU6050_REG_GYRO_CONFIG, value);
}
mpu6050_dps_t MPU6050::getScale(void)
{
uint8_t value;
value = readRegister8(MPU6050_REG_GYRO_CONFIG);
value &= 0b00011000;
value >>= 3;
return (mpu6050_dps_t)value;
}
void MPU6050::setRange(mpu6050_range_t range)
{
uint8_t value;
switch (range)
{
case MPU6050_RANGE_2G:
rangePerDigit = .000061f;
break;
case MPU6050_RANGE_4G:
rangePerDigit = .000122f;
break;
case MPU6050_RANGE_8G:
rangePerDigit = .000244f;
break;
case MPU6050_RANGE_16G:
rangePerDigit = .0004882f;
break;
default:
break;
}
value = readRegister8(MPU6050_REG_ACCEL_CONFIG);
value &= 0b11100111;
value |= (range << 3);
writeRegister8(MPU6050_REG_ACCEL_CONFIG, value);
}
mpu6050_range_t MPU6050::getRange(void)
{
uint8_t value;
value = readRegister8(MPU6050_REG_ACCEL_CONFIG);
value &= 0b00011000;
value >>= 3;
return (mpu6050_range_t)value;
}
void MPU6050::setDHPFMode(mpu6050_dhpf_t dhpf)
{
uint8_t value;
value = readRegister8(MPU6050_REG_ACCEL_CONFIG);
value &= 0b11111000;
value |= dhpf;
writeRegister8(MPU6050_REG_ACCEL_CONFIG, value);
}
void MPU6050::setDLPFMode(mpu6050_dlpf_t dlpf)
{
uint8_t value;
value = readRegister8(MPU6050_REG_CONFIG);
value &= 0b11111000;
value |= dlpf;
writeRegister8(MPU6050_REG_CONFIG, value);
}
void MPU6050::setClockSource(mpu6050_clockSource_t source)
{
uint8_t value;
value = readRegister8(MPU6050_REG_PWR_MGMT_1);
value &= 0b11111000;
value |= source;
writeRegister8(MPU6050_REG_PWR_MGMT_1, value);
}
mpu6050_clockSource_t MPU6050::getClockSource(void)
{
uint8_t value;
value = readRegister8(MPU6050_REG_PWR_MGMT_1);
value &= 0b00000111;
return (mpu6050_clockSource_t)value;
}
bool MPU6050::getSleepEnabled(void)
{
return readRegisterBit(MPU6050_REG_PWR_MGMT_1, 6);
}
void MPU6050::setSleepEnabled(bool state)
{
writeRegisterBit(MPU6050_REG_PWR_MGMT_1, 6, state);
}
bool MPU6050::getIntZeroMotionEnabled(void)
{
return readRegisterBit(MPU6050_REG_INT_ENABLE, 5);
}
void MPU6050::setIntZeroMotionEnabled(bool state)
{
writeRegisterBit(MPU6050_REG_INT_ENABLE, 5, state);
}
bool MPU6050::getIntMotionEnabled(void)
{
return readRegisterBit(MPU6050_REG_INT_ENABLE, 6);
}
void MPU6050::setIntMotionEnabled(bool state)
{
writeRegisterBit(MPU6050_REG_INT_ENABLE, 6, state);
}
bool MPU6050::getIntFreeFallEnabled(void)
{
return readRegisterBit(MPU6050_REG_INT_ENABLE, 7);
}
void MPU6050::setIntFreeFallEnabled(bool state)
{
writeRegisterBit(MPU6050_REG_INT_ENABLE, 7, state);
}
uint8_t MPU6050::getMotionDetectionThreshold(void)
{
return readRegister8(MPU6050_REG_MOT_THRESHOLD);
}
void MPU6050::setMotionDetectionThreshold(uint8_t threshold)
{
writeRegister8(MPU6050_REG_MOT_THRESHOLD, threshold);
}
uint8_t MPU6050::getMotionDetectionDuration(void)
{
return readRegister8(MPU6050_REG_MOT_DURATION);
}
void MPU6050::setMotionDetectionDuration(uint8_t duration)
{
writeRegister8(MPU6050_REG_MOT_DURATION, duration);
}
uint8_t MPU6050::getZeroMotionDetectionThreshold(void)
{
return readRegister8(MPU6050_REG_ZMOT_THRESHOLD);
}
void MPU6050::setZeroMotionDetectionThreshold(uint8_t threshold)
{
writeRegister8(MPU6050_REG_ZMOT_THRESHOLD, threshold);
}
uint8_t MPU6050::getZeroMotionDetectionDuration(void)
{
return readRegister8(MPU6050_REG_ZMOT_DURATION);
}
void MPU6050::setZeroMotionDetectionDuration(uint8_t duration)
{
writeRegister8(MPU6050_REG_ZMOT_DURATION, duration);
}
uint8_t MPU6050::getFreeFallDetectionThreshold(void)
{
return readRegister8(MPU6050_REG_FF_THRESHOLD);
}
void MPU6050::setFreeFallDetectionThreshold(uint8_t threshold)
{
writeRegister8(MPU6050_REG_FF_THRESHOLD, threshold);
}
uint8_t MPU6050::getFreeFallDetectionDuration(void)
{
return readRegister8(MPU6050_REG_FF_DURATION);
}
void MPU6050::setFreeFallDetectionDuration(uint8_t duration)
{
writeRegister8(MPU6050_REG_FF_DURATION, duration);
}
bool MPU6050::getI2CMasterModeEnabled(void)
{
return readRegisterBit(MPU6050_REG_USER_CTRL, 5);
}
void MPU6050::setI2CMasterModeEnabled(bool state)
{
writeRegisterBit(MPU6050_REG_USER_CTRL, 5, state);
}
void MPU6050::setI2CBypassEnabled(bool state)
{
return writeRegisterBit(MPU6050_REG_INT_PIN_CFG, 1, state);
}
bool MPU6050::getI2CBypassEnabled(void)
{
return readRegisterBit(MPU6050_REG_INT_PIN_CFG, 1);
}
void MPU6050::setAccelPowerOnDelay(mpu6050_onDelay_t delay)
{
uint8_t value;
value = readRegister8(MPU6050_REG_MOT_DETECT_CTRL);
value &= 0b11001111;
value |= (delay << 4);
writeRegister8(MPU6050_REG_MOT_DETECT_CTRL, value);
}
mpu6050_onDelay_t MPU6050::getAccelPowerOnDelay(void)
{
uint8_t value;
value = readRegister8(MPU6050_REG_MOT_DETECT_CTRL);
value &= 0b00110000;
return (mpu6050_onDelay_t)(value >> 4);
}
uint8_t MPU6050::getIntStatus(void)
{
return readRegister8(MPU6050_REG_INT_STATUS);
}
Activites MPU6050::readActivites(void)
{
uint8_t data = readRegister8(MPU6050_REG_INT_STATUS);
a.isOverflow = ((data >> 4) & 1);
a.isFreeFall = ((data >> 7) & 1);
a.isInactivity = ((data >> 5) & 1);
a.isActivity = ((data >> 6) & 1);
a.isDataReady = ((data >> 0) & 1);
data = readRegister8(MPU6050_REG_MOT_DETECT_STATUS);
a.isNegActivityOnX = ((data >> 7) & 1);
a.isPosActivityOnX = ((data >> 6) & 1);
a.isNegActivityOnY = ((data >> 5) & 1);
a.isPosActivityOnY = ((data >> 4) & 1);
a.isNegActivityOnZ = ((data >> 3) & 1);
a.isPosActivityOnZ = ((data >> 2) & 1);
return a;
}
Vector MPU6050::readRawAccel(void)
{
Wire.beginTransmission(mpuAddress);
#if ARDUINO >= 100
Wire.write(MPU6050_REG_ACCEL_XOUT_H);
#else
Wire.send(MPU6050_REG_ACCEL_XOUT_H);
#endif
Wire.endTransmission();
Wire.beginTransmission(mpuAddress);
Wire.requestFrom(mpuAddress, 6);
while (Wire.available() < 6);
#if ARDUINO >= 100
uint8_t xha = Wire.read();
uint8_t xla = Wire.read();
uint8_t yha = Wire.read();
uint8_t yla = Wire.read();
uint8_t zha = Wire.read();
uint8_t zla = Wire.read();
#else
uint8_t xha = Wire.receive();
uint8_t xla = Wire.receive();
uint8_t yha = Wire.receive();
uint8_t yla = Wire.receive();
uint8_t zha = Wire.receive();
uint8_t zla = Wire.receive();
#endif
ra.XAxis = xha << 8 | xla;
ra.YAxis = yha << 8 | yla;
ra.ZAxis = zha << 8 | zla;
return ra;
}
Vector MPU6050::readNormalizeAccel(void)
{
readRawAccel();
na.XAxis = ra.XAxis * rangePerDigit * 9.80665f;
na.YAxis = ra.YAxis * rangePerDigit * 9.80665f;
na.ZAxis = ra.ZAxis * rangePerDigit * 9.80665f;
return na;
}
Vector MPU6050::readScaledAccel(void)
{
readRawAccel();
na.XAxis = ra.XAxis * rangePerDigit;
na.YAxis = ra.YAxis * rangePerDigit;
na.ZAxis = ra.ZAxis * rangePerDigit;
return na;
}
Vector MPU6050::readRawGyro(void)
{
Wire.beginTransmission(mpuAddress);
#if ARDUINO >= 100
Wire.write(MPU6050_REG_GYRO_XOUT_H);
#else
Wire.send(MPU6050_REG_GYRO_XOUT_H);
#endif
Wire.endTransmission();
Wire.beginTransmission(mpuAddress);
Wire.requestFrom(mpuAddress, 6);
while (Wire.available() < 6);
#if ARDUINO >= 100
uint8_t xha = Wire.read();
uint8_t xla = Wire.read();
uint8_t yha = Wire.read();
uint8_t yla = Wire.read();
uint8_t zha = Wire.read();
uint8_t zla = Wire.read();
#else
uint8_t xha = Wire.receive();
uint8_t xla = Wire.receive();
uint8_t yha = Wire.receive();
uint8_t yla = Wire.receive();
uint8_t zha = Wire.receive();
uint8_t zla = Wire.receive();
#endif
rg.XAxis = xha << 8 | xla;
rg.YAxis = yha << 8 | yla;
rg.ZAxis = zha << 8 | zla;
return rg;
}
Vector MPU6050::readNormalizeGyro(void)
{
readRawGyro();
if (useCalibrate)
{
ng.XAxis = (rg.XAxis - dg.XAxis) * dpsPerDigit;
ng.YAxis = (rg.YAxis - dg.YAxis) * dpsPerDigit;
ng.ZAxis = (rg.ZAxis - dg.ZAxis) * dpsPerDigit;
} else
{
ng.XAxis = rg.XAxis * dpsPerDigit;
ng.YAxis = rg.YAxis * dpsPerDigit;
ng.ZAxis = rg.ZAxis * dpsPerDigit;
}
if (actualThreshold)
{
if (abs(ng.XAxis) < tg.XAxis) ng.XAxis = 0;
if (abs(ng.YAxis) < tg.YAxis) ng.YAxis = 0;
if (abs(ng.ZAxis) < tg.ZAxis) ng.ZAxis = 0;
}
return ng;
}
float MPU6050::readTemperature(void)
{
int16_t T;
T = readRegister16(MPU6050_REG_TEMP_OUT_H);
return (float)T/340 + 36.53;
}
int16_t MPU6050::getGyroOffsetX(void)
{
return readRegister16(MPU6050_REG_GYRO_XOFFS_H);
}
int16_t MPU6050::getGyroOffsetY(void)
{
return readRegister16(MPU6050_REG_GYRO_YOFFS_H);
}
int16_t MPU6050::getGyroOffsetZ(void)
{
return readRegister16(MPU6050_REG_GYRO_ZOFFS_H);
}
void MPU6050::setGyroOffsetX(int16_t offset)
{
writeRegister16(MPU6050_REG_GYRO_XOFFS_H, offset);
}
void MPU6050::setGyroOffsetY(int16_t offset)
{
writeRegister16(MPU6050_REG_GYRO_YOFFS_H, offset);
}
void MPU6050::setGyroOffsetZ(int16_t offset)
{
writeRegister16(MPU6050_REG_GYRO_ZOFFS_H, offset);
}
int16_t MPU6050::getAccelOffsetX(void)
{
return readRegister16(MPU6050_REG_ACCEL_XOFFS_H);
}
int16_t MPU6050::getAccelOffsetY(void)
{
return readRegister16(MPU6050_REG_ACCEL_YOFFS_H);
}
int16_t MPU6050::getAccelOffsetZ(void)
{
return readRegister16(MPU6050_REG_ACCEL_ZOFFS_H);
}
void MPU6050::setAccelOffsetX(int16_t offset)
{
writeRegister16(MPU6050_REG_ACCEL_XOFFS_H, offset);
}
void MPU6050::setAccelOffsetY(int16_t offset)
{
writeRegister16(MPU6050_REG_ACCEL_YOFFS_H, offset);
}
void MPU6050::setAccelOffsetZ(int16_t offset)
{
writeRegister16(MPU6050_REG_ACCEL_ZOFFS_H, offset);
}
// Calibrate algorithm
void MPU6050::calibrateGyro(uint8_t samples)
{
// Set calibrate
useCalibrate = true;
// Reset values
float sumX = 0;
float sumY = 0;
float sumZ = 0;
float sigmaX = 0;
float sigmaY = 0;
float sigmaZ = 0;
// Read n-samples
for (uint8_t i = 0; i < samples; ++i)
{
readRawGyro();
sumX += rg.XAxis;
sumY += rg.YAxis;
sumZ += rg.ZAxis;
sigmaX += rg.XAxis * rg.XAxis;
sigmaY += rg.YAxis * rg.YAxis;
sigmaZ += rg.ZAxis * rg.ZAxis;
delay(5);
}
// Calculate delta vectors
dg.XAxis = sumX / samples;
dg.YAxis = sumY / samples;
dg.ZAxis = sumZ / samples;
// Calculate threshold vectors
th.XAxis = sqrt((sigmaX / 50) - (dg.XAxis * dg.XAxis));
th.YAxis = sqrt((sigmaY / 50) - (dg.YAxis * dg.YAxis));
th.ZAxis = sqrt((sigmaZ / 50) - (dg.ZAxis * dg.ZAxis));
// If already set threshold, recalculate threshold vectors
if (actualThreshold > 0)
{
setThreshold(actualThreshold);
}
}
// Get current threshold value
uint8_t MPU6050::getThreshold(void)
{
return actualThreshold;
}
// Set treshold value
void MPU6050::setThreshold(uint8_t multiple)
{
if (multiple > 0)
{
// If not calibrated, need calibrate
if (!useCalibrate)
{
calibrateGyro();
}
// Calculate threshold vectors
tg.XAxis = th.XAxis * multiple;
tg.YAxis = th.YAxis * multiple;
tg.ZAxis = th.ZAxis * multiple;
} else
{
// No threshold
tg.XAxis = 0;
tg.YAxis = 0;
tg.ZAxis = 0;
}
// Remember old threshold value
actualThreshold = multiple;
}
// Fast read 8-bit from register
uint8_t MPU6050::fastRegister8(uint8_t reg)
{
uint8_t value;
Wire.beginTransmission(mpuAddress);
#if ARDUINO >= 100
Wire.write(reg);
#else
Wire.send(reg);
#endif
Wire.endTransmission();
Wire.beginTransmission(mpuAddress);
Wire.requestFrom(mpuAddress, 1);
#if ARDUINO >= 100
value = Wire.read();
#else
value = Wire.receive();
#endif;
Wire.endTransmission();
return value;
}
// Read 8-bit from register
uint8_t MPU6050::readRegister8(uint8_t reg)
{
uint8_t value;
Wire.beginTransmission(mpuAddress);
#if ARDUINO >= 100
Wire.write(reg);
#else
Wire.send(reg);
#endif
Wire.endTransmission();
Wire.beginTransmission(mpuAddress);
Wire.requestFrom(mpuAddress, 1);
while(!Wire.available()) {};
#if ARDUINO >= 100
value = Wire.read();
#else
value = Wire.receive();
#endif;
Wire.endTransmission();
return value;
}
// Write 8-bit to register
void MPU6050::writeRegister8(uint8_t reg, uint8_t value)
{
Wire.beginTransmission(mpuAddress);
#if ARDUINO >= 100
Wire.write(reg);
Wire.write(value);
#else
Wire.send(reg);
Wire.send(value);
#endif
Wire.endTransmission();
}
int16_t MPU6050::readRegister16(uint8_t reg)
{
int16_t value;
Wire.beginTransmission(mpuAddress);
#if ARDUINO >= 100
Wire.write(reg);
#else
Wire.send(reg);
#endif
Wire.endTransmission();
Wire.beginTransmission(mpuAddress);
Wire.requestFrom(mpuAddress, 2);
while(!Wire.available()) {};
#if ARDUINO >= 100
uint8_t vha = Wire.read();
uint8_t vla = Wire.read();
#else
uint8_t vha = Wire.receive();
uint8_t vla = Wire.receive();
#endif;
Wire.endTransmission();
value = vha << 8 | vla;
return value;
}
void MPU6050::writeRegister16(uint8_t reg, int16_t value)
{
Wire.beginTransmission(mpuAddress);
#if ARDUINO >= 100
Wire.write(reg);
Wire.write((uint8_t)(value >> 8));
Wire.write((uint8_t)value);
#else
Wire.send(reg);
Wire.send((uint8_t)(value >> 8));
Wire.send((uint8_t)value);
#endif
Wire.endTransmission();
}
// Read register bit
bool MPU6050::readRegisterBit(uint8_t reg, uint8_t pos)
{
uint8_t value;
value = readRegister8(reg);
return ((value >> pos) & 1);
}
// Write register bit
void MPU6050::writeRegisterBit(uint8_t reg, uint8_t pos, bool state)
{
uint8_t value;
value = readRegister8(reg);
if (state)
{
value |= (1 << pos);
} else
{
value &= ~(1 << pos);
}
writeRegister8(reg, value);
}

View file

@ -0,0 +1,258 @@
/*
MPU6050.h - Header file for the MPU6050 Triple Axis Gyroscope & Accelerometer Arduino Library.
Version: 1.0.3
(c) 2014-2015 Korneliusz Jarzebski
www.jarzebski.pl
This program is free software: you can redistribute it and/or modify
it under the terms of the version 3 GNU General Public License as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MPU6050_h
#define MPU6050_h
#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#define MPU6050_ADDRESS (0x68) // 0x69 when AD0 pin to Vcc
#define MPU6050_REG_ACCEL_XOFFS_H (0x06)
#define MPU6050_REG_ACCEL_XOFFS_L (0x07)
#define MPU6050_REG_ACCEL_YOFFS_H (0x08)
#define MPU6050_REG_ACCEL_YOFFS_L (0x09)
#define MPU6050_REG_ACCEL_ZOFFS_H (0x0A)
#define MPU6050_REG_ACCEL_ZOFFS_L (0x0B)
#define MPU6050_REG_GYRO_XOFFS_H (0x13)
#define MPU6050_REG_GYRO_XOFFS_L (0x14)
#define MPU6050_REG_GYRO_YOFFS_H (0x15)
#define MPU6050_REG_GYRO_YOFFS_L (0x16)
#define MPU6050_REG_GYRO_ZOFFS_H (0x17)
#define MPU6050_REG_GYRO_ZOFFS_L (0x18)
#define MPU6050_REG_CONFIG (0x1A)
#define MPU6050_REG_GYRO_CONFIG (0x1B) // Gyroscope Configuration
#define MPU6050_REG_ACCEL_CONFIG (0x1C) // Accelerometer Configuration
#define MPU6050_REG_FF_THRESHOLD (0x1D)
#define MPU6050_REG_FF_DURATION (0x1E)
#define MPU6050_REG_MOT_THRESHOLD (0x1F)
#define MPU6050_REG_MOT_DURATION (0x20)
#define MPU6050_REG_ZMOT_THRESHOLD (0x21)
#define MPU6050_REG_ZMOT_DURATION (0x22)
#define MPU6050_REG_INT_PIN_CFG (0x37) // INT Pin. Bypass Enable Configuration
#define MPU6050_REG_INT_ENABLE (0x38) // INT Enable
#define MPU6050_REG_INT_STATUS (0x3A)
#define MPU6050_REG_ACCEL_XOUT_H (0x3B)
#define MPU6050_REG_ACCEL_XOUT_L (0x3C)
#define MPU6050_REG_ACCEL_YOUT_H (0x3D)
#define MPU6050_REG_ACCEL_YOUT_L (0x3E)
#define MPU6050_REG_ACCEL_ZOUT_H (0x3F)
#define MPU6050_REG_ACCEL_ZOUT_L (0x40)
#define MPU6050_REG_TEMP_OUT_H (0x41)
#define MPU6050_REG_TEMP_OUT_L (0x42)
#define MPU6050_REG_GYRO_XOUT_H (0x43)
#define MPU6050_REG_GYRO_XOUT_L (0x44)
#define MPU6050_REG_GYRO_YOUT_H (0x45)
#define MPU6050_REG_GYRO_YOUT_L (0x46)
#define MPU6050_REG_GYRO_ZOUT_H (0x47)
#define MPU6050_REG_GYRO_ZOUT_L (0x48)
#define MPU6050_REG_MOT_DETECT_STATUS (0x61)
#define MPU6050_REG_MOT_DETECT_CTRL (0x69)
#define MPU6050_REG_USER_CTRL (0x6A) // User Control
#define MPU6050_REG_PWR_MGMT_1 (0x6B) // Power Management 1
#define MPU6050_REG_WHO_AM_I (0x75) // Who Am I
#ifndef VECTOR_STRUCT_H
#define VECTOR_STRUCT_H
struct Vector
{
float XAxis;
float YAxis;
float ZAxis;
};
#endif
struct Activites
{
bool isOverflow;
bool isFreeFall;
bool isInactivity;
bool isActivity;
bool isPosActivityOnX;
bool isPosActivityOnY;
bool isPosActivityOnZ;
bool isNegActivityOnX;
bool isNegActivityOnY;
bool isNegActivityOnZ;
bool isDataReady;
};
typedef enum
{
MPU6050_CLOCK_KEEP_RESET = 0b111,
MPU6050_CLOCK_EXTERNAL_19MHZ = 0b101,
MPU6050_CLOCK_EXTERNAL_32KHZ = 0b100,
MPU6050_CLOCK_PLL_ZGYRO = 0b011,
MPU6050_CLOCK_PLL_YGYRO = 0b010,
MPU6050_CLOCK_PLL_XGYRO = 0b001,
MPU6050_CLOCK_INTERNAL_8MHZ = 0b000
} mpu6050_clockSource_t;
typedef enum
{
MPU6050_SCALE_2000DPS = 0b11,
MPU6050_SCALE_1000DPS = 0b10,
MPU6050_SCALE_500DPS = 0b01,
MPU6050_SCALE_250DPS = 0b00
} mpu6050_dps_t;
typedef enum
{
MPU6050_RANGE_16G = 0b11,
MPU6050_RANGE_8G = 0b10,
MPU6050_RANGE_4G = 0b01,
MPU6050_RANGE_2G = 0b00,
} mpu6050_range_t;
typedef enum
{
MPU6050_DELAY_3MS = 0b11,
MPU6050_DELAY_2MS = 0b10,
MPU6050_DELAY_1MS = 0b01,
MPU6050_NO_DELAY = 0b00,
} mpu6050_onDelay_t;
typedef enum
{
MPU6050_DHPF_HOLD = 0b111,
MPU6050_DHPF_0_63HZ = 0b100,
MPU6050_DHPF_1_25HZ = 0b011,
MPU6050_DHPF_2_5HZ = 0b010,
MPU6050_DHPF_5HZ = 0b001,
MPU6050_DHPF_RESET = 0b000,
} mpu6050_dhpf_t;
typedef enum
{
MPU6050_DLPF_6 = 0b110,
MPU6050_DLPF_5 = 0b101,
MPU6050_DLPF_4 = 0b100,
MPU6050_DLPF_3 = 0b011,
MPU6050_DLPF_2 = 0b010,
MPU6050_DLPF_1 = 0b001,
MPU6050_DLPF_0 = 0b000,
} mpu6050_dlpf_t;
class MPU6050
{
public:
bool begin(mpu6050_dps_t scale = MPU6050_SCALE_2000DPS, mpu6050_range_t range = MPU6050_RANGE_2G, int mpua = MPU6050_ADDRESS);
void setClockSource(mpu6050_clockSource_t source);
void setScale(mpu6050_dps_t scale);
void setRange(mpu6050_range_t range);
mpu6050_clockSource_t getClockSource(void);
mpu6050_dps_t getScale(void);
mpu6050_range_t getRange(void);
void setDHPFMode(mpu6050_dhpf_t dhpf);
void setDLPFMode(mpu6050_dlpf_t dlpf);
mpu6050_onDelay_t getAccelPowerOnDelay();
void setAccelPowerOnDelay(mpu6050_onDelay_t delay);
uint8_t getIntStatus(void);
bool getIntZeroMotionEnabled(void);
void setIntZeroMotionEnabled(bool state);
bool getIntMotionEnabled(void);
void setIntMotionEnabled(bool state);
bool getIntFreeFallEnabled(void);
void setIntFreeFallEnabled(bool state);
uint8_t getMotionDetectionThreshold(void);
void setMotionDetectionThreshold(uint8_t threshold);
uint8_t getMotionDetectionDuration(void);
void setMotionDetectionDuration(uint8_t duration);
uint8_t getZeroMotionDetectionThreshold(void);
void setZeroMotionDetectionThreshold(uint8_t threshold);
uint8_t getZeroMotionDetectionDuration(void);
void setZeroMotionDetectionDuration(uint8_t duration);
uint8_t getFreeFallDetectionThreshold(void);
void setFreeFallDetectionThreshold(uint8_t threshold);
uint8_t getFreeFallDetectionDuration(void);
void setFreeFallDetectionDuration(uint8_t duration);
bool getSleepEnabled(void);
void setSleepEnabled(bool state);
bool getI2CMasterModeEnabled(void);
void setI2CMasterModeEnabled(bool state);
bool getI2CBypassEnabled(void);
void setI2CBypassEnabled(bool state);
float readTemperature(void);
Activites readActivites(void);
int16_t getGyroOffsetX(void);
void setGyroOffsetX(int16_t offset);
int16_t getGyroOffsetY(void);
void setGyroOffsetY(int16_t offset);
int16_t getGyroOffsetZ(void);
void setGyroOffsetZ(int16_t offset);
int16_t getAccelOffsetX(void);
void setAccelOffsetX(int16_t offset);
int16_t getAccelOffsetY(void);
void setAccelOffsetY(int16_t offset);
int16_t getAccelOffsetZ(void);
void setAccelOffsetZ(int16_t offset);
void calibrateGyro(uint8_t samples = 50);
void setThreshold(uint8_t multiple = 1);
uint8_t getThreshold(void);
Vector readRawGyro(void);
Vector readNormalizeGyro(void);
Vector readRawAccel(void);
Vector readNormalizeAccel(void);
Vector readScaledAccel(void);
private:
Vector ra, rg; // Raw vectors
Vector na, ng; // Normalized vectors
Vector tg, dg; // Threshold and Delta for Gyro
Vector th; // Threshold
Activites a; // Activities
float dpsPerDigit, rangePerDigit;
float actualThreshold;
bool useCalibrate;
int mpuAddress;
uint8_t fastRegister8(uint8_t reg);
uint8_t readRegister8(uint8_t reg);
void writeRegister8(uint8_t reg, uint8_t value);
int16_t readRegister16(uint8_t reg);
void writeRegister16(uint8_t reg, int16_t value);
bool readRegisterBit(uint8_t reg, uint8_t pos);
void writeRegisterBit(uint8_t reg, uint8_t pos, bool state);
};
#endif

View file

@ -0,0 +1,47 @@
/*
MPU6050 Triple Axis Gyroscope & Accelerometer. Pitch & Roll Accelerometer Example.
Read more: http://www.jarzebski.pl/arduino/czujniki-i-sensory/3-osiowy-zyroskop-i-akcelerometr-mpu6050.html
GIT: https://github.com/jarzebski/Arduino-MPU6050
Web: http://www.jarzebski.pl
(c) 2014 by Korneliusz Jarzebski
*/
#include <Wire.h>
#include <MPU6050.h>
MPU6050 mpu;
void setup()
{
Serial.begin(115200);
Serial.println("Initialize MPU6050");
while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
{
Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
delay(500);
}
}
void loop()
{
// Read normalized values
Vector normAccel = mpu.readNormalizeAccel();
// Calculate Pitch & Roll
int pitch = -(atan2(normAccel.XAxis, sqrt(normAccel.YAxis*normAccel.YAxis + normAccel.ZAxis*normAccel.ZAxis))*180.0)/M_PI;
int roll = (atan2(normAccel.YAxis, normAccel.ZAxis)*180.0)/M_PI;
// Output
Serial.print(" Pitch = ");
Serial.print(pitch);
Serial.print(" Roll = ");
Serial.print(roll);
Serial.println();
delay(10);
}

View file

@ -0,0 +1,94 @@
/*
MPU6050 Triple Axis Gyroscope & Accelerometer. Simple Accelerometer Example.
Read more: http://www.jarzebski.pl/arduino/czujniki-i-sensory/3-osiowy-zyroskop-i-akcelerometr-mpu6050.html
GIT: https://github.com/jarzebski/Arduino-MPU6050
Web: http://www.jarzebski.pl
(c) 2014 by Korneliusz Jarzebski
*/
#include <Wire.h>
#include <MPU6050.h>
MPU6050 mpu;
void setup()
{
Serial.begin(115200);
Serial.println("Initialize MPU6050");
while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
{
Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
delay(500);
}
// If you want, you can set accelerometer offsets
// mpu.setAccelOffsetX();
// mpu.setAccelOffsetY();
// mpu.setAccelOffsetZ();
checkSettings();
}
void checkSettings()
{
Serial.println();
Serial.print(" * Sleep Mode: ");
Serial.println(mpu.getSleepEnabled() ? "Enabled" : "Disabled");
Serial.print(" * Clock Source: ");
switch(mpu.getClockSource())
{
case MPU6050_CLOCK_KEEP_RESET: Serial.println("Stops the clock and keeps the timing generator in reset"); break;
case MPU6050_CLOCK_EXTERNAL_19MHZ: Serial.println("PLL with external 19.2MHz reference"); break;
case MPU6050_CLOCK_EXTERNAL_32KHZ: Serial.println("PLL with external 32.768kHz reference"); break;
case MPU6050_CLOCK_PLL_ZGYRO: Serial.println("PLL with Z axis gyroscope reference"); break;
case MPU6050_CLOCK_PLL_YGYRO: Serial.println("PLL with Y axis gyroscope reference"); break;
case MPU6050_CLOCK_PLL_XGYRO: Serial.println("PLL with X axis gyroscope reference"); break;
case MPU6050_CLOCK_INTERNAL_8MHZ: Serial.println("Internal 8MHz oscillator"); break;
}
Serial.print(" * Accelerometer: ");
switch(mpu.getRange())
{
case MPU6050_RANGE_16G: Serial.println("+/- 16 g"); break;
case MPU6050_RANGE_8G: Serial.println("+/- 8 g"); break;
case MPU6050_RANGE_4G: Serial.println("+/- 4 g"); break;
case MPU6050_RANGE_2G: Serial.println("+/- 2 g"); break;
}
Serial.print(" * Accelerometer offsets: ");
Serial.print(mpu.getAccelOffsetX());
Serial.print(" / ");
Serial.print(mpu.getAccelOffsetY());
Serial.print(" / ");
Serial.println(mpu.getAccelOffsetZ());
Serial.println();
}
void loop()
{
Vector rawAccel = mpu.readRawAccel();
Vector normAccel = mpu.readNormalizeAccel();
Serial.print(" Xraw = ");
Serial.print(rawAccel.XAxis);
Serial.print(" Yraw = ");
Serial.print(rawAccel.YAxis);
Serial.print(" Zraw = ");
Serial.println(rawAccel.ZAxis);
Serial.print(" Xnorm = ");
Serial.print(normAccel.XAxis);
Serial.print(" Ynorm = ");
Serial.print(normAccel.YAxis);
Serial.print(" Znorm = ");
Serial.println(normAccel.ZAxis);
delay(10);
}

View file

@ -0,0 +1,143 @@
/*
MPU6050 Triple Axis Gyroscope & Accelerometer. Free fall detection.
Read more: http://www.jarzebski.pl/arduino/czujniki-i-sensory/3-osiowy-zyroskop-i-akcelerometr-mpu6050.html
GIT: https://github.com/jarzebski/Arduino-MPU6050
Web: http://www.jarzebski.pl
(c) 2014 by Korneliusz Jarzebski
*/
#include <Wire.h>
#include <MPU6050.h>
MPU6050 mpu;
boolean ledState = false;
boolean freefallDetected = false;
int freefallBlinkCount = 0;
void setup()
{
Serial.begin(115200);
Serial.println("Initialize MPU6050");
while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_16G))
{
Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
delay(500);
}
mpu.setAccelPowerOnDelay(MPU6050_DELAY_3MS);
mpu.setIntFreeFallEnabled(true);
mpu.setIntZeroMotionEnabled(false);
mpu.setIntMotionEnabled(false);
mpu.setDHPFMode(MPU6050_DHPF_5HZ);
mpu.setFreeFallDetectionThreshold(17);
mpu.setFreeFallDetectionDuration(2);
checkSettings();
pinMode(4, OUTPUT);
digitalWrite(4, LOW);
attachInterrupt(0, doInt, RISING);
}
void doInt()
{
freefallBlinkCount = 0;
freefallDetected = true;
}
void checkSettings()
{
Serial.println();
Serial.print(" * Sleep Mode: ");
Serial.println(mpu.getSleepEnabled() ? "Enabled" : "Disabled");
Serial.print(" * Motion Interrupt: ");
Serial.println(mpu.getIntMotionEnabled() ? "Enabled" : "Disabled");
Serial.print(" * Zero Motion Interrupt: ");
Serial.println(mpu.getIntZeroMotionEnabled() ? "Enabled" : "Disabled");
Serial.print(" * Free Fall Interrupt: ");
Serial.println(mpu.getIntFreeFallEnabled() ? "Enabled" : "Disabled");
Serial.print(" * Free Fal Threshold: ");
Serial.println(mpu.getFreeFallDetectionThreshold());
Serial.print(" * Free FallDuration: ");
Serial.println(mpu.getFreeFallDetectionDuration());
Serial.print(" * Clock Source: ");
switch(mpu.getClockSource())
{
case MPU6050_CLOCK_KEEP_RESET: Serial.println("Stops the clock and keeps the timing generator in reset"); break;
case MPU6050_CLOCK_EXTERNAL_19MHZ: Serial.println("PLL with external 19.2MHz reference"); break;
case MPU6050_CLOCK_EXTERNAL_32KHZ: Serial.println("PLL with external 32.768kHz reference"); break;
case MPU6050_CLOCK_PLL_ZGYRO: Serial.println("PLL with Z axis gyroscope reference"); break;
case MPU6050_CLOCK_PLL_YGYRO: Serial.println("PLL with Y axis gyroscope reference"); break;
case MPU6050_CLOCK_PLL_XGYRO: Serial.println("PLL with X axis gyroscope reference"); break;
case MPU6050_CLOCK_INTERNAL_8MHZ: Serial.println("Internal 8MHz oscillator"); break;
}
Serial.print(" * Accelerometer: ");
switch(mpu.getRange())
{
case MPU6050_RANGE_16G: Serial.println("+/- 16 g"); break;
case MPU6050_RANGE_8G: Serial.println("+/- 8 g"); break;
case MPU6050_RANGE_4G: Serial.println("+/- 4 g"); break;
case MPU6050_RANGE_2G: Serial.println("+/- 2 g"); break;
}
Serial.print(" * Accelerometer offsets: ");
Serial.print(mpu.getAccelOffsetX());
Serial.print(" / ");
Serial.print(mpu.getAccelOffsetY());
Serial.print(" / ");
Serial.println(mpu.getAccelOffsetZ());
Serial.print(" * Accelerometer power delay: ");
switch(mpu.getAccelPowerOnDelay())
{
case MPU6050_DELAY_3MS: Serial.println("3ms"); break;
case MPU6050_DELAY_2MS: Serial.println("2ms"); break;
case MPU6050_DELAY_1MS: Serial.println("1ms"); break;
case MPU6050_NO_DELAY: Serial.println("0ms"); break;
}
Serial.println();
}
void loop()
{
Vector rawAccel = mpu.readRawAccel();
Activites act = mpu.readActivites();
Serial.print(act.isFreeFall);
Serial.print("\n");
if (freefallDetected)
{
ledState = !ledState;
digitalWrite(4, ledState);
freefallBlinkCount++;
if (freefallBlinkCount == 20)
{
freefallDetected = false;
ledState = false;
digitalWrite(4, ledState);
}
}
delay(100);
}

View file

@ -0,0 +1,65 @@
/*
MPU6050 Triple Axis Gyroscope & Accelerometer. Pitch & Roll & Yaw Gyroscope Example.
Read more: http://www.jarzebski.pl/arduino/czujniki-i-sensory/3-osiowy-zyroskop-i-akcelerometr-mpu6050.html
GIT: https://github.com/jarzebski/Arduino-MPU6050
Web: http://www.jarzebski.pl
(c) 2014 by Korneliusz Jarzebski
*/
#include <Wire.h>
#include <MPU6050.h>
MPU6050 mpu;
// Timers
unsigned long timer = 0;
float timeStep = 0.01;
// Pitch, Roll and Yaw values
float pitch = 0;
float roll = 0;
float yaw = 0;
void setup()
{
Serial.begin(115200);
// Initialize MPU6050
while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
{
Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
delay(500);
}
// Calibrate gyroscope. The calibration must be at rest.
// If you don't want calibrate, comment this line.
mpu.calibrateGyro();
// Set threshold sensivty. Default 3.
// If you don't want use threshold, comment this line or set 0.
mpu.setThreshold(3);
}
void loop()
{
timer = millis();
// Read normalized values
Vector norm = mpu.readNormalizeGyro();
// Calculate Pitch, Roll and Yaw
pitch = pitch + norm.YAxis * timeStep;
roll = roll + norm.XAxis * timeStep;
yaw = yaw + norm.ZAxis * timeStep;
// Output raw
Serial.print(" Pitch = ");
Serial.print(pitch);
Serial.print(" Roll = ");
Serial.print(roll);
Serial.print(" Yaw = ");
Serial.println(yaw);
// Wait to full timeStep period
delay((timeStep*1000) - (millis() - timer));
}

View file

@ -0,0 +1,103 @@
/*
MPU6050 Triple Axis Gyroscope & Accelerometer. Simple Gyroscope Example.
Read more: http://www.jarzebski.pl/arduino/czujniki-i-sensory/3-osiowy-zyroskop-i-akcelerometr-mpu6050.html
GIT: https://github.com/jarzebski/Arduino-MPU6050
Web: http://www.jarzebski.pl
(c) 2014 by Korneliusz Jarzebski
*/
#include <Wire.h>
#include <MPU6050.h>
MPU6050 mpu;
void setup()
{
Serial.begin(115200);
// Initialize MPU6050
Serial.println("Initialize MPU6050");
while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
{
Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
delay(500);
}
// If you want, you can set gyroscope offsets
// mpu.setGyroOffsetX(155);
// mpu.setGyroOffsetY(15);
// mpu.setGyroOffsetZ(15);
// Calibrate gyroscope. The calibration must be at rest.
// If you don't want calibrate, comment this line.
mpu.calibrateGyro();
// Set threshold sensivty. Default 3.
// If you don't want use threshold, comment this line or set 0.
mpu.setThreshold(3);
// Check settings
checkSettings();
}
void checkSettings()
{
Serial.println();
Serial.print(" * Sleep Mode: ");
Serial.println(mpu.getSleepEnabled() ? "Enabled" : "Disabled");
Serial.print(" * Clock Source: ");
switch(mpu.getClockSource())
{
case MPU6050_CLOCK_KEEP_RESET: Serial.println("Stops the clock and keeps the timing generator in reset"); break;
case MPU6050_CLOCK_EXTERNAL_19MHZ: Serial.println("PLL with external 19.2MHz reference"); break;
case MPU6050_CLOCK_EXTERNAL_32KHZ: Serial.println("PLL with external 32.768kHz reference"); break;
case MPU6050_CLOCK_PLL_ZGYRO: Serial.println("PLL with Z axis gyroscope reference"); break;
case MPU6050_CLOCK_PLL_YGYRO: Serial.println("PLL with Y axis gyroscope reference"); break;
case MPU6050_CLOCK_PLL_XGYRO: Serial.println("PLL with X axis gyroscope reference"); break;
case MPU6050_CLOCK_INTERNAL_8MHZ: Serial.println("Internal 8MHz oscillator"); break;
}
Serial.print(" * Gyroscope: ");
switch(mpu.getScale())
{
case MPU6050_SCALE_2000DPS: Serial.println("2000 dps"); break;
case MPU6050_SCALE_1000DPS: Serial.println("1000 dps"); break;
case MPU6050_SCALE_500DPS: Serial.println("500 dps"); break;
case MPU6050_SCALE_250DPS: Serial.println("250 dps"); break;
}
Serial.print(" * Gyroscope offsets: ");
Serial.print(mpu.getGyroOffsetX());
Serial.print(" / ");
Serial.print(mpu.getGyroOffsetY());
Serial.print(" / ");
Serial.println(mpu.getGyroOffsetZ());
Serial.println();
}
void loop()
{
Vector rawGyro = mpu.readRawGyro();
Vector normGyro = mpu.readNormalizeGyro();
Serial.print(" Xraw = ");
Serial.print(rawGyro.XAxis);
Serial.print(" Yraw = ");
Serial.print(rawGyro.YAxis);
Serial.print(" Zraw = ");
Serial.println(rawGyro.ZAxis);
Serial.print(" Xnorm = ");
Serial.print(normGyro.XAxis);
Serial.print(" Ynorm = ");
Serial.print(normGyro.YAxis);
Serial.print(" Znorm = ");
Serial.println(normGyro.ZAxis);
delay(10);
}

View file

@ -0,0 +1,156 @@
/*
MPU6050 Triple Axis Gyroscope & Accelerometer. Motion detection.
Read more: http://www.jarzebski.pl/arduino/czujniki-i-sensory/3-osiowy-zyroskop-i-akcelerometr-mpu6050.html
GIT: https://github.com/jarzebski/Arduino-MPU6050
Web: http://www.jarzebski.pl
(c) 2014 by Korneliusz Jarzebski
*/
#include <Wire.h>
#include <MPU6050.h>
MPU6050 mpu;
void setup()
{
Serial.begin(115200);
Serial.println("Initialize MPU6050");
while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_16G))
{
Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
delay(500);
}
mpu.setAccelPowerOnDelay(MPU6050_DELAY_3MS);
mpu.setIntFreeFallEnabled(false);
mpu.setIntZeroMotionEnabled(false);
mpu.setIntMotionEnabled(false);
mpu.setDHPFMode(MPU6050_DHPF_5HZ);
mpu.setMotionDetectionThreshold(2);
mpu.setMotionDetectionDuration(5);
mpu.setZeroMotionDetectionThreshold(4);
mpu.setZeroMotionDetectionDuration(2);
checkSettings();
pinMode(4, OUTPUT);
digitalWrite(4, LOW);
pinMode(7, OUTPUT);
digitalWrite(7, LOW);
}
void checkSettings()
{
Serial.println();
Serial.print(" * Sleep Mode: ");
Serial.println(mpu.getSleepEnabled() ? "Enabled" : "Disabled");
Serial.print(" * Motion Interrupt: ");
Serial.println(mpu.getIntMotionEnabled() ? "Enabled" : "Disabled");
Serial.print(" * Zero Motion Interrupt: ");
Serial.println(mpu.getIntZeroMotionEnabled() ? "Enabled" : "Disabled");
Serial.print(" * Free Fall Interrupt: ");
Serial.println(mpu.getIntFreeFallEnabled() ? "Enabled" : "Disabled");
Serial.print(" * Motion Threshold: ");
Serial.println(mpu.getMotionDetectionThreshold());
Serial.print(" * Motion Duration: ");
Serial.println(mpu.getMotionDetectionDuration());
Serial.print(" * Zero Motion Threshold: ");
Serial.println(mpu.getZeroMotionDetectionThreshold());
Serial.print(" * Zero Motion Duration: ");
Serial.println(mpu.getZeroMotionDetectionDuration());
Serial.print(" * Clock Source: ");
switch(mpu.getClockSource())
{
case MPU6050_CLOCK_KEEP_RESET: Serial.println("Stops the clock and keeps the timing generator in reset"); break;
case MPU6050_CLOCK_EXTERNAL_19MHZ: Serial.println("PLL with external 19.2MHz reference"); break;
case MPU6050_CLOCK_EXTERNAL_32KHZ: Serial.println("PLL with external 32.768kHz reference"); break;
case MPU6050_CLOCK_PLL_ZGYRO: Serial.println("PLL with Z axis gyroscope reference"); break;
case MPU6050_CLOCK_PLL_YGYRO: Serial.println("PLL with Y axis gyroscope reference"); break;
case MPU6050_CLOCK_PLL_XGYRO: Serial.println("PLL with X axis gyroscope reference"); break;
case MPU6050_CLOCK_INTERNAL_8MHZ: Serial.println("Internal 8MHz oscillator"); break;
}
Serial.print(" * Accelerometer: ");
switch(mpu.getRange())
{
case MPU6050_RANGE_16G: Serial.println("+/- 16 g"); break;
case MPU6050_RANGE_8G: Serial.println("+/- 8 g"); break;
case MPU6050_RANGE_4G: Serial.println("+/- 4 g"); break;
case MPU6050_RANGE_2G: Serial.println("+/- 2 g"); break;
}
Serial.print(" * Accelerometer offsets: ");
Serial.print(mpu.getAccelOffsetX());
Serial.print(" / ");
Serial.print(mpu.getAccelOffsetY());
Serial.print(" / ");
Serial.println(mpu.getAccelOffsetZ());
Serial.print(" * Accelerometer power delay: ");
switch(mpu.getAccelPowerOnDelay())
{
case MPU6050_DELAY_3MS: Serial.println("3ms"); break;
case MPU6050_DELAY_2MS: Serial.println("2ms"); break;
case MPU6050_DELAY_1MS: Serial.println("1ms"); break;
case MPU6050_NO_DELAY: Serial.println("0ms"); break;
}
Serial.println();
}
void loop()
{
Vector rawAccel = mpu.readRawAccel();
Activites act = mpu.readActivites();
if (act.isActivity)
{
digitalWrite(4, HIGH);
} else
{
digitalWrite(4, LOW);
}
if (act.isInactivity)
{
digitalWrite(7, HIGH);
} else
{
digitalWrite(7, LOW);
}
Serial.print(act.isActivity);
Serial.print(act.isInactivity);
Serial.print(" ");
Serial.print(act.isPosActivityOnX);
Serial.print(act.isNegActivityOnX);
Serial.print(" ");
Serial.print(act.isPosActivityOnY);
Serial.print(act.isNegActivityOnY);
Serial.print(" ");
Serial.print(act.isPosActivityOnZ);
Serial.print(act.isNegActivityOnZ);
Serial.print("\n");
delay(50);
}

View file

@ -0,0 +1,38 @@
/*
MPU6050 Triple Axis Gyroscope & Accelerometer. Temperature Example.
Read more: http://www.jarzebski.pl/arduino/czujniki-i-sensory/3-osiowy-zyroskop-i-akcelerometr-mpu6050.html
GIT: https://github.com/jarzebski/Arduino-MPU6050
Web: http://www.jarzebski.pl
(c) 2014 by Korneliusz Jarzebski
*/
#include <Wire.h>
#include <MPU6050.h>
MPU6050 mpu;
void setup()
{
Serial.begin(115200);
Serial.println("Initialize MPU6050");
while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
{
Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
delay(500);
}
}
void loop()
{
float temp = mpu.readTemperature();
Serial.print(" Temp = ");
Serial.print(temp);
Serial.println(" *C");
delay(500);
}

View file

@ -0,0 +1,25 @@
Arduino-MPU6050
===============
MPU6050 Triple Axis Gyroscope & Accelerometer Arduino Library.
![MPU6050 Processing](http://www.jarzebski.pl/media/zoom/publish/2014/10/mpu6050-processing-2.png "MPU6050 Processing")
Tutorials: http://www.jarzebski.pl/arduino/czujniki-i-sensory/3-osiowy-zyroskop-i-akcelerometr-mpu6050.html
This library use I2C to communicate, 2 pins are required to interface
I need your help
----------------
July 31, 2017
In the near future I plan to refactoring the libraries. The main goal is to improve code quality, new features and add support for different versions of Arduino boards like Uno, Mega and Zero.
For this purpose I need to buy modules, Arduino Boards and lot of beer.
If you want to support the further and long-term development of libraries, please help.
You can do this by transferring any amount to my PayPal account: paypal@jarzebski.pl
Thanks!

1
libraries/readme.txt Executable file
View file

@ -0,0 +1 @@
For information on installing libraries, see: http://www.arduino.cc/en/Guide/Libraries

BIN
syllabus.docx Executable file

Binary file not shown.