file_path
stringlengths 21
207
| content
stringlengths 5
1.02M
| size
int64 5
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 2.5
98.5
| max_line_length
int64 5
993
| alphanum_fraction
float64 0.27
0.91
|
---|---|---|---|---|---|---|
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/unitree_ros-CHAMP/robots/a1_description/config/robot_control.yaml | a1_gazebo:
# Publish all joint states -----------------------------------
joint_state_controller:
type: joint_state_controller/JointStateController
publish_rate: 1000
# FL Controllers ---------------------------------------
FL_hip_controller:
type: unitree_legged_control/UnitreeJointController
joint: FL_hip_joint
pid: {p: 100.0, i: 0.0, d: 5.0}
FL_thigh_controller:
type: unitree_legged_control/UnitreeJointController
joint: FL_thigh_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
FL_calf_controller:
type: unitree_legged_control/UnitreeJointController
joint: FL_calf_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
# FR Controllers ---------------------------------------
FR_hip_controller:
type: unitree_legged_control/UnitreeJointController
joint: FR_hip_joint
pid: {p: 100.0, i: 0.0, d: 5.0}
FR_thigh_controller:
type: unitree_legged_control/UnitreeJointController
joint: FR_thigh_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
FR_calf_controller:
type: unitree_legged_control/UnitreeJointController
joint: FR_calf_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
# RL Controllers ---------------------------------------
RL_hip_controller:
type: unitree_legged_control/UnitreeJointController
joint: RL_hip_joint
pid: {p: 100.0, i: 0.0, d: 5.0}
RL_thigh_controller:
type: unitree_legged_control/UnitreeJointController
joint: RL_thigh_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
RL_calf_controller:
type: unitree_legged_control/UnitreeJointController
joint: RL_calf_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
# RR Controllers ---------------------------------------
RR_hip_controller:
type: unitree_legged_control/UnitreeJointController
joint: RR_hip_joint
pid: {p: 100.0, i: 0.0, d: 5.0}
RR_thigh_controller:
type: unitree_legged_control/UnitreeJointController
joint: RR_thigh_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
RR_calf_controller:
type: unitree_legged_control/UnitreeJointController
joint: RR_calf_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
| 2,286 | YAML | 31.211267 | 66 | 0.552931 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/unitree_ros-CHAMP/robots/aliengo_description/config/robot_control.yaml | aliengo_gazebo:
# Publish all joint states -----------------------------------
joint_state_controller:
type: joint_state_controller/JointStateController
publish_rate: 1000
# FL Controllers ---------------------------------------
FL_hip_controller:
type: unitree_legged_control/UnitreeJointController
joint: FL_hip_joint
pid: {p: 100.0, i: 0.0, d: 5.0}
FL_thigh_controller:
type: unitree_legged_control/UnitreeJointController
joint: FL_thigh_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
FL_calf_controller:
type: unitree_legged_control/UnitreeJointController
joint: FL_calf_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
# FR Controllers ---------------------------------------
FR_hip_controller:
type: unitree_legged_control/UnitreeJointController
joint: FR_hip_joint
pid: {p: 100.0, i: 0.0, d: 5.0}
FR_thigh_controller:
type: unitree_legged_control/UnitreeJointController
joint: FR_thigh_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
FR_calf_controller:
type: unitree_legged_control/UnitreeJointController
joint: FR_calf_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
# RL Controllers ---------------------------------------
RL_hip_controller:
type: unitree_legged_control/UnitreeJointController
joint: RL_hip_joint
pid: {p: 100.0, i: 0.0, d: 5.0}
RL_thigh_controller:
type: unitree_legged_control/UnitreeJointController
joint: RL_thigh_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
RL_calf_controller:
type: unitree_legged_control/UnitreeJointController
joint: RL_calf_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
# RR Controllers ---------------------------------------
RR_hip_controller:
type: unitree_legged_control/UnitreeJointController
joint: RR_hip_joint
pid: {p: 100.0, i: 0.0, d: 5.0}
RR_thigh_controller:
type: unitree_legged_control/UnitreeJointController
joint: RR_thigh_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
RR_calf_controller:
type: unitree_legged_control/UnitreeJointController
joint: RR_calf_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
| 2,291 | YAML | 31.28169 | 66 | 0.553907 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/unitree_ros-CHAMP/robots/go1_description/config/robot_control.yaml | go1_gazebo:
# Publish all joint states -----------------------------------
joint_state_controller:
type: joint_state_controller/JointStateController
publish_rate: 1000
# FL Controllers ---------------------------------------
FL_hip_controller:
type: unitree_legged_control/UnitreeJointController
joint: FL_hip_joint
pid: {p: 100.0, i: 0.0, d: 5.0}
FL_thigh_controller:
type: unitree_legged_control/UnitreeJointController
joint: FL_thigh_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
FL_calf_controller:
type: unitree_legged_control/UnitreeJointController
joint: FL_calf_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
# FR Controllers ---------------------------------------
FR_hip_controller:
type: unitree_legged_control/UnitreeJointController
joint: FR_hip_joint
pid: {p: 100.0, i: 0.0, d: 5.0}
FR_thigh_controller:
type: unitree_legged_control/UnitreeJointController
joint: FR_thigh_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
FR_calf_controller:
type: unitree_legged_control/UnitreeJointController
joint: FR_calf_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
# RL Controllers ---------------------------------------
RL_hip_controller:
type: unitree_legged_control/UnitreeJointController
joint: RL_hip_joint
pid: {p: 100.0, i: 0.0, d: 5.0}
RL_thigh_controller:
type: unitree_legged_control/UnitreeJointController
joint: RL_thigh_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
RL_calf_controller:
type: unitree_legged_control/UnitreeJointController
joint: RL_calf_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
# RR Controllers ---------------------------------------
RR_hip_controller:
type: unitree_legged_control/UnitreeJointController
joint: RR_hip_joint
pid: {p: 100.0, i: 0.0, d: 5.0}
RR_thigh_controller:
type: unitree_legged_control/UnitreeJointController
joint: RR_thigh_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
RR_calf_controller:
type: unitree_legged_control/UnitreeJointController
joint: RR_calf_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
| 2,287 | YAML | 31.225352 | 66 | 0.553126 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/b1_description/config/robot_control.yaml | b1_gazebo:
# Publish all joint states -----------------------------------
joint_state_controller:
type: joint_state_controller/JointStateController
publish_rate: 1000
# FL Controllers ---------------------------------------
FL_hip_controller:
type: unitree_legged_control/UnitreeJointController
joint: FL_hip_joint
pid: {p: 100.0, i: 0.0, d: 5.0}
FL_thigh_controller:
type: unitree_legged_control/UnitreeJointController
joint: FL_thigh_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
FL_calf_controller:
type: unitree_legged_control/UnitreeJointController
joint: FL_calf_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
# FR Controllers ---------------------------------------
FR_hip_controller:
type: unitree_legged_control/UnitreeJointController
joint: FR_hip_joint
pid: {p: 100.0, i: 0.0, d: 5.0}
FR_thigh_controller:
type: unitree_legged_control/UnitreeJointController
joint: FR_thigh_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
FR_calf_controller:
type: unitree_legged_control/UnitreeJointController
joint: FR_calf_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
# RL Controllers ---------------------------------------
RL_hip_controller:
type: unitree_legged_control/UnitreeJointController
joint: RL_hip_joint
pid: {p: 100.0, i: 0.0, d: 5.0}
RL_thigh_controller:
type: unitree_legged_control/UnitreeJointController
joint: RL_thigh_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
RL_calf_controller:
type: unitree_legged_control/UnitreeJointController
joint: RL_calf_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
# RR Controllers ---------------------------------------
RR_hip_controller:
type: unitree_legged_control/UnitreeJointController
joint: RR_hip_joint
pid: {p: 100.0, i: 0.0, d: 5.0}
RR_thigh_controller:
type: unitree_legged_control/UnitreeJointController
joint: RR_thigh_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
RR_calf_controller:
type: unitree_legged_control/UnitreeJointController
joint: RR_calf_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
| 2,286 | YAML | 31.211267 | 66 | 0.552931 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/aliengo_description/config/robot_control.yaml | aliengo_gazebo:
# Publish all joint states -----------------------------------
joint_state_controller:
type: joint_state_controller/JointStateController
publish_rate: 1000
# FL Controllers ---------------------------------------
FL_hip_controller:
type: unitree_legged_control/UnitreeJointController
joint: FL_hip_joint
pid: {p: 100.0, i: 0.0, d: 5.0}
FL_thigh_controller:
type: unitree_legged_control/UnitreeJointController
joint: FL_thigh_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
FL_calf_controller:
type: unitree_legged_control/UnitreeJointController
joint: FL_calf_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
# FR Controllers ---------------------------------------
FR_hip_controller:
type: unitree_legged_control/UnitreeJointController
joint: FR_hip_joint
pid: {p: 100.0, i: 0.0, d: 5.0}
FR_thigh_controller:
type: unitree_legged_control/UnitreeJointController
joint: FR_thigh_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
FR_calf_controller:
type: unitree_legged_control/UnitreeJointController
joint: FR_calf_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
# RL Controllers ---------------------------------------
RL_hip_controller:
type: unitree_legged_control/UnitreeJointController
joint: RL_hip_joint
pid: {p: 100.0, i: 0.0, d: 5.0}
RL_thigh_controller:
type: unitree_legged_control/UnitreeJointController
joint: RL_thigh_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
RL_calf_controller:
type: unitree_legged_control/UnitreeJointController
joint: RL_calf_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
# RR Controllers ---------------------------------------
RR_hip_controller:
type: unitree_legged_control/UnitreeJointController
joint: RR_hip_joint
pid: {p: 100.0, i: 0.0, d: 5.0}
RR_thigh_controller:
type: unitree_legged_control/UnitreeJointController
joint: RR_thigh_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
RR_calf_controller:
type: unitree_legged_control/UnitreeJointController
joint: RR_calf_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
| 2,291 | YAML | 31.28169 | 66 | 0.553907 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/unitreerobotics/go1_description/config/robot_control.yaml | go1_gazebo:
# Publish all joint states -----------------------------------
joint_state_controller:
type: joint_state_controller/JointStateController
publish_rate: 1000
# FL Controllers ---------------------------------------
FL_hip_controller:
type: unitree_legged_control/UnitreeJointController
joint: FL_hip_joint
pid: {p: 100.0, i: 0.0, d: 5.0}
FL_thigh_controller:
type: unitree_legged_control/UnitreeJointController
joint: FL_thigh_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
FL_calf_controller:
type: unitree_legged_control/UnitreeJointController
joint: FL_calf_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
# FR Controllers ---------------------------------------
FR_hip_controller:
type: unitree_legged_control/UnitreeJointController
joint: FR_hip_joint
pid: {p: 100.0, i: 0.0, d: 5.0}
FR_thigh_controller:
type: unitree_legged_control/UnitreeJointController
joint: FR_thigh_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
FR_calf_controller:
type: unitree_legged_control/UnitreeJointController
joint: FR_calf_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
# RL Controllers ---------------------------------------
RL_hip_controller:
type: unitree_legged_control/UnitreeJointController
joint: RL_hip_joint
pid: {p: 100.0, i: 0.0, d: 5.0}
RL_thigh_controller:
type: unitree_legged_control/UnitreeJointController
joint: RL_thigh_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
RL_calf_controller:
type: unitree_legged_control/UnitreeJointController
joint: RL_calf_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
# RR Controllers ---------------------------------------
RR_hip_controller:
type: unitree_legged_control/UnitreeJointController
joint: RR_hip_joint
pid: {p: 100.0, i: 0.0, d: 5.0}
RR_thigh_controller:
type: unitree_legged_control/UnitreeJointController
joint: RR_thigh_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
RR_calf_controller:
type: unitree_legged_control/UnitreeJointController
joint: RR_calf_joint
pid: {p: 300.0, i: 0.0, d: 8.0}
| 2,287 | YAML | 31.225352 | 66 | 0.553126 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/openDogV2/opendog_description-CHAMP/README.md | URDF and Gazebo model of [Jame's Bruton's](https://www.youtube.com/user/jamesbruton) [OpenDog V2](https://github.com/XRobots/openDogV2) project.
| 146 | Markdown | 72.499964 | 145 | 0.760274 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/openDogV2/openDogV2-original/README.md | # openDogV2:
CAD and Code that relates to this YouTube series:
https://www.youtube.com/playlist?list=PLpwJoq86vov9CcmrLGyM2XyyYDAYG0-Iu
Release 1: created at the end of part 6 of the YouTube series. Please note the issues stated at the end of this video.
Release 2: created at the end of part 7 of the YouTube series. Please note the issues stated during this video. Note that the remote is unchanged since release 1.
Relase 3: created for part 8 of the YouTube series. Includes the modified knee motor pulley, Python and Arduino code for the deep learning model.
# Related Community Projects:
OpenDog URDF/config for CHAMP: https://github.com/chvmp/opendog_description
'openDog 2.1' with higher belt reductions and cooling fans: https://github.com/J-DIndustries/openDog-V2.1
| 789 | Markdown | 42.888887 | 162 | 0.784537 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/openDogV2/openDogV2-original/Release02/Code/openDogV2_R2/MPU6050_6Axis_MotionApps20.h | // I2Cdev library collection - MPU6050 I2C device class, 6-axis MotionApps 2.0 implementation
// Based on InvenSense MPU-6050 register map document rev. 2.0, 5/19/2011 (RM-MPU-6000A-00)
// 5/20/2013 by Jeff Rowberg <jeff@rowberg.net>
// Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib
//
// Changelog:
// ... - ongoing debug release
/* ============================================
I2Cdev device library code is placed under the MIT license
Copyright (c) 2012 Jeff Rowberg
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
===============================================
*/
#ifndef _MPU6050_6AXIS_MOTIONAPPS20_H_
#define _MPU6050_6AXIS_MOTIONAPPS20_H_
#include "I2Cdev.h"
#include "helper_3dmath.h"
// MotionApps 2.0 DMP implementation, built using the MPU-6050EVB evaluation board
#define MPU6050_INCLUDE_DMP_MOTIONAPPS20
#include "MPU6050.h"
// Tom Carpenter's conditional PROGMEM code
// http://forum.arduino.cc/index.php?topic=129407.0
#ifndef __arm__
#include <avr/pgmspace.h>
#else
// Teensy 3.0 library conditional PROGMEM code from Paul Stoffregen
#ifndef __PGMSPACE_H_
#define __PGMSPACE_H_ 1
#include <inttypes.h>
#define PROGMEM
#define PGM_P const char *
#define PSTR(str) (str)
#define F(x) x
typedef void prog_void;
typedef char prog_char;
typedef unsigned char prog_uchar;
typedef int8_t prog_int8_t;
typedef uint8_t prog_uint8_t;
typedef int16_t prog_int16_t;
typedef uint16_t prog_uint16_t;
typedef int32_t prog_int32_t;
typedef uint32_t prog_uint32_t;
#define strcpy_P(dest, src) strcpy((dest), (src))
#define strcat_P(dest, src) strcat((dest), (src))
#define strcmp_P(a, b) strcmp((a), (b))
#define pgm_read_byte(addr) (*(const unsigned char *)(addr))
#define pgm_read_word(addr) (*(const unsigned short *)(addr))
#define pgm_read_dword(addr) (*(const unsigned long *)(addr))
#define pgm_read_float(addr) (*(const float *)(addr))
#define pgm_read_byte_near(addr) pgm_read_byte(addr)
#define pgm_read_word_near(addr) pgm_read_word(addr)
#define pgm_read_dword_near(addr) pgm_read_dword(addr)
#define pgm_read_float_near(addr) pgm_read_float(addr)
#define pgm_read_byte_far(addr) pgm_read_byte(addr)
#define pgm_read_word_far(addr) pgm_read_word(addr)
#define pgm_read_dword_far(addr) pgm_read_dword(addr)
#define pgm_read_float_far(addr) pgm_read_float(addr)
#endif
#endif
/* Source is from the InvenSense MotionApps v2 demo code. Original source is
* unavailable, unless you happen to be amazing as decompiling binary by
* hand (in which case, please contact me, and I'm totally serious).
*
* Also, I'd like to offer many, many thanks to Noah Zerkin for all of the
* DMP reverse-engineering he did to help make this bit of wizardry
* possible.
*/
// NOTE! Enabling DEBUG adds about 3.3kB to the flash program size.
// Debug output is now working even on ATMega328P MCUs (e.g. Arduino Uno)
// after moving string constants to flash memory storage using the F()
// compiler macro (Arduino IDE 1.0+ required).
//#define DEBUG
#ifdef DEBUG
#define DEBUG_PRINT(x) Serial.print(x)
#define DEBUG_PRINTF(x, y) Serial.print(x, y)
#define DEBUG_PRINTLN(x) Serial.println(x)
#define DEBUG_PRINTLNF(x, y) Serial.println(x, y)
#else
#define DEBUG_PRINT(x)
#define DEBUG_PRINTF(x, y)
#define DEBUG_PRINTLN(x)
#define DEBUG_PRINTLNF(x, y)
#endif
#define MPU6050_DMP_CODE_SIZE 1929 // dmpMemory[]
#define MPU6050_DMP_CONFIG_SIZE 192 // dmpConfig[]
#define MPU6050_DMP_UPDATES_SIZE 47 // dmpUpdates[]
/* ================================================================================================ *
| Default MotionApps v2.0 42-byte FIFO packet structure: |
| |
| [QUAT W][ ][QUAT X][ ][QUAT Y][ ][QUAT Z][ ][GYRO X][ ][GYRO Y][ ] |
| 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
| |
| [GYRO Z][ ][ACC X ][ ][ACC Y ][ ][ACC Z ][ ][ ] |
| 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
* ================================================================================================ */
// this block of memory gets written to the MPU on start-up, and it seems
// to be volatile memory, so it has to be done each time (it only takes ~1
// second though)
const unsigned char dmpMemory[MPU6050_DMP_CODE_SIZE] PROGMEM = {
// bank 0, 256 bytes
0xFB, 0x00, 0x00, 0x3E, 0x00, 0x0B, 0x00, 0x36, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x00,
0x00, 0x65, 0x00, 0x54, 0xFF, 0xEF, 0x00, 0x00, 0xFA, 0x80, 0x00, 0x0B, 0x12, 0x82, 0x00, 0x01,
0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x28, 0x00, 0x00, 0xFF, 0xFF, 0x45, 0x81, 0xFF, 0xFF, 0xFA, 0x72, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x03, 0xE8, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x7F, 0xFF, 0xFF, 0xFE, 0x80, 0x01,
0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x3E, 0x03, 0x30, 0x40, 0x00, 0x00, 0x00, 0x02, 0xCA, 0xE3, 0x09, 0x3E, 0x80, 0x00, 0x00,
0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00,
0x41, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x0B, 0x2A, 0x00, 0x00, 0x16, 0x55, 0x00, 0x00, 0x21, 0x82,
0xFD, 0x87, 0x26, 0x50, 0xFD, 0x80, 0x00, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x00, 0x05, 0x80, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00,
0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x6F, 0x00, 0x02, 0x65, 0x32, 0x00, 0x00, 0x5E, 0xC0,
0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFB, 0x8C, 0x6F, 0x5D, 0xFD, 0x5D, 0x08, 0xD9, 0x00, 0x7C, 0x73, 0x3B, 0x00, 0x6C, 0x12, 0xCC,
0x32, 0x00, 0x13, 0x9D, 0x32, 0x00, 0xD0, 0xD6, 0x32, 0x00, 0x08, 0x00, 0x40, 0x00, 0x01, 0xF4,
0xFF, 0xE6, 0x80, 0x79, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD0, 0xD6, 0x00, 0x00, 0x27, 0x10,
// bank 1, 256 bytes
0xFB, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFA, 0x36, 0xFF, 0xBC, 0x30, 0x8E, 0x00, 0x05, 0xFB, 0xF0, 0xFF, 0xD9, 0x5B, 0xC8,
0xFF, 0xD0, 0x9A, 0xBE, 0x00, 0x00, 0x10, 0xA9, 0xFF, 0xF4, 0x1E, 0xB2, 0x00, 0xCE, 0xBB, 0xF7,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x02, 0x00, 0x02, 0x02, 0x00, 0x00, 0x0C,
0xFF, 0xC2, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0xCF, 0x80, 0x00, 0x40, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x14,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x03, 0x3F, 0x68, 0xB6, 0x79, 0x35, 0x28, 0xBC, 0xC6, 0x7E, 0xD1, 0x6C,
0x80, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0xB2, 0x6A, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0xF0, 0x00, 0x00, 0x00, 0x30,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x25, 0x4D, 0x00, 0x2F, 0x70, 0x6D, 0x00, 0x00, 0x05, 0xAE, 0x00, 0x0C, 0x02, 0xD0,
// bank 2, 256 bytes
0x00, 0x00, 0x00, 0x00, 0x00, 0x65, 0x00, 0x54, 0xFF, 0xEF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x01, 0x00, 0x00, 0x44, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x00, 0x54, 0x00, 0x00, 0xFF, 0xEF, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,
0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// bank 3, 256 bytes
0xD8, 0xDC, 0xBA, 0xA2, 0xF1, 0xDE, 0xB2, 0xB8, 0xB4, 0xA8, 0x81, 0x91, 0xF7, 0x4A, 0x90, 0x7F,
0x91, 0x6A, 0xF3, 0xF9, 0xDB, 0xA8, 0xF9, 0xB0, 0xBA, 0xA0, 0x80, 0xF2, 0xCE, 0x81, 0xF3, 0xC2,
0xF1, 0xC1, 0xF2, 0xC3, 0xF3, 0xCC, 0xA2, 0xB2, 0x80, 0xF1, 0xC6, 0xD8, 0x80, 0xBA, 0xA7, 0xDF,
0xDF, 0xDF, 0xF2, 0xA7, 0xC3, 0xCB, 0xC5, 0xB6, 0xF0, 0x87, 0xA2, 0x94, 0x24, 0x48, 0x70, 0x3C,
0x95, 0x40, 0x68, 0x34, 0x58, 0x9B, 0x78, 0xA2, 0xF1, 0x83, 0x92, 0x2D, 0x55, 0x7D, 0xD8, 0xB1,
0xB4, 0xB8, 0xA1, 0xD0, 0x91, 0x80, 0xF2, 0x70, 0xF3, 0x70, 0xF2, 0x7C, 0x80, 0xA8, 0xF1, 0x01,
0xB0, 0x98, 0x87, 0xD9, 0x43, 0xD8, 0x86, 0xC9, 0x88, 0xBA, 0xA1, 0xF2, 0x0E, 0xB8, 0x97, 0x80,
0xF1, 0xA9, 0xDF, 0xDF, 0xDF, 0xAA, 0xDF, 0xDF, 0xDF, 0xF2, 0xAA, 0xC5, 0xCD, 0xC7, 0xA9, 0x0C,
0xC9, 0x2C, 0x97, 0x97, 0x97, 0x97, 0xF1, 0xA9, 0x89, 0x26, 0x46, 0x66, 0xB0, 0xB4, 0xBA, 0x80,
0xAC, 0xDE, 0xF2, 0xCA, 0xF1, 0xB2, 0x8C, 0x02, 0xA9, 0xB6, 0x98, 0x00, 0x89, 0x0E, 0x16, 0x1E,
0xB8, 0xA9, 0xB4, 0x99, 0x2C, 0x54, 0x7C, 0xB0, 0x8A, 0xA8, 0x96, 0x36, 0x56, 0x76, 0xF1, 0xB9,
0xAF, 0xB4, 0xB0, 0x83, 0xC0, 0xB8, 0xA8, 0x97, 0x11, 0xB1, 0x8F, 0x98, 0xB9, 0xAF, 0xF0, 0x24,
0x08, 0x44, 0x10, 0x64, 0x18, 0xF1, 0xA3, 0x29, 0x55, 0x7D, 0xAF, 0x83, 0xB5, 0x93, 0xAF, 0xF0,
0x00, 0x28, 0x50, 0xF1, 0xA3, 0x86, 0x9F, 0x61, 0xA6, 0xDA, 0xDE, 0xDF, 0xD9, 0xFA, 0xA3, 0x86,
0x96, 0xDB, 0x31, 0xA6, 0xD9, 0xF8, 0xDF, 0xBA, 0xA6, 0x8F, 0xC2, 0xC5, 0xC7, 0xB2, 0x8C, 0xC1,
0xB8, 0xA2, 0xDF, 0xDF, 0xDF, 0xA3, 0xDF, 0xDF, 0xDF, 0xD8, 0xD8, 0xF1, 0xB8, 0xA8, 0xB2, 0x86,
// bank 4, 256 bytes
0xB4, 0x98, 0x0D, 0x35, 0x5D, 0xB8, 0xAA, 0x98, 0xB0, 0x87, 0x2D, 0x35, 0x3D, 0xB2, 0xB6, 0xBA,
0xAF, 0x8C, 0x96, 0x19, 0x8F, 0x9F, 0xA7, 0x0E, 0x16, 0x1E, 0xB4, 0x9A, 0xB8, 0xAA, 0x87, 0x2C,
0x54, 0x7C, 0xB9, 0xA3, 0xDE, 0xDF, 0xDF, 0xA3, 0xB1, 0x80, 0xF2, 0xC4, 0xCD, 0xC9, 0xF1, 0xB8,
0xA9, 0xB4, 0x99, 0x83, 0x0D, 0x35, 0x5D, 0x89, 0xB9, 0xA3, 0x2D, 0x55, 0x7D, 0xB5, 0x93, 0xA3,
0x0E, 0x16, 0x1E, 0xA9, 0x2C, 0x54, 0x7C, 0xB8, 0xB4, 0xB0, 0xF1, 0x97, 0x83, 0xA8, 0x11, 0x84,
0xA5, 0x09, 0x98, 0xA3, 0x83, 0xF0, 0xDA, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0xD8, 0xF1, 0xA5,
0x29, 0x55, 0x7D, 0xA5, 0x85, 0x95, 0x02, 0x1A, 0x2E, 0x3A, 0x56, 0x5A, 0x40, 0x48, 0xF9, 0xF3,
0xA3, 0xD9, 0xF8, 0xF0, 0x98, 0x83, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0x97, 0x82, 0xA8, 0xF1,
0x11, 0xF0, 0x98, 0xA2, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0xDA, 0xF3, 0xDE, 0xD8, 0x83, 0xA5,
0x94, 0x01, 0xD9, 0xA3, 0x02, 0xF1, 0xA2, 0xC3, 0xC5, 0xC7, 0xD8, 0xF1, 0x84, 0x92, 0xA2, 0x4D,
0xDA, 0x2A, 0xD8, 0x48, 0x69, 0xD9, 0x2A, 0xD8, 0x68, 0x55, 0xDA, 0x32, 0xD8, 0x50, 0x71, 0xD9,
0x32, 0xD8, 0x70, 0x5D, 0xDA, 0x3A, 0xD8, 0x58, 0x79, 0xD9, 0x3A, 0xD8, 0x78, 0x93, 0xA3, 0x4D,
0xDA, 0x2A, 0xD8, 0x48, 0x69, 0xD9, 0x2A, 0xD8, 0x68, 0x55, 0xDA, 0x32, 0xD8, 0x50, 0x71, 0xD9,
0x32, 0xD8, 0x70, 0x5D, 0xDA, 0x3A, 0xD8, 0x58, 0x79, 0xD9, 0x3A, 0xD8, 0x78, 0xA8, 0x8A, 0x9A,
0xF0, 0x28, 0x50, 0x78, 0x9E, 0xF3, 0x88, 0x18, 0xF1, 0x9F, 0x1D, 0x98, 0xA8, 0xD9, 0x08, 0xD8,
0xC8, 0x9F, 0x12, 0x9E, 0xF3, 0x15, 0xA8, 0xDA, 0x12, 0x10, 0xD8, 0xF1, 0xAF, 0xC8, 0x97, 0x87,
// bank 5, 256 bytes
0x34, 0xB5, 0xB9, 0x94, 0xA4, 0x21, 0xF3, 0xD9, 0x22, 0xD8, 0xF2, 0x2D, 0xF3, 0xD9, 0x2A, 0xD8,
0xF2, 0x35, 0xF3, 0xD9, 0x32, 0xD8, 0x81, 0xA4, 0x60, 0x60, 0x61, 0xD9, 0x61, 0xD8, 0x6C, 0x68,
0x69, 0xD9, 0x69, 0xD8, 0x74, 0x70, 0x71, 0xD9, 0x71, 0xD8, 0xB1, 0xA3, 0x84, 0x19, 0x3D, 0x5D,
0xA3, 0x83, 0x1A, 0x3E, 0x5E, 0x93, 0x10, 0x30, 0x81, 0x10, 0x11, 0xB8, 0xB0, 0xAF, 0x8F, 0x94,
0xF2, 0xDA, 0x3E, 0xD8, 0xB4, 0x9A, 0xA8, 0x87, 0x29, 0xDA, 0xF8, 0xD8, 0x87, 0x9A, 0x35, 0xDA,
0xF8, 0xD8, 0x87, 0x9A, 0x3D, 0xDA, 0xF8, 0xD8, 0xB1, 0xB9, 0xA4, 0x98, 0x85, 0x02, 0x2E, 0x56,
0xA5, 0x81, 0x00, 0x0C, 0x14, 0xA3, 0x97, 0xB0, 0x8A, 0xF1, 0x2D, 0xD9, 0x28, 0xD8, 0x4D, 0xD9,
0x48, 0xD8, 0x6D, 0xD9, 0x68, 0xD8, 0xB1, 0x84, 0x0D, 0xDA, 0x0E, 0xD8, 0xA3, 0x29, 0x83, 0xDA,
0x2C, 0x0E, 0xD8, 0xA3, 0x84, 0x49, 0x83, 0xDA, 0x2C, 0x4C, 0x0E, 0xD8, 0xB8, 0xB0, 0xA8, 0x8A,
0x9A, 0xF5, 0x20, 0xAA, 0xDA, 0xDF, 0xD8, 0xA8, 0x40, 0xAA, 0xD0, 0xDA, 0xDE, 0xD8, 0xA8, 0x60,
0xAA, 0xDA, 0xD0, 0xDF, 0xD8, 0xF1, 0x97, 0x86, 0xA8, 0x31, 0x9B, 0x06, 0x99, 0x07, 0xAB, 0x97,
0x28, 0x88, 0x9B, 0xF0, 0x0C, 0x20, 0x14, 0x40, 0xB8, 0xB0, 0xB4, 0xA8, 0x8C, 0x9C, 0xF0, 0x04,
0x28, 0x51, 0x79, 0x1D, 0x30, 0x14, 0x38, 0xB2, 0x82, 0xAB, 0xD0, 0x98, 0x2C, 0x50, 0x50, 0x78,
0x78, 0x9B, 0xF1, 0x1A, 0xB0, 0xF0, 0x8A, 0x9C, 0xA8, 0x29, 0x51, 0x79, 0x8B, 0x29, 0x51, 0x79,
0x8A, 0x24, 0x70, 0x59, 0x8B, 0x20, 0x58, 0x71, 0x8A, 0x44, 0x69, 0x38, 0x8B, 0x39, 0x40, 0x68,
0x8A, 0x64, 0x48, 0x31, 0x8B, 0x30, 0x49, 0x60, 0xA5, 0x88, 0x20, 0x09, 0x71, 0x58, 0x44, 0x68,
// bank 6, 256 bytes
0x11, 0x39, 0x64, 0x49, 0x30, 0x19, 0xF1, 0xAC, 0x00, 0x2C, 0x54, 0x7C, 0xF0, 0x8C, 0xA8, 0x04,
0x28, 0x50, 0x78, 0xF1, 0x88, 0x97, 0x26, 0xA8, 0x59, 0x98, 0xAC, 0x8C, 0x02, 0x26, 0x46, 0x66,
0xF0, 0x89, 0x9C, 0xA8, 0x29, 0x51, 0x79, 0x24, 0x70, 0x59, 0x44, 0x69, 0x38, 0x64, 0x48, 0x31,
0xA9, 0x88, 0x09, 0x20, 0x59, 0x70, 0xAB, 0x11, 0x38, 0x40, 0x69, 0xA8, 0x19, 0x31, 0x48, 0x60,
0x8C, 0xA8, 0x3C, 0x41, 0x5C, 0x20, 0x7C, 0x00, 0xF1, 0x87, 0x98, 0x19, 0x86, 0xA8, 0x6E, 0x76,
0x7E, 0xA9, 0x99, 0x88, 0x2D, 0x55, 0x7D, 0x9E, 0xB9, 0xA3, 0x8A, 0x22, 0x8A, 0x6E, 0x8A, 0x56,
0x8A, 0x5E, 0x9F, 0xB1, 0x83, 0x06, 0x26, 0x46, 0x66, 0x0E, 0x2E, 0x4E, 0x6E, 0x9D, 0xB8, 0xAD,
0x00, 0x2C, 0x54, 0x7C, 0xF2, 0xB1, 0x8C, 0xB4, 0x99, 0xB9, 0xA3, 0x2D, 0x55, 0x7D, 0x81, 0x91,
0xAC, 0x38, 0xAD, 0x3A, 0xB5, 0x83, 0x91, 0xAC, 0x2D, 0xD9, 0x28, 0xD8, 0x4D, 0xD9, 0x48, 0xD8,
0x6D, 0xD9, 0x68, 0xD8, 0x8C, 0x9D, 0xAE, 0x29, 0xD9, 0x04, 0xAE, 0xD8, 0x51, 0xD9, 0x04, 0xAE,
0xD8, 0x79, 0xD9, 0x04, 0xD8, 0x81, 0xF3, 0x9D, 0xAD, 0x00, 0x8D, 0xAE, 0x19, 0x81, 0xAD, 0xD9,
0x01, 0xD8, 0xF2, 0xAE, 0xDA, 0x26, 0xD8, 0x8E, 0x91, 0x29, 0x83, 0xA7, 0xD9, 0xAD, 0xAD, 0xAD,
0xAD, 0xF3, 0x2A, 0xD8, 0xD8, 0xF1, 0xB0, 0xAC, 0x89, 0x91, 0x3E, 0x5E, 0x76, 0xF3, 0xAC, 0x2E,
0x2E, 0xF1, 0xB1, 0x8C, 0x5A, 0x9C, 0xAC, 0x2C, 0x28, 0x28, 0x28, 0x9C, 0xAC, 0x30, 0x18, 0xA8,
0x98, 0x81, 0x28, 0x34, 0x3C, 0x97, 0x24, 0xA7, 0x28, 0x34, 0x3C, 0x9C, 0x24, 0xF2, 0xB0, 0x89,
0xAC, 0x91, 0x2C, 0x4C, 0x6C, 0x8A, 0x9B, 0x2D, 0xD9, 0xD8, 0xD8, 0x51, 0xD9, 0xD8, 0xD8, 0x79,
// bank 7, 138 bytes (remainder)
0xD9, 0xD8, 0xD8, 0xF1, 0x9E, 0x88, 0xA3, 0x31, 0xDA, 0xD8, 0xD8, 0x91, 0x2D, 0xD9, 0x28, 0xD8,
0x4D, 0xD9, 0x48, 0xD8, 0x6D, 0xD9, 0x68, 0xD8, 0xB1, 0x83, 0x93, 0x35, 0x3D, 0x80, 0x25, 0xDA,
0xD8, 0xD8, 0x85, 0x69, 0xDA, 0xD8, 0xD8, 0xB4, 0x93, 0x81, 0xA3, 0x28, 0x34, 0x3C, 0xF3, 0xAB,
0x8B, 0xF8, 0xA3, 0x91, 0xB6, 0x09, 0xB4, 0xD9, 0xAB, 0xDE, 0xFA, 0xB0, 0x87, 0x9C, 0xB9, 0xA3,
0xDD, 0xF1, 0xA3, 0xA3, 0xA3, 0xA3, 0x95, 0xF1, 0xA3, 0xA3, 0xA3, 0x9D, 0xF1, 0xA3, 0xA3, 0xA3,
0xA3, 0xF2, 0xA3, 0xB4, 0x90, 0x80, 0xF2, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3,
0xA3, 0xB2, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xB0, 0x87, 0xB5, 0x99, 0xF1, 0xA3, 0xA3, 0xA3,
0x98, 0xF1, 0xA3, 0xA3, 0xA3, 0xA3, 0x97, 0xA3, 0xA3, 0xA3, 0xA3, 0xF3, 0x9B, 0xA3, 0xA3, 0xDC,
0xB9, 0xA7, 0xF1, 0x26, 0x26, 0x26, 0xD8, 0xD8, 0xFF
};
// thanks to Noah Zerkin for piecing this stuff together!
const unsigned char dmpConfig[MPU6050_DMP_CONFIG_SIZE] PROGMEM = {
// BANK OFFSET LENGTH [DATA]
0x03, 0x7B, 0x03, 0x4C, 0xCD, 0x6C, // FCFG_1 inv_set_gyro_calibration
0x03, 0xAB, 0x03, 0x36, 0x56, 0x76, // FCFG_3 inv_set_gyro_calibration
0x00, 0x68, 0x04, 0x02, 0xCB, 0x47, 0xA2, // D_0_104 inv_set_gyro_calibration
0x02, 0x18, 0x04, 0x00, 0x05, 0x8B, 0xC1, // D_0_24 inv_set_gyro_calibration
0x01, 0x0C, 0x04, 0x00, 0x00, 0x00, 0x00, // D_1_152 inv_set_accel_calibration
0x03, 0x7F, 0x06, 0x0C, 0xC9, 0x2C, 0x97, 0x97, 0x97, // FCFG_2 inv_set_accel_calibration
0x03, 0x89, 0x03, 0x26, 0x46, 0x66, // FCFG_7 inv_set_accel_calibration
0x00, 0x6C, 0x02, 0x20, 0x00, // D_0_108 inv_set_accel_calibration
0x02, 0x40, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_00 inv_set_compass_calibration
0x02, 0x44, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_01
0x02, 0x48, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_02
0x02, 0x4C, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_10
0x02, 0x50, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_11
0x02, 0x54, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_12
0x02, 0x58, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_20
0x02, 0x5C, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_21
0x02, 0xBC, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_22
0x01, 0xEC, 0x04, 0x00, 0x00, 0x40, 0x00, // D_1_236 inv_apply_endian_accel
0x03, 0x7F, 0x06, 0x0C, 0xC9, 0x2C, 0x97, 0x97, 0x97, // FCFG_2 inv_set_mpu_sensors
0x04, 0x02, 0x03, 0x0D, 0x35, 0x5D, // CFG_MOTION_BIAS inv_turn_on_bias_from_no_motion
0x04, 0x09, 0x04, 0x87, 0x2D, 0x35, 0x3D, // FCFG_5 inv_set_bias_update
0x00, 0xA3, 0x01, 0x00, // D_0_163 inv_set_dead_zone
// SPECIAL 0x01 = enable interrupts
0x00, 0x00, 0x00, 0x01, // SET INT_ENABLE at i=22, SPECIAL INSTRUCTION
0x07, 0x86, 0x01, 0xFE, // CFG_6 inv_set_fifo_interupt
0x07, 0x41, 0x05, 0xF1, 0x20, 0x28, 0x30, 0x38, // CFG_8 inv_send_quaternion
0x07, 0x7E, 0x01, 0x30, // CFG_16 inv_set_footer
0x07, 0x46, 0x01, 0x9A, // CFG_GYRO_SOURCE inv_send_gyro
0x07, 0x47, 0x04, 0xF1, 0x28, 0x30, 0x38, // CFG_9 inv_send_gyro -> inv_construct3_fifo
0x07, 0x6C, 0x04, 0xF1, 0x28, 0x30, 0x38, // CFG_12 inv_send_accel -> inv_construct3_fifo
0x02, 0x16, 0x02, 0x00, 0x09 // D_0_22 inv_set_fifo_rate
// This very last 0x01 WAS a 0x09, which drops the FIFO rate down to 20 Hz. 0x07 is 25 Hz,
// 0x01 is 100Hz. Going faster than 100Hz (0x00=200Hz) tends to result in very noisy data.
// DMP output frequency is calculated easily using this equation: (200Hz / (1 + value))
// It is important to make sure the host processor can keep up with reading and processing
// the FIFO output at the desired rate. Handling FIFO overflow cleanly is also a good idea.
};
const unsigned char dmpUpdates[MPU6050_DMP_UPDATES_SIZE] PROGMEM = {
0x01, 0xB2, 0x02, 0xFF, 0xFF,
0x01, 0x90, 0x04, 0x09, 0x23, 0xA1, 0x35,
0x01, 0x6A, 0x02, 0x06, 0x00,
0x01, 0x60, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x60, 0x04, 0x40, 0x00, 0x00, 0x00,
0x01, 0x62, 0x02, 0x00, 0x00,
0x00, 0x60, 0x04, 0x00, 0x40, 0x00, 0x00
};
uint8_t MPU6050::dmpInitialize() {
// reset device
DEBUG_PRINTLN(F("\n\nResetting MPU6050..."));
reset();
delay(30); // wait after reset
// enable sleep mode and wake cycle
/*Serial.println(F("Enabling sleep mode..."));
setSleepEnabled(true);
Serial.println(F("Enabling wake cycle..."));
setWakeCycleEnabled(true);*/
// disable sleep mode
DEBUG_PRINTLN(F("Disabling sleep mode..."));
setSleepEnabled(false);
// get MPU hardware revision
DEBUG_PRINTLN(F("Selecting user bank 16..."));
setMemoryBank(0x10, true, true);
DEBUG_PRINTLN(F("Selecting memory byte 6..."));
setMemoryStartAddress(0x06);
DEBUG_PRINTLN(F("Checking hardware revision..."));
uint8_t hwRevision = readMemoryByte();
DEBUG_PRINT(F("Revision @ user[16][6] = "));
DEBUG_PRINTLNF(hwRevision, HEX);
DEBUG_PRINTLN(F("Resetting memory bank selection to 0..."));
setMemoryBank(0, false, false);
// check OTP bank valid
DEBUG_PRINTLN(F("Reading OTP bank valid flag..."));
uint8_t otpValid = getOTPBankValid();
DEBUG_PRINT(F("OTP bank is "));
DEBUG_PRINTLN(otpValid ? F("valid!") : F("invalid!"));
// get X/Y/Z gyro offsets
DEBUG_PRINTLN(F("Reading gyro offset TC values..."));
int8_t xgOffsetTC = getXGyroOffsetTC();
int8_t ygOffsetTC = getYGyroOffsetTC();
int8_t zgOffsetTC = getZGyroOffsetTC();
DEBUG_PRINT(F("X gyro offset = "));
DEBUG_PRINTLN(xgOffset);
DEBUG_PRINT(F("Y gyro offset = "));
DEBUG_PRINTLN(ygOffset);
DEBUG_PRINT(F("Z gyro offset = "));
DEBUG_PRINTLN(zgOffset);
// setup weird slave stuff (?)
DEBUG_PRINTLN(F("Setting slave 0 address to 0x7F..."));
setSlaveAddress(0, 0x7F);
DEBUG_PRINTLN(F("Disabling I2C Master mode..."));
setI2CMasterModeEnabled(false);
DEBUG_PRINTLN(F("Setting slave 0 address to 0x68 (self)..."));
setSlaveAddress(0, 0x68);
DEBUG_PRINTLN(F("Resetting I2C Master control..."));
resetI2CMaster();
delay(20);
// load DMP code into memory banks
DEBUG_PRINT(F("Writing DMP code to MPU memory banks ("));
DEBUG_PRINT(MPU6050_DMP_CODE_SIZE);
DEBUG_PRINTLN(F(" bytes)"));
if (writeProgMemoryBlock(dmpMemory, MPU6050_DMP_CODE_SIZE)) {
DEBUG_PRINTLN(F("Success! DMP code written and verified."));
// write DMP configuration
DEBUG_PRINT(F("Writing DMP configuration to MPU memory banks ("));
DEBUG_PRINT(MPU6050_DMP_CONFIG_SIZE);
DEBUG_PRINTLN(F(" bytes in config def)"));
if (writeProgDMPConfigurationSet(dmpConfig, MPU6050_DMP_CONFIG_SIZE)) {
DEBUG_PRINTLN(F("Success! DMP configuration written and verified."));
DEBUG_PRINTLN(F("Setting clock source to Z Gyro..."));
setClockSource(MPU6050_CLOCK_PLL_ZGYRO);
DEBUG_PRINTLN(F("Setting DMP and FIFO_OFLOW interrupts enabled..."));
setIntEnabled(0x12);
DEBUG_PRINTLN(F("Setting sample rate to 200Hz..."));
setRate(4); // 1khz / (1 + 4) = 200 Hz
DEBUG_PRINTLN(F("Setting external frame sync to TEMP_OUT_L[0]..."));
setExternalFrameSync(MPU6050_EXT_SYNC_TEMP_OUT_L);
DEBUG_PRINTLN(F("Setting DLPF bandwidth to 42Hz..."));
setDLPFMode(MPU6050_DLPF_BW_42);
DEBUG_PRINTLN(F("Setting gyro sensitivity to +/- 2000 deg/sec..."));
setFullScaleGyroRange(MPU6050_GYRO_FS_2000);
DEBUG_PRINTLN(F("Setting DMP configuration bytes (function unknown)..."));
setDMPConfig1(0x03);
setDMPConfig2(0x00);
DEBUG_PRINTLN(F("Clearing OTP Bank flag..."));
setOTPBankValid(false);
DEBUG_PRINTLN(F("Setting X/Y/Z gyro offset TCs to previous values..."));
setXGyroOffsetTC(xgOffsetTC);
setYGyroOffsetTC(ygOffsetTC);
setZGyroOffsetTC(zgOffsetTC);
//DEBUG_PRINTLN(F("Setting X/Y/Z gyro user offsets to zero..."));
//setXGyroOffset(0);
//setYGyroOffset(0);
//setZGyroOffset(0);
DEBUG_PRINTLN(F("Writing final memory update 1/7 (function unknown)..."));
uint8_t dmpUpdate[16], j;
uint16_t pos = 0;
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
DEBUG_PRINTLN(F("Writing final memory update 2/7 (function unknown)..."));
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
DEBUG_PRINTLN(F("Resetting FIFO..."));
resetFIFO();
DEBUG_PRINTLN(F("Reading FIFO count..."));
uint16_t fifoCount = getFIFOCount();
uint8_t fifoBuffer[128];
DEBUG_PRINT(F("Current FIFO count="));
DEBUG_PRINTLN(fifoCount);
getFIFOBytes(fifoBuffer, fifoCount);
DEBUG_PRINTLN(F("Setting motion detection threshold to 2..."));
setMotionDetectionThreshold(2);
DEBUG_PRINTLN(F("Setting zero-motion detection threshold to 156..."));
setZeroMotionDetectionThreshold(156);
DEBUG_PRINTLN(F("Setting motion detection duration to 80..."));
setMotionDetectionDuration(80);
DEBUG_PRINTLN(F("Setting zero-motion detection duration to 0..."));
setZeroMotionDetectionDuration(0);
DEBUG_PRINTLN(F("Resetting FIFO..."));
resetFIFO();
DEBUG_PRINTLN(F("Enabling FIFO..."));
setFIFOEnabled(true);
DEBUG_PRINTLN(F("Enabling DMP..."));
setDMPEnabled(true);
DEBUG_PRINTLN(F("Resetting DMP..."));
resetDMP();
DEBUG_PRINTLN(F("Writing final memory update 3/7 (function unknown)..."));
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
DEBUG_PRINTLN(F("Writing final memory update 4/7 (function unknown)..."));
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
DEBUG_PRINTLN(F("Writing final memory update 5/7 (function unknown)..."));
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
DEBUG_PRINTLN(F("Waiting for FIFO count > 2..."));
while ((fifoCount = getFIFOCount()) < 3);
DEBUG_PRINT(F("Current FIFO count="));
DEBUG_PRINTLN(fifoCount);
DEBUG_PRINTLN(F("Reading FIFO data..."));
getFIFOBytes(fifoBuffer, fifoCount);
DEBUG_PRINTLN(F("Reading interrupt status..."));
uint8_t mpuIntStatus = getIntStatus();
DEBUG_PRINT(F("Current interrupt status="));
DEBUG_PRINTLNF(mpuIntStatus, HEX);
DEBUG_PRINTLN(F("Reading final memory update 6/7 (function unknown)..."));
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
readMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
DEBUG_PRINTLN(F("Waiting for FIFO count > 2..."));
while ((fifoCount = getFIFOCount()) < 3);
DEBUG_PRINT(F("Current FIFO count="));
DEBUG_PRINTLN(fifoCount);
DEBUG_PRINTLN(F("Reading FIFO data..."));
getFIFOBytes(fifoBuffer, fifoCount);
DEBUG_PRINTLN(F("Reading interrupt status..."));
mpuIntStatus = getIntStatus();
DEBUG_PRINT(F("Current interrupt status="));
DEBUG_PRINTLNF(mpuIntStatus, HEX);
DEBUG_PRINTLN(F("Writing final memory update 7/7 (function unknown)..."));
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
DEBUG_PRINTLN(F("DMP is good to go! Finally."));
DEBUG_PRINTLN(F("Disabling DMP (you turn it on later)..."));
setDMPEnabled(false);
DEBUG_PRINTLN(F("Setting up internal 42-byte (default) DMP packet buffer..."));
dmpPacketSize = 42;
/*if ((dmpPacketBuffer = (uint8_t *)malloc(42)) == 0) {
return 3; // TODO: proper error code for no memory
}*/
DEBUG_PRINTLN(F("Resetting FIFO and clearing INT status one last time..."));
resetFIFO();
getIntStatus();
} else {
DEBUG_PRINTLN(F("ERROR! DMP configuration verification failed."));
return 2; // configuration block loading failed
}
} else {
DEBUG_PRINTLN(F("ERROR! DMP code verification failed."));
return 1; // main binary block loading failed
}
return 0; // success
}
bool MPU6050::dmpPacketAvailable() {
return getFIFOCount() >= dmpGetFIFOPacketSize();
}
// uint8_t MPU6050::dmpSetFIFORate(uint8_t fifoRate);
// uint8_t MPU6050::dmpGetFIFORate();
// uint8_t MPU6050::dmpGetSampleStepSizeMS();
// uint8_t MPU6050::dmpGetSampleFrequency();
// int32_t MPU6050::dmpDecodeTemperature(int8_t tempReg);
//uint8_t MPU6050::dmpRegisterFIFORateProcess(inv_obj_func func, int16_t priority);
//uint8_t MPU6050::dmpUnregisterFIFORateProcess(inv_obj_func func);
//uint8_t MPU6050::dmpRunFIFORateProcesses();
// uint8_t MPU6050::dmpSendQuaternion(uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendGyro(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendAccel(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendLinearAccel(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendLinearAccelInWorld(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendControlData(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendSensorData(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendExternalSensorData(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendGravity(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendPacketNumber(uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendQuantizedAccel(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendEIS(uint_fast16_t elements, uint_fast16_t accuracy);
uint8_t MPU6050::dmpGetAccel(int32_t *data, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
data[0] = ((packet[28] << 24) + (packet[29] << 16) + (packet[30] << 8) + packet[31]);
data[1] = ((packet[32] << 24) + (packet[33] << 16) + (packet[34] << 8) + packet[35]);
data[2] = ((packet[36] << 24) + (packet[37] << 16) + (packet[38] << 8) + packet[39]);
return 0;
}
uint8_t MPU6050::dmpGetAccel(int16_t *data, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
data[0] = (packet[28] << 8) + packet[29];
data[1] = (packet[32] << 8) + packet[33];
data[2] = (packet[36] << 8) + packet[37];
return 0;
}
uint8_t MPU6050::dmpGetAccel(VectorInt16 *v, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
v -> x = (packet[28] << 8) + packet[29];
v -> y = (packet[32] << 8) + packet[33];
v -> z = (packet[36] << 8) + packet[37];
return 0;
}
uint8_t MPU6050::dmpGetQuaternion(int32_t *data, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
data[0] = ((packet[0] << 24) + (packet[1] << 16) + (packet[2] << 8) + packet[3]);
data[1] = ((packet[4] << 24) + (packet[5] << 16) + (packet[6] << 8) + packet[7]);
data[2] = ((packet[8] << 24) + (packet[9] << 16) + (packet[10] << 8) + packet[11]);
data[3] = ((packet[12] << 24) + (packet[13] << 16) + (packet[14] << 8) + packet[15]);
return 0;
}
uint8_t MPU6050::dmpGetQuaternion(int16_t *data, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
data[0] = ((packet[0] << 8) + packet[1]);
data[1] = ((packet[4] << 8) + packet[5]);
data[2] = ((packet[8] << 8) + packet[9]);
data[3] = ((packet[12] << 8) + packet[13]);
return 0;
}
uint8_t MPU6050::dmpGetQuaternion(Quaternion *q, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
int16_t qI[4];
uint8_t status = dmpGetQuaternion(qI, packet);
if (status == 0) {
q -> w = (float)qI[0] / 16384.0f;
q -> x = (float)qI[1] / 16384.0f;
q -> y = (float)qI[2] / 16384.0f;
q -> z = (float)qI[3] / 16384.0f;
return 0;
}
return status; // int16 return value, indicates error if this line is reached
}
// uint8_t MPU6050::dmpGet6AxisQuaternion(long *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetRelativeQuaternion(long *data, const uint8_t* packet);
uint8_t MPU6050::dmpGetGyro(int32_t *data, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
data[0] = ((packet[16] << 24) + (packet[17] << 16) + (packet[18] << 8) + packet[19]);
data[1] = ((packet[20] << 24) + (packet[21] << 16) + (packet[22] << 8) + packet[23]);
data[2] = ((packet[24] << 24) + (packet[25] << 16) + (packet[26] << 8) + packet[27]);
return 0;
}
uint8_t MPU6050::dmpGetGyro(int16_t *data, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
data[0] = (packet[16] << 8) + packet[17];
data[1] = (packet[20] << 8) + packet[21];
data[2] = (packet[24] << 8) + packet[25];
return 0;
}
uint8_t MPU6050::dmpGetGyro(VectorInt16 *v, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
v -> x = (packet[16] << 8) + packet[17];
v -> y = (packet[20] << 8) + packet[21];
v -> z = (packet[24] << 8) + packet[25];
return 0;
}
// uint8_t MPU6050::dmpSetLinearAccelFilterCoefficient(float coef);
// uint8_t MPU6050::dmpGetLinearAccel(long *data, const uint8_t* packet);
uint8_t MPU6050::dmpGetLinearAccel(VectorInt16 *v, VectorInt16 *vRaw, VectorFloat *gravity) {
// get rid of the gravity component (+1g = +8192 in standard DMP FIFO packet, sensitivity is 2g)
v -> x = vRaw -> x - gravity -> x*8192;
v -> y = vRaw -> y - gravity -> y*8192;
v -> z = vRaw -> z - gravity -> z*8192;
return 0;
}
// uint8_t MPU6050::dmpGetLinearAccelInWorld(long *data, const uint8_t* packet);
uint8_t MPU6050::dmpGetLinearAccelInWorld(VectorInt16 *v, VectorInt16 *vReal, Quaternion *q) {
// rotate measured 3D acceleration vector into original state
// frame of reference based on orientation quaternion
memcpy(v, vReal, sizeof(VectorInt16));
v -> rotate(q);
return 0;
}
// uint8_t MPU6050::dmpGetGyroAndAccelSensor(long *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetGyroSensor(long *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetControlData(long *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetTemperature(long *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetGravity(long *data, const uint8_t* packet);
uint8_t MPU6050::dmpGetGravity(VectorFloat *v, Quaternion *q) {
v -> x = 2 * (q -> x*q -> z - q -> w*q -> y);
v -> y = 2 * (q -> w*q -> x + q -> y*q -> z);
v -> z = q -> w*q -> w - q -> x*q -> x - q -> y*q -> y + q -> z*q -> z;
return 0;
}
// uint8_t MPU6050::dmpGetUnquantizedAccel(long *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetQuantizedAccel(long *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetExternalSensorData(long *data, int size, const uint8_t* packet);
// uint8_t MPU6050::dmpGetEIS(long *data, const uint8_t* packet);
uint8_t MPU6050::dmpGetEuler(float *data, Quaternion *q) {
data[0] = atan2(2*q -> x*q -> y - 2*q -> w*q -> z, 2*q -> w*q -> w + 2*q -> x*q -> x - 1); // psi
data[1] = -asin(2*q -> x*q -> z + 2*q -> w*q -> y); // theta
data[2] = atan2(2*q -> y*q -> z - 2*q -> w*q -> x, 2*q -> w*q -> w + 2*q -> z*q -> z - 1); // phi
return 0;
}
uint8_t MPU6050::dmpGetYawPitchRoll(float *data, Quaternion *q, VectorFloat *gravity) {
// yaw: (about Z axis)
data[0] = atan2(2*q -> x*q -> y - 2*q -> w*q -> z, 2*q -> w*q -> w + 2*q -> x*q -> x - 1);
// pitch: (nose up/down, about Y axis)
data[1] = atan(gravity -> x / sqrt(gravity -> y*gravity -> y + gravity -> z*gravity -> z));
// roll: (tilt left/right, about X axis)
data[2] = atan(gravity -> y / sqrt(gravity -> x*gravity -> x + gravity -> z*gravity -> z));
return 0;
}
// uint8_t MPU6050::dmpGetAccelFloat(float *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetQuaternionFloat(float *data, const uint8_t* packet);
uint8_t MPU6050::dmpProcessFIFOPacket(const unsigned char *dmpData) {
/*for (uint8_t k = 0; k < dmpPacketSize; k++) {
if (dmpData[k] < 0x10) Serial.print("0");
Serial.print(dmpData[k], HEX);
Serial.print(" ");
}
Serial.print("\n");*/
//Serial.println((uint16_t)dmpPacketBuffer);
return 0;
}
uint8_t MPU6050::dmpReadAndProcessFIFOPacket(uint8_t numPackets, uint8_t *processed) {
uint8_t status;
uint8_t buf[dmpPacketSize];
for (uint8_t i = 0; i < numPackets; i++) {
// read packet from FIFO
getFIFOBytes(buf, dmpPacketSize);
// process packet
if ((status = dmpProcessFIFOPacket(buf)) > 0) return status;
// increment external process count variable, if supplied
if (processed != 0) *processed++;
}
return 0;
}
// uint8_t MPU6050::dmpSetFIFOProcessedCallback(void (*func) (void));
// uint8_t MPU6050::dmpInitFIFOParam();
// uint8_t MPU6050::dmpCloseFIFO();
// uint8_t MPU6050::dmpSetGyroDataSource(uint_fast8_t source);
// uint8_t MPU6050::dmpDecodeQuantizedAccel();
// uint32_t MPU6050::dmpGetGyroSumOfSquare();
// uint32_t MPU6050::dmpGetAccelSumOfSquare();
// void MPU6050::dmpOverrideQuaternion(long *q);
uint16_t MPU6050::dmpGetFIFOPacketSize() {
return dmpPacketSize;
}
#endif /* _MPU6050_6AXIS_MOTIONAPPS20_H_ */
| 41,027 | C | 53.704 | 114 | 0.617106 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/openDogV2/openDogV2-original/Release03/code/Python/camera100.py | import RPi.GPIO as GPIO
import jetson.inference
import jetson.utils
import time
import argparse
import sys
# parse the command line
parser = argparse.ArgumentParser(description="Locate objects in a live camera stream using an object detection DNN.",
formatter_class=argparse.RawTextHelpFormatter, epilog=jetson.inference.detectNet.Usage() +
jetson.utils.videoSource.Usage() + jetson.utils.videoOutput.Usage() + jetson.utils.logUsage())
parser.add_argument("input_URI", type=str, default="", nargs='?', help="URI of the input stream")
parser.add_argument("output_URI", type=str, default="", nargs='?', help="URI of the output stream")
parser.add_argument("--network", type=str, default="ssd-mobilenet-v2", help="pre-trained model to load (see below for options)")
parser.add_argument("--overlay", type=str, default="box,labels,conf", help="detection overlay flags (e.g. --overlay=box,labels,conf)\nvalid combinations are: 'box', 'labels', 'conf', 'none'")
parser.add_argument("--threshold", type=float, default=0.5, help="minimum detection threshold to use")
is_headless = ["--headless"] if sys.argv[0].find('console.py') != -1 else [""]
try:
opt = parser.parse_known_args()[0]
except:
print("")
parser.print_help()
sys.exit(0)
# load the object detection network
net = jetson.inference.detectNet(opt.network, sys.argv, opt.threshold)
# create video sources & outputs
input = jetson.utils.videoSource(opt.input_URI, argv=sys.argv)
output = jetson.utils.videoOutput(opt.output_URI, argv=sys.argv+is_headless)
#setup GPIO pins
GPIO.setmode(GPIO.BCM) #RaspPi pin numbering
GPIO.setup(18, GPIO.OUT, initial=GPIO.HIGH)
GPIO.output(18, GPIO.HIGH)
GPIO.setup(17, GPIO.OUT, initial=GPIO.HIGH)
GPIO.output(17, GPIO.HIGH)
GPIO.setup(16, GPIO.OUT, initial=GPIO.HIGH)
GPIO.output(16, GPIO.HIGH)
GPIO.setup(20, GPIO.OUT, initial=GPIO.HIGH)
GPIO.output(20, GPIO.HIGH)
GPIO.setup(21, GPIO.OUT, initial=GPIO.HIGH)
GPIO.output(21, GPIO.HIGH)
def back():
GPIO.output(18, GPIO.LOW)
GPIO.output(17, GPIO.HIGH)
GPIO.output(16, GPIO.HIGH)
GPIO.output(20, GPIO.HIGH)
GPIO.output(21, GPIO.HIGH)
print("back")
def forward():
GPIO.output(18, GPIO.HIGH)
GPIO.output(17, GPIO.LOW)
GPIO.output(16, GPIO.HIGH)
GPIO.output(20, GPIO.HIGH)
GPIO.output(21, GPIO.HIGH)
print("forward")
def left():
GPIO.output(18, GPIO.HIGH)
GPIO.output(17, GPIO.HIGH)
GPIO.output(16, GPIO.LOW)
GPIO.output(20, GPIO.HIGH)
GPIO.output(21, GPIO.HIGH)
print("left")
def right():
GPIO.output(18, GPIO.HIGH)
GPIO.output(17, GPIO.HIGH)
GPIO.output(16, GPIO.HIGH)
GPIO.output(20, GPIO.LOW)
GPIO.output(21, GPIO.HIGH)
print("right")
def up():
GPIO.output(18, GPIO.HIGH)
GPIO.output(17, GPIO.HIGH)
GPIO.output(16, GPIO.HIGH)
GPIO.output(20, GPIO.HIGH)
GPIO.output(21, GPIO.LOW)
print("up")
def nothing():
GPIO.output(18, GPIO.HIGH)
GPIO.output(17, GPIO.HIGH)
GPIO.output(16, GPIO.HIGH)
GPIO.output(20, GPIO.HIGH)
GPIO.output(21, GPIO.HIGH)
print("nothing")
# declare variables as global and that
global index
global width
global location
global confidence
index = 0
width = 0
location = 0
condifence = 0;
# process frames until the user exits
while True:
# capture the next image
img = input.Capture()
# detect objects in the image (with overlay)
detections = net.Detect(img, overlay=opt.overlay)
# print the detections
#print("detected {:d} objects in image".format(len(detections)))
# check for detections, otherwise nothing
if(len(detections) > 0):
print("object detected")
for detection in detections:
index = detections[0].ClassID
confidence = (detections[0].Confidence)
width = (detections[0].Width)
location = (detections[0].Center[0])
# print index of item, width and horizonal location
print(index)
print(width)
print(location)
print(confidence)
# look for detections
if (index == 1 and confidence > 0.9):
back()
elif (index == 2 and confidence > 0.7):
forward()
elif (index == 3 and confidence > 0.7):
left()
elif (index == 4 and confidence > 0.7):
right()
elif (index == 5 and confidence > 0.7):
up()
else:
nothing() # nothing is detected
# render the image
output.Render(img)
# update the title bar
output.SetStatus("{:s} | Network {:.0f} FPS".format(opt.network, net.GetNetworkFPS()))
# print out performance info
#net.PrintProfilerTimes()
# exit on input/output EOS
if not input.IsStreaming() or not output.IsStreaming():
break
| 4,525 | Python | 24.570621 | 192 | 0.698122 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/openDogV2/openDogV2-original/Release03/code/openDogV2_R3/MPU6050_6Axis_MotionApps20.h | // I2Cdev library collection - MPU6050 I2C device class, 6-axis MotionApps 2.0 implementation
// Based on InvenSense MPU-6050 register map document rev. 2.0, 5/19/2011 (RM-MPU-6000A-00)
// 5/20/2013 by Jeff Rowberg <jeff@rowberg.net>
// Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib
//
// Changelog:
// ... - ongoing debug release
/* ============================================
I2Cdev device library code is placed under the MIT license
Copyright (c) 2012 Jeff Rowberg
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
===============================================
*/
#ifndef _MPU6050_6AXIS_MOTIONAPPS20_H_
#define _MPU6050_6AXIS_MOTIONAPPS20_H_
#include "I2Cdev.h"
#include "helper_3dmath.h"
// MotionApps 2.0 DMP implementation, built using the MPU-6050EVB evaluation board
#define MPU6050_INCLUDE_DMP_MOTIONAPPS20
#include "MPU6050.h"
// Tom Carpenter's conditional PROGMEM code
// http://forum.arduino.cc/index.php?topic=129407.0
#ifndef __arm__
#include <avr/pgmspace.h>
#else
// Teensy 3.0 library conditional PROGMEM code from Paul Stoffregen
#ifndef __PGMSPACE_H_
#define __PGMSPACE_H_ 1
#include <inttypes.h>
#define PROGMEM
#define PGM_P const char *
#define PSTR(str) (str)
#define F(x) x
typedef void prog_void;
typedef char prog_char;
typedef unsigned char prog_uchar;
typedef int8_t prog_int8_t;
typedef uint8_t prog_uint8_t;
typedef int16_t prog_int16_t;
typedef uint16_t prog_uint16_t;
typedef int32_t prog_int32_t;
typedef uint32_t prog_uint32_t;
#define strcpy_P(dest, src) strcpy((dest), (src))
#define strcat_P(dest, src) strcat((dest), (src))
#define strcmp_P(a, b) strcmp((a), (b))
#define pgm_read_byte(addr) (*(const unsigned char *)(addr))
#define pgm_read_word(addr) (*(const unsigned short *)(addr))
#define pgm_read_dword(addr) (*(const unsigned long *)(addr))
#define pgm_read_float(addr) (*(const float *)(addr))
#define pgm_read_byte_near(addr) pgm_read_byte(addr)
#define pgm_read_word_near(addr) pgm_read_word(addr)
#define pgm_read_dword_near(addr) pgm_read_dword(addr)
#define pgm_read_float_near(addr) pgm_read_float(addr)
#define pgm_read_byte_far(addr) pgm_read_byte(addr)
#define pgm_read_word_far(addr) pgm_read_word(addr)
#define pgm_read_dword_far(addr) pgm_read_dword(addr)
#define pgm_read_float_far(addr) pgm_read_float(addr)
#endif
#endif
/* Source is from the InvenSense MotionApps v2 demo code. Original source is
* unavailable, unless you happen to be amazing as decompiling binary by
* hand (in which case, please contact me, and I'm totally serious).
*
* Also, I'd like to offer many, many thanks to Noah Zerkin for all of the
* DMP reverse-engineering he did to help make this bit of wizardry
* possible.
*/
// NOTE! Enabling DEBUG adds about 3.3kB to the flash program size.
// Debug output is now working even on ATMega328P MCUs (e.g. Arduino Uno)
// after moving string constants to flash memory storage using the F()
// compiler macro (Arduino IDE 1.0+ required).
//#define DEBUG
#ifdef DEBUG
#define DEBUG_PRINT(x) Serial.print(x)
#define DEBUG_PRINTF(x, y) Serial.print(x, y)
#define DEBUG_PRINTLN(x) Serial.println(x)
#define DEBUG_PRINTLNF(x, y) Serial.println(x, y)
#else
#define DEBUG_PRINT(x)
#define DEBUG_PRINTF(x, y)
#define DEBUG_PRINTLN(x)
#define DEBUG_PRINTLNF(x, y)
#endif
#define MPU6050_DMP_CODE_SIZE 1929 // dmpMemory[]
#define MPU6050_DMP_CONFIG_SIZE 192 // dmpConfig[]
#define MPU6050_DMP_UPDATES_SIZE 47 // dmpUpdates[]
/* ================================================================================================ *
| Default MotionApps v2.0 42-byte FIFO packet structure: |
| |
| [QUAT W][ ][QUAT X][ ][QUAT Y][ ][QUAT Z][ ][GYRO X][ ][GYRO Y][ ] |
| 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
| |
| [GYRO Z][ ][ACC X ][ ][ACC Y ][ ][ACC Z ][ ][ ] |
| 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
* ================================================================================================ */
// this block of memory gets written to the MPU on start-up, and it seems
// to be volatile memory, so it has to be done each time (it only takes ~1
// second though)
const unsigned char dmpMemory[MPU6050_DMP_CODE_SIZE] PROGMEM = {
// bank 0, 256 bytes
0xFB, 0x00, 0x00, 0x3E, 0x00, 0x0B, 0x00, 0x36, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x00,
0x00, 0x65, 0x00, 0x54, 0xFF, 0xEF, 0x00, 0x00, 0xFA, 0x80, 0x00, 0x0B, 0x12, 0x82, 0x00, 0x01,
0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x28, 0x00, 0x00, 0xFF, 0xFF, 0x45, 0x81, 0xFF, 0xFF, 0xFA, 0x72, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x03, 0xE8, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x7F, 0xFF, 0xFF, 0xFE, 0x80, 0x01,
0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x3E, 0x03, 0x30, 0x40, 0x00, 0x00, 0x00, 0x02, 0xCA, 0xE3, 0x09, 0x3E, 0x80, 0x00, 0x00,
0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00,
0x41, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x0B, 0x2A, 0x00, 0x00, 0x16, 0x55, 0x00, 0x00, 0x21, 0x82,
0xFD, 0x87, 0x26, 0x50, 0xFD, 0x80, 0x00, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x00, 0x05, 0x80, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00,
0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x6F, 0x00, 0x02, 0x65, 0x32, 0x00, 0x00, 0x5E, 0xC0,
0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFB, 0x8C, 0x6F, 0x5D, 0xFD, 0x5D, 0x08, 0xD9, 0x00, 0x7C, 0x73, 0x3B, 0x00, 0x6C, 0x12, 0xCC,
0x32, 0x00, 0x13, 0x9D, 0x32, 0x00, 0xD0, 0xD6, 0x32, 0x00, 0x08, 0x00, 0x40, 0x00, 0x01, 0xF4,
0xFF, 0xE6, 0x80, 0x79, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD0, 0xD6, 0x00, 0x00, 0x27, 0x10,
// bank 1, 256 bytes
0xFB, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFA, 0x36, 0xFF, 0xBC, 0x30, 0x8E, 0x00, 0x05, 0xFB, 0xF0, 0xFF, 0xD9, 0x5B, 0xC8,
0xFF, 0xD0, 0x9A, 0xBE, 0x00, 0x00, 0x10, 0xA9, 0xFF, 0xF4, 0x1E, 0xB2, 0x00, 0xCE, 0xBB, 0xF7,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x02, 0x00, 0x02, 0x02, 0x00, 0x00, 0x0C,
0xFF, 0xC2, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0xCF, 0x80, 0x00, 0x40, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x14,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x03, 0x3F, 0x68, 0xB6, 0x79, 0x35, 0x28, 0xBC, 0xC6, 0x7E, 0xD1, 0x6C,
0x80, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0xB2, 0x6A, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0xF0, 0x00, 0x00, 0x00, 0x30,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x25, 0x4D, 0x00, 0x2F, 0x70, 0x6D, 0x00, 0x00, 0x05, 0xAE, 0x00, 0x0C, 0x02, 0xD0,
// bank 2, 256 bytes
0x00, 0x00, 0x00, 0x00, 0x00, 0x65, 0x00, 0x54, 0xFF, 0xEF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x01, 0x00, 0x00, 0x44, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x00, 0x54, 0x00, 0x00, 0xFF, 0xEF, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,
0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// bank 3, 256 bytes
0xD8, 0xDC, 0xBA, 0xA2, 0xF1, 0xDE, 0xB2, 0xB8, 0xB4, 0xA8, 0x81, 0x91, 0xF7, 0x4A, 0x90, 0x7F,
0x91, 0x6A, 0xF3, 0xF9, 0xDB, 0xA8, 0xF9, 0xB0, 0xBA, 0xA0, 0x80, 0xF2, 0xCE, 0x81, 0xF3, 0xC2,
0xF1, 0xC1, 0xF2, 0xC3, 0xF3, 0xCC, 0xA2, 0xB2, 0x80, 0xF1, 0xC6, 0xD8, 0x80, 0xBA, 0xA7, 0xDF,
0xDF, 0xDF, 0xF2, 0xA7, 0xC3, 0xCB, 0xC5, 0xB6, 0xF0, 0x87, 0xA2, 0x94, 0x24, 0x48, 0x70, 0x3C,
0x95, 0x40, 0x68, 0x34, 0x58, 0x9B, 0x78, 0xA2, 0xF1, 0x83, 0x92, 0x2D, 0x55, 0x7D, 0xD8, 0xB1,
0xB4, 0xB8, 0xA1, 0xD0, 0x91, 0x80, 0xF2, 0x70, 0xF3, 0x70, 0xF2, 0x7C, 0x80, 0xA8, 0xF1, 0x01,
0xB0, 0x98, 0x87, 0xD9, 0x43, 0xD8, 0x86, 0xC9, 0x88, 0xBA, 0xA1, 0xF2, 0x0E, 0xB8, 0x97, 0x80,
0xF1, 0xA9, 0xDF, 0xDF, 0xDF, 0xAA, 0xDF, 0xDF, 0xDF, 0xF2, 0xAA, 0xC5, 0xCD, 0xC7, 0xA9, 0x0C,
0xC9, 0x2C, 0x97, 0x97, 0x97, 0x97, 0xF1, 0xA9, 0x89, 0x26, 0x46, 0x66, 0xB0, 0xB4, 0xBA, 0x80,
0xAC, 0xDE, 0xF2, 0xCA, 0xF1, 0xB2, 0x8C, 0x02, 0xA9, 0xB6, 0x98, 0x00, 0x89, 0x0E, 0x16, 0x1E,
0xB8, 0xA9, 0xB4, 0x99, 0x2C, 0x54, 0x7C, 0xB0, 0x8A, 0xA8, 0x96, 0x36, 0x56, 0x76, 0xF1, 0xB9,
0xAF, 0xB4, 0xB0, 0x83, 0xC0, 0xB8, 0xA8, 0x97, 0x11, 0xB1, 0x8F, 0x98, 0xB9, 0xAF, 0xF0, 0x24,
0x08, 0x44, 0x10, 0x64, 0x18, 0xF1, 0xA3, 0x29, 0x55, 0x7D, 0xAF, 0x83, 0xB5, 0x93, 0xAF, 0xF0,
0x00, 0x28, 0x50, 0xF1, 0xA3, 0x86, 0x9F, 0x61, 0xA6, 0xDA, 0xDE, 0xDF, 0xD9, 0xFA, 0xA3, 0x86,
0x96, 0xDB, 0x31, 0xA6, 0xD9, 0xF8, 0xDF, 0xBA, 0xA6, 0x8F, 0xC2, 0xC5, 0xC7, 0xB2, 0x8C, 0xC1,
0xB8, 0xA2, 0xDF, 0xDF, 0xDF, 0xA3, 0xDF, 0xDF, 0xDF, 0xD8, 0xD8, 0xF1, 0xB8, 0xA8, 0xB2, 0x86,
// bank 4, 256 bytes
0xB4, 0x98, 0x0D, 0x35, 0x5D, 0xB8, 0xAA, 0x98, 0xB0, 0x87, 0x2D, 0x35, 0x3D, 0xB2, 0xB6, 0xBA,
0xAF, 0x8C, 0x96, 0x19, 0x8F, 0x9F, 0xA7, 0x0E, 0x16, 0x1E, 0xB4, 0x9A, 0xB8, 0xAA, 0x87, 0x2C,
0x54, 0x7C, 0xB9, 0xA3, 0xDE, 0xDF, 0xDF, 0xA3, 0xB1, 0x80, 0xF2, 0xC4, 0xCD, 0xC9, 0xF1, 0xB8,
0xA9, 0xB4, 0x99, 0x83, 0x0D, 0x35, 0x5D, 0x89, 0xB9, 0xA3, 0x2D, 0x55, 0x7D, 0xB5, 0x93, 0xA3,
0x0E, 0x16, 0x1E, 0xA9, 0x2C, 0x54, 0x7C, 0xB8, 0xB4, 0xB0, 0xF1, 0x97, 0x83, 0xA8, 0x11, 0x84,
0xA5, 0x09, 0x98, 0xA3, 0x83, 0xF0, 0xDA, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0xD8, 0xF1, 0xA5,
0x29, 0x55, 0x7D, 0xA5, 0x85, 0x95, 0x02, 0x1A, 0x2E, 0x3A, 0x56, 0x5A, 0x40, 0x48, 0xF9, 0xF3,
0xA3, 0xD9, 0xF8, 0xF0, 0x98, 0x83, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0x97, 0x82, 0xA8, 0xF1,
0x11, 0xF0, 0x98, 0xA2, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0xDA, 0xF3, 0xDE, 0xD8, 0x83, 0xA5,
0x94, 0x01, 0xD9, 0xA3, 0x02, 0xF1, 0xA2, 0xC3, 0xC5, 0xC7, 0xD8, 0xF1, 0x84, 0x92, 0xA2, 0x4D,
0xDA, 0x2A, 0xD8, 0x48, 0x69, 0xD9, 0x2A, 0xD8, 0x68, 0x55, 0xDA, 0x32, 0xD8, 0x50, 0x71, 0xD9,
0x32, 0xD8, 0x70, 0x5D, 0xDA, 0x3A, 0xD8, 0x58, 0x79, 0xD9, 0x3A, 0xD8, 0x78, 0x93, 0xA3, 0x4D,
0xDA, 0x2A, 0xD8, 0x48, 0x69, 0xD9, 0x2A, 0xD8, 0x68, 0x55, 0xDA, 0x32, 0xD8, 0x50, 0x71, 0xD9,
0x32, 0xD8, 0x70, 0x5D, 0xDA, 0x3A, 0xD8, 0x58, 0x79, 0xD9, 0x3A, 0xD8, 0x78, 0xA8, 0x8A, 0x9A,
0xF0, 0x28, 0x50, 0x78, 0x9E, 0xF3, 0x88, 0x18, 0xF1, 0x9F, 0x1D, 0x98, 0xA8, 0xD9, 0x08, 0xD8,
0xC8, 0x9F, 0x12, 0x9E, 0xF3, 0x15, 0xA8, 0xDA, 0x12, 0x10, 0xD8, 0xF1, 0xAF, 0xC8, 0x97, 0x87,
// bank 5, 256 bytes
0x34, 0xB5, 0xB9, 0x94, 0xA4, 0x21, 0xF3, 0xD9, 0x22, 0xD8, 0xF2, 0x2D, 0xF3, 0xD9, 0x2A, 0xD8,
0xF2, 0x35, 0xF3, 0xD9, 0x32, 0xD8, 0x81, 0xA4, 0x60, 0x60, 0x61, 0xD9, 0x61, 0xD8, 0x6C, 0x68,
0x69, 0xD9, 0x69, 0xD8, 0x74, 0x70, 0x71, 0xD9, 0x71, 0xD8, 0xB1, 0xA3, 0x84, 0x19, 0x3D, 0x5D,
0xA3, 0x83, 0x1A, 0x3E, 0x5E, 0x93, 0x10, 0x30, 0x81, 0x10, 0x11, 0xB8, 0xB0, 0xAF, 0x8F, 0x94,
0xF2, 0xDA, 0x3E, 0xD8, 0xB4, 0x9A, 0xA8, 0x87, 0x29, 0xDA, 0xF8, 0xD8, 0x87, 0x9A, 0x35, 0xDA,
0xF8, 0xD8, 0x87, 0x9A, 0x3D, 0xDA, 0xF8, 0xD8, 0xB1, 0xB9, 0xA4, 0x98, 0x85, 0x02, 0x2E, 0x56,
0xA5, 0x81, 0x00, 0x0C, 0x14, 0xA3, 0x97, 0xB0, 0x8A, 0xF1, 0x2D, 0xD9, 0x28, 0xD8, 0x4D, 0xD9,
0x48, 0xD8, 0x6D, 0xD9, 0x68, 0xD8, 0xB1, 0x84, 0x0D, 0xDA, 0x0E, 0xD8, 0xA3, 0x29, 0x83, 0xDA,
0x2C, 0x0E, 0xD8, 0xA3, 0x84, 0x49, 0x83, 0xDA, 0x2C, 0x4C, 0x0E, 0xD8, 0xB8, 0xB0, 0xA8, 0x8A,
0x9A, 0xF5, 0x20, 0xAA, 0xDA, 0xDF, 0xD8, 0xA8, 0x40, 0xAA, 0xD0, 0xDA, 0xDE, 0xD8, 0xA8, 0x60,
0xAA, 0xDA, 0xD0, 0xDF, 0xD8, 0xF1, 0x97, 0x86, 0xA8, 0x31, 0x9B, 0x06, 0x99, 0x07, 0xAB, 0x97,
0x28, 0x88, 0x9B, 0xF0, 0x0C, 0x20, 0x14, 0x40, 0xB8, 0xB0, 0xB4, 0xA8, 0x8C, 0x9C, 0xF0, 0x04,
0x28, 0x51, 0x79, 0x1D, 0x30, 0x14, 0x38, 0xB2, 0x82, 0xAB, 0xD0, 0x98, 0x2C, 0x50, 0x50, 0x78,
0x78, 0x9B, 0xF1, 0x1A, 0xB0, 0xF0, 0x8A, 0x9C, 0xA8, 0x29, 0x51, 0x79, 0x8B, 0x29, 0x51, 0x79,
0x8A, 0x24, 0x70, 0x59, 0x8B, 0x20, 0x58, 0x71, 0x8A, 0x44, 0x69, 0x38, 0x8B, 0x39, 0x40, 0x68,
0x8A, 0x64, 0x48, 0x31, 0x8B, 0x30, 0x49, 0x60, 0xA5, 0x88, 0x20, 0x09, 0x71, 0x58, 0x44, 0x68,
// bank 6, 256 bytes
0x11, 0x39, 0x64, 0x49, 0x30, 0x19, 0xF1, 0xAC, 0x00, 0x2C, 0x54, 0x7C, 0xF0, 0x8C, 0xA8, 0x04,
0x28, 0x50, 0x78, 0xF1, 0x88, 0x97, 0x26, 0xA8, 0x59, 0x98, 0xAC, 0x8C, 0x02, 0x26, 0x46, 0x66,
0xF0, 0x89, 0x9C, 0xA8, 0x29, 0x51, 0x79, 0x24, 0x70, 0x59, 0x44, 0x69, 0x38, 0x64, 0x48, 0x31,
0xA9, 0x88, 0x09, 0x20, 0x59, 0x70, 0xAB, 0x11, 0x38, 0x40, 0x69, 0xA8, 0x19, 0x31, 0x48, 0x60,
0x8C, 0xA8, 0x3C, 0x41, 0x5C, 0x20, 0x7C, 0x00, 0xF1, 0x87, 0x98, 0x19, 0x86, 0xA8, 0x6E, 0x76,
0x7E, 0xA9, 0x99, 0x88, 0x2D, 0x55, 0x7D, 0x9E, 0xB9, 0xA3, 0x8A, 0x22, 0x8A, 0x6E, 0x8A, 0x56,
0x8A, 0x5E, 0x9F, 0xB1, 0x83, 0x06, 0x26, 0x46, 0x66, 0x0E, 0x2E, 0x4E, 0x6E, 0x9D, 0xB8, 0xAD,
0x00, 0x2C, 0x54, 0x7C, 0xF2, 0xB1, 0x8C, 0xB4, 0x99, 0xB9, 0xA3, 0x2D, 0x55, 0x7D, 0x81, 0x91,
0xAC, 0x38, 0xAD, 0x3A, 0xB5, 0x83, 0x91, 0xAC, 0x2D, 0xD9, 0x28, 0xD8, 0x4D, 0xD9, 0x48, 0xD8,
0x6D, 0xD9, 0x68, 0xD8, 0x8C, 0x9D, 0xAE, 0x29, 0xD9, 0x04, 0xAE, 0xD8, 0x51, 0xD9, 0x04, 0xAE,
0xD8, 0x79, 0xD9, 0x04, 0xD8, 0x81, 0xF3, 0x9D, 0xAD, 0x00, 0x8D, 0xAE, 0x19, 0x81, 0xAD, 0xD9,
0x01, 0xD8, 0xF2, 0xAE, 0xDA, 0x26, 0xD8, 0x8E, 0x91, 0x29, 0x83, 0xA7, 0xD9, 0xAD, 0xAD, 0xAD,
0xAD, 0xF3, 0x2A, 0xD8, 0xD8, 0xF1, 0xB0, 0xAC, 0x89, 0x91, 0x3E, 0x5E, 0x76, 0xF3, 0xAC, 0x2E,
0x2E, 0xF1, 0xB1, 0x8C, 0x5A, 0x9C, 0xAC, 0x2C, 0x28, 0x28, 0x28, 0x9C, 0xAC, 0x30, 0x18, 0xA8,
0x98, 0x81, 0x28, 0x34, 0x3C, 0x97, 0x24, 0xA7, 0x28, 0x34, 0x3C, 0x9C, 0x24, 0xF2, 0xB0, 0x89,
0xAC, 0x91, 0x2C, 0x4C, 0x6C, 0x8A, 0x9B, 0x2D, 0xD9, 0xD8, 0xD8, 0x51, 0xD9, 0xD8, 0xD8, 0x79,
// bank 7, 138 bytes (remainder)
0xD9, 0xD8, 0xD8, 0xF1, 0x9E, 0x88, 0xA3, 0x31, 0xDA, 0xD8, 0xD8, 0x91, 0x2D, 0xD9, 0x28, 0xD8,
0x4D, 0xD9, 0x48, 0xD8, 0x6D, 0xD9, 0x68, 0xD8, 0xB1, 0x83, 0x93, 0x35, 0x3D, 0x80, 0x25, 0xDA,
0xD8, 0xD8, 0x85, 0x69, 0xDA, 0xD8, 0xD8, 0xB4, 0x93, 0x81, 0xA3, 0x28, 0x34, 0x3C, 0xF3, 0xAB,
0x8B, 0xF8, 0xA3, 0x91, 0xB6, 0x09, 0xB4, 0xD9, 0xAB, 0xDE, 0xFA, 0xB0, 0x87, 0x9C, 0xB9, 0xA3,
0xDD, 0xF1, 0xA3, 0xA3, 0xA3, 0xA3, 0x95, 0xF1, 0xA3, 0xA3, 0xA3, 0x9D, 0xF1, 0xA3, 0xA3, 0xA3,
0xA3, 0xF2, 0xA3, 0xB4, 0x90, 0x80, 0xF2, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3,
0xA3, 0xB2, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xB0, 0x87, 0xB5, 0x99, 0xF1, 0xA3, 0xA3, 0xA3,
0x98, 0xF1, 0xA3, 0xA3, 0xA3, 0xA3, 0x97, 0xA3, 0xA3, 0xA3, 0xA3, 0xF3, 0x9B, 0xA3, 0xA3, 0xDC,
0xB9, 0xA7, 0xF1, 0x26, 0x26, 0x26, 0xD8, 0xD8, 0xFF
};
// thanks to Noah Zerkin for piecing this stuff together!
const unsigned char dmpConfig[MPU6050_DMP_CONFIG_SIZE] PROGMEM = {
// BANK OFFSET LENGTH [DATA]
0x03, 0x7B, 0x03, 0x4C, 0xCD, 0x6C, // FCFG_1 inv_set_gyro_calibration
0x03, 0xAB, 0x03, 0x36, 0x56, 0x76, // FCFG_3 inv_set_gyro_calibration
0x00, 0x68, 0x04, 0x02, 0xCB, 0x47, 0xA2, // D_0_104 inv_set_gyro_calibration
0x02, 0x18, 0x04, 0x00, 0x05, 0x8B, 0xC1, // D_0_24 inv_set_gyro_calibration
0x01, 0x0C, 0x04, 0x00, 0x00, 0x00, 0x00, // D_1_152 inv_set_accel_calibration
0x03, 0x7F, 0x06, 0x0C, 0xC9, 0x2C, 0x97, 0x97, 0x97, // FCFG_2 inv_set_accel_calibration
0x03, 0x89, 0x03, 0x26, 0x46, 0x66, // FCFG_7 inv_set_accel_calibration
0x00, 0x6C, 0x02, 0x20, 0x00, // D_0_108 inv_set_accel_calibration
0x02, 0x40, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_00 inv_set_compass_calibration
0x02, 0x44, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_01
0x02, 0x48, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_02
0x02, 0x4C, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_10
0x02, 0x50, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_11
0x02, 0x54, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_12
0x02, 0x58, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_20
0x02, 0x5C, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_21
0x02, 0xBC, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_22
0x01, 0xEC, 0x04, 0x00, 0x00, 0x40, 0x00, // D_1_236 inv_apply_endian_accel
0x03, 0x7F, 0x06, 0x0C, 0xC9, 0x2C, 0x97, 0x97, 0x97, // FCFG_2 inv_set_mpu_sensors
0x04, 0x02, 0x03, 0x0D, 0x35, 0x5D, // CFG_MOTION_BIAS inv_turn_on_bias_from_no_motion
0x04, 0x09, 0x04, 0x87, 0x2D, 0x35, 0x3D, // FCFG_5 inv_set_bias_update
0x00, 0xA3, 0x01, 0x00, // D_0_163 inv_set_dead_zone
// SPECIAL 0x01 = enable interrupts
0x00, 0x00, 0x00, 0x01, // SET INT_ENABLE at i=22, SPECIAL INSTRUCTION
0x07, 0x86, 0x01, 0xFE, // CFG_6 inv_set_fifo_interupt
0x07, 0x41, 0x05, 0xF1, 0x20, 0x28, 0x30, 0x38, // CFG_8 inv_send_quaternion
0x07, 0x7E, 0x01, 0x30, // CFG_16 inv_set_footer
0x07, 0x46, 0x01, 0x9A, // CFG_GYRO_SOURCE inv_send_gyro
0x07, 0x47, 0x04, 0xF1, 0x28, 0x30, 0x38, // CFG_9 inv_send_gyro -> inv_construct3_fifo
0x07, 0x6C, 0x04, 0xF1, 0x28, 0x30, 0x38, // CFG_12 inv_send_accel -> inv_construct3_fifo
0x02, 0x16, 0x02, 0x00, 0x09 // D_0_22 inv_set_fifo_rate
// This very last 0x01 WAS a 0x09, which drops the FIFO rate down to 20 Hz. 0x07 is 25 Hz,
// 0x01 is 100Hz. Going faster than 100Hz (0x00=200Hz) tends to result in very noisy data.
// DMP output frequency is calculated easily using this equation: (200Hz / (1 + value))
// It is important to make sure the host processor can keep up with reading and processing
// the FIFO output at the desired rate. Handling FIFO overflow cleanly is also a good idea.
};
const unsigned char dmpUpdates[MPU6050_DMP_UPDATES_SIZE] PROGMEM = {
0x01, 0xB2, 0x02, 0xFF, 0xFF,
0x01, 0x90, 0x04, 0x09, 0x23, 0xA1, 0x35,
0x01, 0x6A, 0x02, 0x06, 0x00,
0x01, 0x60, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x60, 0x04, 0x40, 0x00, 0x00, 0x00,
0x01, 0x62, 0x02, 0x00, 0x00,
0x00, 0x60, 0x04, 0x00, 0x40, 0x00, 0x00
};
uint8_t MPU6050::dmpInitialize() {
// reset device
DEBUG_PRINTLN(F("\n\nResetting MPU6050..."));
reset();
delay(30); // wait after reset
// enable sleep mode and wake cycle
/*Serial.println(F("Enabling sleep mode..."));
setSleepEnabled(true);
Serial.println(F("Enabling wake cycle..."));
setWakeCycleEnabled(true);*/
// disable sleep mode
DEBUG_PRINTLN(F("Disabling sleep mode..."));
setSleepEnabled(false);
// get MPU hardware revision
DEBUG_PRINTLN(F("Selecting user bank 16..."));
setMemoryBank(0x10, true, true);
DEBUG_PRINTLN(F("Selecting memory byte 6..."));
setMemoryStartAddress(0x06);
DEBUG_PRINTLN(F("Checking hardware revision..."));
uint8_t hwRevision = readMemoryByte();
DEBUG_PRINT(F("Revision @ user[16][6] = "));
DEBUG_PRINTLNF(hwRevision, HEX);
DEBUG_PRINTLN(F("Resetting memory bank selection to 0..."));
setMemoryBank(0, false, false);
// check OTP bank valid
DEBUG_PRINTLN(F("Reading OTP bank valid flag..."));
uint8_t otpValid = getOTPBankValid();
DEBUG_PRINT(F("OTP bank is "));
DEBUG_PRINTLN(otpValid ? F("valid!") : F("invalid!"));
// get X/Y/Z gyro offsets
DEBUG_PRINTLN(F("Reading gyro offset TC values..."));
int8_t xgOffsetTC = getXGyroOffsetTC();
int8_t ygOffsetTC = getYGyroOffsetTC();
int8_t zgOffsetTC = getZGyroOffsetTC();
DEBUG_PRINT(F("X gyro offset = "));
DEBUG_PRINTLN(xgOffset);
DEBUG_PRINT(F("Y gyro offset = "));
DEBUG_PRINTLN(ygOffset);
DEBUG_PRINT(F("Z gyro offset = "));
DEBUG_PRINTLN(zgOffset);
// setup weird slave stuff (?)
DEBUG_PRINTLN(F("Setting slave 0 address to 0x7F..."));
setSlaveAddress(0, 0x7F);
DEBUG_PRINTLN(F("Disabling I2C Master mode..."));
setI2CMasterModeEnabled(false);
DEBUG_PRINTLN(F("Setting slave 0 address to 0x68 (self)..."));
setSlaveAddress(0, 0x68);
DEBUG_PRINTLN(F("Resetting I2C Master control..."));
resetI2CMaster();
delay(20);
// load DMP code into memory banks
DEBUG_PRINT(F("Writing DMP code to MPU memory banks ("));
DEBUG_PRINT(MPU6050_DMP_CODE_SIZE);
DEBUG_PRINTLN(F(" bytes)"));
if (writeProgMemoryBlock(dmpMemory, MPU6050_DMP_CODE_SIZE)) {
DEBUG_PRINTLN(F("Success! DMP code written and verified."));
// write DMP configuration
DEBUG_PRINT(F("Writing DMP configuration to MPU memory banks ("));
DEBUG_PRINT(MPU6050_DMP_CONFIG_SIZE);
DEBUG_PRINTLN(F(" bytes in config def)"));
if (writeProgDMPConfigurationSet(dmpConfig, MPU6050_DMP_CONFIG_SIZE)) {
DEBUG_PRINTLN(F("Success! DMP configuration written and verified."));
DEBUG_PRINTLN(F("Setting clock source to Z Gyro..."));
setClockSource(MPU6050_CLOCK_PLL_ZGYRO);
DEBUG_PRINTLN(F("Setting DMP and FIFO_OFLOW interrupts enabled..."));
setIntEnabled(0x12);
DEBUG_PRINTLN(F("Setting sample rate to 200Hz..."));
setRate(4); // 1khz / (1 + 4) = 200 Hz
DEBUG_PRINTLN(F("Setting external frame sync to TEMP_OUT_L[0]..."));
setExternalFrameSync(MPU6050_EXT_SYNC_TEMP_OUT_L);
DEBUG_PRINTLN(F("Setting DLPF bandwidth to 42Hz..."));
setDLPFMode(MPU6050_DLPF_BW_42);
DEBUG_PRINTLN(F("Setting gyro sensitivity to +/- 2000 deg/sec..."));
setFullScaleGyroRange(MPU6050_GYRO_FS_2000);
DEBUG_PRINTLN(F("Setting DMP configuration bytes (function unknown)..."));
setDMPConfig1(0x03);
setDMPConfig2(0x00);
DEBUG_PRINTLN(F("Clearing OTP Bank flag..."));
setOTPBankValid(false);
DEBUG_PRINTLN(F("Setting X/Y/Z gyro offset TCs to previous values..."));
setXGyroOffsetTC(xgOffsetTC);
setYGyroOffsetTC(ygOffsetTC);
setZGyroOffsetTC(zgOffsetTC);
//DEBUG_PRINTLN(F("Setting X/Y/Z gyro user offsets to zero..."));
//setXGyroOffset(0);
//setYGyroOffset(0);
//setZGyroOffset(0);
DEBUG_PRINTLN(F("Writing final memory update 1/7 (function unknown)..."));
uint8_t dmpUpdate[16], j;
uint16_t pos = 0;
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
DEBUG_PRINTLN(F("Writing final memory update 2/7 (function unknown)..."));
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
DEBUG_PRINTLN(F("Resetting FIFO..."));
resetFIFO();
DEBUG_PRINTLN(F("Reading FIFO count..."));
uint16_t fifoCount = getFIFOCount();
uint8_t fifoBuffer[128];
DEBUG_PRINT(F("Current FIFO count="));
DEBUG_PRINTLN(fifoCount);
getFIFOBytes(fifoBuffer, fifoCount);
DEBUG_PRINTLN(F("Setting motion detection threshold to 2..."));
setMotionDetectionThreshold(2);
DEBUG_PRINTLN(F("Setting zero-motion detection threshold to 156..."));
setZeroMotionDetectionThreshold(156);
DEBUG_PRINTLN(F("Setting motion detection duration to 80..."));
setMotionDetectionDuration(80);
DEBUG_PRINTLN(F("Setting zero-motion detection duration to 0..."));
setZeroMotionDetectionDuration(0);
DEBUG_PRINTLN(F("Resetting FIFO..."));
resetFIFO();
DEBUG_PRINTLN(F("Enabling FIFO..."));
setFIFOEnabled(true);
DEBUG_PRINTLN(F("Enabling DMP..."));
setDMPEnabled(true);
DEBUG_PRINTLN(F("Resetting DMP..."));
resetDMP();
DEBUG_PRINTLN(F("Writing final memory update 3/7 (function unknown)..."));
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
DEBUG_PRINTLN(F("Writing final memory update 4/7 (function unknown)..."));
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
DEBUG_PRINTLN(F("Writing final memory update 5/7 (function unknown)..."));
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
DEBUG_PRINTLN(F("Waiting for FIFO count > 2..."));
while ((fifoCount = getFIFOCount()) < 3);
DEBUG_PRINT(F("Current FIFO count="));
DEBUG_PRINTLN(fifoCount);
DEBUG_PRINTLN(F("Reading FIFO data..."));
getFIFOBytes(fifoBuffer, fifoCount);
DEBUG_PRINTLN(F("Reading interrupt status..."));
uint8_t mpuIntStatus = getIntStatus();
DEBUG_PRINT(F("Current interrupt status="));
DEBUG_PRINTLNF(mpuIntStatus, HEX);
DEBUG_PRINTLN(F("Reading final memory update 6/7 (function unknown)..."));
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
readMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
DEBUG_PRINTLN(F("Waiting for FIFO count > 2..."));
while ((fifoCount = getFIFOCount()) < 3);
DEBUG_PRINT(F("Current FIFO count="));
DEBUG_PRINTLN(fifoCount);
DEBUG_PRINTLN(F("Reading FIFO data..."));
getFIFOBytes(fifoBuffer, fifoCount);
DEBUG_PRINTLN(F("Reading interrupt status..."));
mpuIntStatus = getIntStatus();
DEBUG_PRINT(F("Current interrupt status="));
DEBUG_PRINTLNF(mpuIntStatus, HEX);
DEBUG_PRINTLN(F("Writing final memory update 7/7 (function unknown)..."));
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
DEBUG_PRINTLN(F("DMP is good to go! Finally."));
DEBUG_PRINTLN(F("Disabling DMP (you turn it on later)..."));
setDMPEnabled(false);
DEBUG_PRINTLN(F("Setting up internal 42-byte (default) DMP packet buffer..."));
dmpPacketSize = 42;
/*if ((dmpPacketBuffer = (uint8_t *)malloc(42)) == 0) {
return 3; // TODO: proper error code for no memory
}*/
DEBUG_PRINTLN(F("Resetting FIFO and clearing INT status one last time..."));
resetFIFO();
getIntStatus();
} else {
DEBUG_PRINTLN(F("ERROR! DMP configuration verification failed."));
return 2; // configuration block loading failed
}
} else {
DEBUG_PRINTLN(F("ERROR! DMP code verification failed."));
return 1; // main binary block loading failed
}
return 0; // success
}
bool MPU6050::dmpPacketAvailable() {
return getFIFOCount() >= dmpGetFIFOPacketSize();
}
// uint8_t MPU6050::dmpSetFIFORate(uint8_t fifoRate);
// uint8_t MPU6050::dmpGetFIFORate();
// uint8_t MPU6050::dmpGetSampleStepSizeMS();
// uint8_t MPU6050::dmpGetSampleFrequency();
// int32_t MPU6050::dmpDecodeTemperature(int8_t tempReg);
//uint8_t MPU6050::dmpRegisterFIFORateProcess(inv_obj_func func, int16_t priority);
//uint8_t MPU6050::dmpUnregisterFIFORateProcess(inv_obj_func func);
//uint8_t MPU6050::dmpRunFIFORateProcesses();
// uint8_t MPU6050::dmpSendQuaternion(uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendGyro(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendAccel(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendLinearAccel(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendLinearAccelInWorld(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendControlData(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendSensorData(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendExternalSensorData(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendGravity(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendPacketNumber(uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendQuantizedAccel(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendEIS(uint_fast16_t elements, uint_fast16_t accuracy);
uint8_t MPU6050::dmpGetAccel(int32_t *data, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
data[0] = ((packet[28] << 24) + (packet[29] << 16) + (packet[30] << 8) + packet[31]);
data[1] = ((packet[32] << 24) + (packet[33] << 16) + (packet[34] << 8) + packet[35]);
data[2] = ((packet[36] << 24) + (packet[37] << 16) + (packet[38] << 8) + packet[39]);
return 0;
}
uint8_t MPU6050::dmpGetAccel(int16_t *data, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
data[0] = (packet[28] << 8) + packet[29];
data[1] = (packet[32] << 8) + packet[33];
data[2] = (packet[36] << 8) + packet[37];
return 0;
}
uint8_t MPU6050::dmpGetAccel(VectorInt16 *v, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
v -> x = (packet[28] << 8) + packet[29];
v -> y = (packet[32] << 8) + packet[33];
v -> z = (packet[36] << 8) + packet[37];
return 0;
}
uint8_t MPU6050::dmpGetQuaternion(int32_t *data, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
data[0] = ((packet[0] << 24) + (packet[1] << 16) + (packet[2] << 8) + packet[3]);
data[1] = ((packet[4] << 24) + (packet[5] << 16) + (packet[6] << 8) + packet[7]);
data[2] = ((packet[8] << 24) + (packet[9] << 16) + (packet[10] << 8) + packet[11]);
data[3] = ((packet[12] << 24) + (packet[13] << 16) + (packet[14] << 8) + packet[15]);
return 0;
}
uint8_t MPU6050::dmpGetQuaternion(int16_t *data, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
data[0] = ((packet[0] << 8) + packet[1]);
data[1] = ((packet[4] << 8) + packet[5]);
data[2] = ((packet[8] << 8) + packet[9]);
data[3] = ((packet[12] << 8) + packet[13]);
return 0;
}
uint8_t MPU6050::dmpGetQuaternion(Quaternion *q, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
int16_t qI[4];
uint8_t status = dmpGetQuaternion(qI, packet);
if (status == 0) {
q -> w = (float)qI[0] / 16384.0f;
q -> x = (float)qI[1] / 16384.0f;
q -> y = (float)qI[2] / 16384.0f;
q -> z = (float)qI[3] / 16384.0f;
return 0;
}
return status; // int16 return value, indicates error if this line is reached
}
// uint8_t MPU6050::dmpGet6AxisQuaternion(long *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetRelativeQuaternion(long *data, const uint8_t* packet);
uint8_t MPU6050::dmpGetGyro(int32_t *data, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
data[0] = ((packet[16] << 24) + (packet[17] << 16) + (packet[18] << 8) + packet[19]);
data[1] = ((packet[20] << 24) + (packet[21] << 16) + (packet[22] << 8) + packet[23]);
data[2] = ((packet[24] << 24) + (packet[25] << 16) + (packet[26] << 8) + packet[27]);
return 0;
}
uint8_t MPU6050::dmpGetGyro(int16_t *data, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
data[0] = (packet[16] << 8) + packet[17];
data[1] = (packet[20] << 8) + packet[21];
data[2] = (packet[24] << 8) + packet[25];
return 0;
}
uint8_t MPU6050::dmpGetGyro(VectorInt16 *v, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
v -> x = (packet[16] << 8) + packet[17];
v -> y = (packet[20] << 8) + packet[21];
v -> z = (packet[24] << 8) + packet[25];
return 0;
}
// uint8_t MPU6050::dmpSetLinearAccelFilterCoefficient(float coef);
// uint8_t MPU6050::dmpGetLinearAccel(long *data, const uint8_t* packet);
uint8_t MPU6050::dmpGetLinearAccel(VectorInt16 *v, VectorInt16 *vRaw, VectorFloat *gravity) {
// get rid of the gravity component (+1g = +8192 in standard DMP FIFO packet, sensitivity is 2g)
v -> x = vRaw -> x - gravity -> x*8192;
v -> y = vRaw -> y - gravity -> y*8192;
v -> z = vRaw -> z - gravity -> z*8192;
return 0;
}
// uint8_t MPU6050::dmpGetLinearAccelInWorld(long *data, const uint8_t* packet);
uint8_t MPU6050::dmpGetLinearAccelInWorld(VectorInt16 *v, VectorInt16 *vReal, Quaternion *q) {
// rotate measured 3D acceleration vector into original state
// frame of reference based on orientation quaternion
memcpy(v, vReal, sizeof(VectorInt16));
v -> rotate(q);
return 0;
}
// uint8_t MPU6050::dmpGetGyroAndAccelSensor(long *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetGyroSensor(long *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetControlData(long *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetTemperature(long *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetGravity(long *data, const uint8_t* packet);
uint8_t MPU6050::dmpGetGravity(VectorFloat *v, Quaternion *q) {
v -> x = 2 * (q -> x*q -> z - q -> w*q -> y);
v -> y = 2 * (q -> w*q -> x + q -> y*q -> z);
v -> z = q -> w*q -> w - q -> x*q -> x - q -> y*q -> y + q -> z*q -> z;
return 0;
}
// uint8_t MPU6050::dmpGetUnquantizedAccel(long *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetQuantizedAccel(long *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetExternalSensorData(long *data, int size, const uint8_t* packet);
// uint8_t MPU6050::dmpGetEIS(long *data, const uint8_t* packet);
uint8_t MPU6050::dmpGetEuler(float *data, Quaternion *q) {
data[0] = atan2(2*q -> x*q -> y - 2*q -> w*q -> z, 2*q -> w*q -> w + 2*q -> x*q -> x - 1); // psi
data[1] = -asin(2*q -> x*q -> z + 2*q -> w*q -> y); // theta
data[2] = atan2(2*q -> y*q -> z - 2*q -> w*q -> x, 2*q -> w*q -> w + 2*q -> z*q -> z - 1); // phi
return 0;
}
uint8_t MPU6050::dmpGetYawPitchRoll(float *data, Quaternion *q, VectorFloat *gravity) {
// yaw: (about Z axis)
data[0] = atan2(2*q -> x*q -> y - 2*q -> w*q -> z, 2*q -> w*q -> w + 2*q -> x*q -> x - 1);
// pitch: (nose up/down, about Y axis)
data[1] = atan(gravity -> x / sqrt(gravity -> y*gravity -> y + gravity -> z*gravity -> z));
// roll: (tilt left/right, about X axis)
data[2] = atan(gravity -> y / sqrt(gravity -> x*gravity -> x + gravity -> z*gravity -> z));
return 0;
}
// uint8_t MPU6050::dmpGetAccelFloat(float *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetQuaternionFloat(float *data, const uint8_t* packet);
uint8_t MPU6050::dmpProcessFIFOPacket(const unsigned char *dmpData) {
/*for (uint8_t k = 0; k < dmpPacketSize; k++) {
if (dmpData[k] < 0x10) Serial.print("0");
Serial.print(dmpData[k], HEX);
Serial.print(" ");
}
Serial.print("\n");*/
//Serial.println((uint16_t)dmpPacketBuffer);
return 0;
}
uint8_t MPU6050::dmpReadAndProcessFIFOPacket(uint8_t numPackets, uint8_t *processed) {
uint8_t status;
uint8_t buf[dmpPacketSize];
for (uint8_t i = 0; i < numPackets; i++) {
// read packet from FIFO
getFIFOBytes(buf, dmpPacketSize);
// process packet
if ((status = dmpProcessFIFOPacket(buf)) > 0) return status;
// increment external process count variable, if supplied
if (processed != 0) *processed++;
}
return 0;
}
// uint8_t MPU6050::dmpSetFIFOProcessedCallback(void (*func) (void));
// uint8_t MPU6050::dmpInitFIFOParam();
// uint8_t MPU6050::dmpCloseFIFO();
// uint8_t MPU6050::dmpSetGyroDataSource(uint_fast8_t source);
// uint8_t MPU6050::dmpDecodeQuantizedAccel();
// uint32_t MPU6050::dmpGetGyroSumOfSquare();
// uint32_t MPU6050::dmpGetAccelSumOfSquare();
// void MPU6050::dmpOverrideQuaternion(long *q);
uint16_t MPU6050::dmpGetFIFOPacketSize() {
return dmpPacketSize;
}
#endif /* _MPU6050_6AXIS_MOTIONAPPS20_H_ */
| 41,027 | C | 53.704 | 114 | 0.617106 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/openDogV2/openDogV2-original/Release01/Code/openDogV2_R1/MPU6050_6Axis_MotionApps20.h | // I2Cdev library collection - MPU6050 I2C device class, 6-axis MotionApps 2.0 implementation
// Based on InvenSense MPU-6050 register map document rev. 2.0, 5/19/2011 (RM-MPU-6000A-00)
// 5/20/2013 by Jeff Rowberg <jeff@rowberg.net>
// Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib
//
// Changelog:
// ... - ongoing debug release
/* ============================================
I2Cdev device library code is placed under the MIT license
Copyright (c) 2012 Jeff Rowberg
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
===============================================
*/
#ifndef _MPU6050_6AXIS_MOTIONAPPS20_H_
#define _MPU6050_6AXIS_MOTIONAPPS20_H_
#include "I2Cdev.h"
#include "helper_3dmath.h"
// MotionApps 2.0 DMP implementation, built using the MPU-6050EVB evaluation board
#define MPU6050_INCLUDE_DMP_MOTIONAPPS20
#include "MPU6050.h"
// Tom Carpenter's conditional PROGMEM code
// http://forum.arduino.cc/index.php?topic=129407.0
#ifndef __arm__
#include <avr/pgmspace.h>
#else
// Teensy 3.0 library conditional PROGMEM code from Paul Stoffregen
#ifndef __PGMSPACE_H_
#define __PGMSPACE_H_ 1
#include <inttypes.h>
#define PROGMEM
#define PGM_P const char *
#define PSTR(str) (str)
#define F(x) x
typedef void prog_void;
typedef char prog_char;
typedef unsigned char prog_uchar;
typedef int8_t prog_int8_t;
typedef uint8_t prog_uint8_t;
typedef int16_t prog_int16_t;
typedef uint16_t prog_uint16_t;
typedef int32_t prog_int32_t;
typedef uint32_t prog_uint32_t;
#define strcpy_P(dest, src) strcpy((dest), (src))
#define strcat_P(dest, src) strcat((dest), (src))
#define strcmp_P(a, b) strcmp((a), (b))
#define pgm_read_byte(addr) (*(const unsigned char *)(addr))
#define pgm_read_word(addr) (*(const unsigned short *)(addr))
#define pgm_read_dword(addr) (*(const unsigned long *)(addr))
#define pgm_read_float(addr) (*(const float *)(addr))
#define pgm_read_byte_near(addr) pgm_read_byte(addr)
#define pgm_read_word_near(addr) pgm_read_word(addr)
#define pgm_read_dword_near(addr) pgm_read_dword(addr)
#define pgm_read_float_near(addr) pgm_read_float(addr)
#define pgm_read_byte_far(addr) pgm_read_byte(addr)
#define pgm_read_word_far(addr) pgm_read_word(addr)
#define pgm_read_dword_far(addr) pgm_read_dword(addr)
#define pgm_read_float_far(addr) pgm_read_float(addr)
#endif
#endif
/* Source is from the InvenSense MotionApps v2 demo code. Original source is
* unavailable, unless you happen to be amazing as decompiling binary by
* hand (in which case, please contact me, and I'm totally serious).
*
* Also, I'd like to offer many, many thanks to Noah Zerkin for all of the
* DMP reverse-engineering he did to help make this bit of wizardry
* possible.
*/
// NOTE! Enabling DEBUG adds about 3.3kB to the flash program size.
// Debug output is now working even on ATMega328P MCUs (e.g. Arduino Uno)
// after moving string constants to flash memory storage using the F()
// compiler macro (Arduino IDE 1.0+ required).
//#define DEBUG
#ifdef DEBUG
#define DEBUG_PRINT(x) Serial.print(x)
#define DEBUG_PRINTF(x, y) Serial.print(x, y)
#define DEBUG_PRINTLN(x) Serial.println(x)
#define DEBUG_PRINTLNF(x, y) Serial.println(x, y)
#else
#define DEBUG_PRINT(x)
#define DEBUG_PRINTF(x, y)
#define DEBUG_PRINTLN(x)
#define DEBUG_PRINTLNF(x, y)
#endif
#define MPU6050_DMP_CODE_SIZE 1929 // dmpMemory[]
#define MPU6050_DMP_CONFIG_SIZE 192 // dmpConfig[]
#define MPU6050_DMP_UPDATES_SIZE 47 // dmpUpdates[]
/* ================================================================================================ *
| Default MotionApps v2.0 42-byte FIFO packet structure: |
| |
| [QUAT W][ ][QUAT X][ ][QUAT Y][ ][QUAT Z][ ][GYRO X][ ][GYRO Y][ ] |
| 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
| |
| [GYRO Z][ ][ACC X ][ ][ACC Y ][ ][ACC Z ][ ][ ] |
| 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
* ================================================================================================ */
// this block of memory gets written to the MPU on start-up, and it seems
// to be volatile memory, so it has to be done each time (it only takes ~1
// second though)
const unsigned char dmpMemory[MPU6050_DMP_CODE_SIZE] PROGMEM = {
// bank 0, 256 bytes
0xFB, 0x00, 0x00, 0x3E, 0x00, 0x0B, 0x00, 0x36, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x00,
0x00, 0x65, 0x00, 0x54, 0xFF, 0xEF, 0x00, 0x00, 0xFA, 0x80, 0x00, 0x0B, 0x12, 0x82, 0x00, 0x01,
0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x28, 0x00, 0x00, 0xFF, 0xFF, 0x45, 0x81, 0xFF, 0xFF, 0xFA, 0x72, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x03, 0xE8, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x7F, 0xFF, 0xFF, 0xFE, 0x80, 0x01,
0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x3E, 0x03, 0x30, 0x40, 0x00, 0x00, 0x00, 0x02, 0xCA, 0xE3, 0x09, 0x3E, 0x80, 0x00, 0x00,
0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00,
0x41, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x0B, 0x2A, 0x00, 0x00, 0x16, 0x55, 0x00, 0x00, 0x21, 0x82,
0xFD, 0x87, 0x26, 0x50, 0xFD, 0x80, 0x00, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x00, 0x05, 0x80, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00,
0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x6F, 0x00, 0x02, 0x65, 0x32, 0x00, 0x00, 0x5E, 0xC0,
0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xFB, 0x8C, 0x6F, 0x5D, 0xFD, 0x5D, 0x08, 0xD9, 0x00, 0x7C, 0x73, 0x3B, 0x00, 0x6C, 0x12, 0xCC,
0x32, 0x00, 0x13, 0x9D, 0x32, 0x00, 0xD0, 0xD6, 0x32, 0x00, 0x08, 0x00, 0x40, 0x00, 0x01, 0xF4,
0xFF, 0xE6, 0x80, 0x79, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD0, 0xD6, 0x00, 0x00, 0x27, 0x10,
// bank 1, 256 bytes
0xFB, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0xFA, 0x36, 0xFF, 0xBC, 0x30, 0x8E, 0x00, 0x05, 0xFB, 0xF0, 0xFF, 0xD9, 0x5B, 0xC8,
0xFF, 0xD0, 0x9A, 0xBE, 0x00, 0x00, 0x10, 0xA9, 0xFF, 0xF4, 0x1E, 0xB2, 0x00, 0xCE, 0xBB, 0xF7,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x02, 0x00, 0x02, 0x02, 0x00, 0x00, 0x0C,
0xFF, 0xC2, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0xCF, 0x80, 0x00, 0x40, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x14,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x03, 0x3F, 0x68, 0xB6, 0x79, 0x35, 0x28, 0xBC, 0xC6, 0x7E, 0xD1, 0x6C,
0x80, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0xB2, 0x6A, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0xF0, 0x00, 0x00, 0x00, 0x30,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x25, 0x4D, 0x00, 0x2F, 0x70, 0x6D, 0x00, 0x00, 0x05, 0xAE, 0x00, 0x0C, 0x02, 0xD0,
// bank 2, 256 bytes
0x00, 0x00, 0x00, 0x00, 0x00, 0x65, 0x00, 0x54, 0xFF, 0xEF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x01, 0x00, 0x00, 0x44, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x00, 0x54, 0x00, 0x00, 0xFF, 0xEF, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,
0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// bank 3, 256 bytes
0xD8, 0xDC, 0xBA, 0xA2, 0xF1, 0xDE, 0xB2, 0xB8, 0xB4, 0xA8, 0x81, 0x91, 0xF7, 0x4A, 0x90, 0x7F,
0x91, 0x6A, 0xF3, 0xF9, 0xDB, 0xA8, 0xF9, 0xB0, 0xBA, 0xA0, 0x80, 0xF2, 0xCE, 0x81, 0xF3, 0xC2,
0xF1, 0xC1, 0xF2, 0xC3, 0xF3, 0xCC, 0xA2, 0xB2, 0x80, 0xF1, 0xC6, 0xD8, 0x80, 0xBA, 0xA7, 0xDF,
0xDF, 0xDF, 0xF2, 0xA7, 0xC3, 0xCB, 0xC5, 0xB6, 0xF0, 0x87, 0xA2, 0x94, 0x24, 0x48, 0x70, 0x3C,
0x95, 0x40, 0x68, 0x34, 0x58, 0x9B, 0x78, 0xA2, 0xF1, 0x83, 0x92, 0x2D, 0x55, 0x7D, 0xD8, 0xB1,
0xB4, 0xB8, 0xA1, 0xD0, 0x91, 0x80, 0xF2, 0x70, 0xF3, 0x70, 0xF2, 0x7C, 0x80, 0xA8, 0xF1, 0x01,
0xB0, 0x98, 0x87, 0xD9, 0x43, 0xD8, 0x86, 0xC9, 0x88, 0xBA, 0xA1, 0xF2, 0x0E, 0xB8, 0x97, 0x80,
0xF1, 0xA9, 0xDF, 0xDF, 0xDF, 0xAA, 0xDF, 0xDF, 0xDF, 0xF2, 0xAA, 0xC5, 0xCD, 0xC7, 0xA9, 0x0C,
0xC9, 0x2C, 0x97, 0x97, 0x97, 0x97, 0xF1, 0xA9, 0x89, 0x26, 0x46, 0x66, 0xB0, 0xB4, 0xBA, 0x80,
0xAC, 0xDE, 0xF2, 0xCA, 0xF1, 0xB2, 0x8C, 0x02, 0xA9, 0xB6, 0x98, 0x00, 0x89, 0x0E, 0x16, 0x1E,
0xB8, 0xA9, 0xB4, 0x99, 0x2C, 0x54, 0x7C, 0xB0, 0x8A, 0xA8, 0x96, 0x36, 0x56, 0x76, 0xF1, 0xB9,
0xAF, 0xB4, 0xB0, 0x83, 0xC0, 0xB8, 0xA8, 0x97, 0x11, 0xB1, 0x8F, 0x98, 0xB9, 0xAF, 0xF0, 0x24,
0x08, 0x44, 0x10, 0x64, 0x18, 0xF1, 0xA3, 0x29, 0x55, 0x7D, 0xAF, 0x83, 0xB5, 0x93, 0xAF, 0xF0,
0x00, 0x28, 0x50, 0xF1, 0xA3, 0x86, 0x9F, 0x61, 0xA6, 0xDA, 0xDE, 0xDF, 0xD9, 0xFA, 0xA3, 0x86,
0x96, 0xDB, 0x31, 0xA6, 0xD9, 0xF8, 0xDF, 0xBA, 0xA6, 0x8F, 0xC2, 0xC5, 0xC7, 0xB2, 0x8C, 0xC1,
0xB8, 0xA2, 0xDF, 0xDF, 0xDF, 0xA3, 0xDF, 0xDF, 0xDF, 0xD8, 0xD8, 0xF1, 0xB8, 0xA8, 0xB2, 0x86,
// bank 4, 256 bytes
0xB4, 0x98, 0x0D, 0x35, 0x5D, 0xB8, 0xAA, 0x98, 0xB0, 0x87, 0x2D, 0x35, 0x3D, 0xB2, 0xB6, 0xBA,
0xAF, 0x8C, 0x96, 0x19, 0x8F, 0x9F, 0xA7, 0x0E, 0x16, 0x1E, 0xB4, 0x9A, 0xB8, 0xAA, 0x87, 0x2C,
0x54, 0x7C, 0xB9, 0xA3, 0xDE, 0xDF, 0xDF, 0xA3, 0xB1, 0x80, 0xF2, 0xC4, 0xCD, 0xC9, 0xF1, 0xB8,
0xA9, 0xB4, 0x99, 0x83, 0x0D, 0x35, 0x5D, 0x89, 0xB9, 0xA3, 0x2D, 0x55, 0x7D, 0xB5, 0x93, 0xA3,
0x0E, 0x16, 0x1E, 0xA9, 0x2C, 0x54, 0x7C, 0xB8, 0xB4, 0xB0, 0xF1, 0x97, 0x83, 0xA8, 0x11, 0x84,
0xA5, 0x09, 0x98, 0xA3, 0x83, 0xF0, 0xDA, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0xD8, 0xF1, 0xA5,
0x29, 0x55, 0x7D, 0xA5, 0x85, 0x95, 0x02, 0x1A, 0x2E, 0x3A, 0x56, 0x5A, 0x40, 0x48, 0xF9, 0xF3,
0xA3, 0xD9, 0xF8, 0xF0, 0x98, 0x83, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0x97, 0x82, 0xA8, 0xF1,
0x11, 0xF0, 0x98, 0xA2, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0xDA, 0xF3, 0xDE, 0xD8, 0x83, 0xA5,
0x94, 0x01, 0xD9, 0xA3, 0x02, 0xF1, 0xA2, 0xC3, 0xC5, 0xC7, 0xD8, 0xF1, 0x84, 0x92, 0xA2, 0x4D,
0xDA, 0x2A, 0xD8, 0x48, 0x69, 0xD9, 0x2A, 0xD8, 0x68, 0x55, 0xDA, 0x32, 0xD8, 0x50, 0x71, 0xD9,
0x32, 0xD8, 0x70, 0x5D, 0xDA, 0x3A, 0xD8, 0x58, 0x79, 0xD9, 0x3A, 0xD8, 0x78, 0x93, 0xA3, 0x4D,
0xDA, 0x2A, 0xD8, 0x48, 0x69, 0xD9, 0x2A, 0xD8, 0x68, 0x55, 0xDA, 0x32, 0xD8, 0x50, 0x71, 0xD9,
0x32, 0xD8, 0x70, 0x5D, 0xDA, 0x3A, 0xD8, 0x58, 0x79, 0xD9, 0x3A, 0xD8, 0x78, 0xA8, 0x8A, 0x9A,
0xF0, 0x28, 0x50, 0x78, 0x9E, 0xF3, 0x88, 0x18, 0xF1, 0x9F, 0x1D, 0x98, 0xA8, 0xD9, 0x08, 0xD8,
0xC8, 0x9F, 0x12, 0x9E, 0xF3, 0x15, 0xA8, 0xDA, 0x12, 0x10, 0xD8, 0xF1, 0xAF, 0xC8, 0x97, 0x87,
// bank 5, 256 bytes
0x34, 0xB5, 0xB9, 0x94, 0xA4, 0x21, 0xF3, 0xD9, 0x22, 0xD8, 0xF2, 0x2D, 0xF3, 0xD9, 0x2A, 0xD8,
0xF2, 0x35, 0xF3, 0xD9, 0x32, 0xD8, 0x81, 0xA4, 0x60, 0x60, 0x61, 0xD9, 0x61, 0xD8, 0x6C, 0x68,
0x69, 0xD9, 0x69, 0xD8, 0x74, 0x70, 0x71, 0xD9, 0x71, 0xD8, 0xB1, 0xA3, 0x84, 0x19, 0x3D, 0x5D,
0xA3, 0x83, 0x1A, 0x3E, 0x5E, 0x93, 0x10, 0x30, 0x81, 0x10, 0x11, 0xB8, 0xB0, 0xAF, 0x8F, 0x94,
0xF2, 0xDA, 0x3E, 0xD8, 0xB4, 0x9A, 0xA8, 0x87, 0x29, 0xDA, 0xF8, 0xD8, 0x87, 0x9A, 0x35, 0xDA,
0xF8, 0xD8, 0x87, 0x9A, 0x3D, 0xDA, 0xF8, 0xD8, 0xB1, 0xB9, 0xA4, 0x98, 0x85, 0x02, 0x2E, 0x56,
0xA5, 0x81, 0x00, 0x0C, 0x14, 0xA3, 0x97, 0xB0, 0x8A, 0xF1, 0x2D, 0xD9, 0x28, 0xD8, 0x4D, 0xD9,
0x48, 0xD8, 0x6D, 0xD9, 0x68, 0xD8, 0xB1, 0x84, 0x0D, 0xDA, 0x0E, 0xD8, 0xA3, 0x29, 0x83, 0xDA,
0x2C, 0x0E, 0xD8, 0xA3, 0x84, 0x49, 0x83, 0xDA, 0x2C, 0x4C, 0x0E, 0xD8, 0xB8, 0xB0, 0xA8, 0x8A,
0x9A, 0xF5, 0x20, 0xAA, 0xDA, 0xDF, 0xD8, 0xA8, 0x40, 0xAA, 0xD0, 0xDA, 0xDE, 0xD8, 0xA8, 0x60,
0xAA, 0xDA, 0xD0, 0xDF, 0xD8, 0xF1, 0x97, 0x86, 0xA8, 0x31, 0x9B, 0x06, 0x99, 0x07, 0xAB, 0x97,
0x28, 0x88, 0x9B, 0xF0, 0x0C, 0x20, 0x14, 0x40, 0xB8, 0xB0, 0xB4, 0xA8, 0x8C, 0x9C, 0xF0, 0x04,
0x28, 0x51, 0x79, 0x1D, 0x30, 0x14, 0x38, 0xB2, 0x82, 0xAB, 0xD0, 0x98, 0x2C, 0x50, 0x50, 0x78,
0x78, 0x9B, 0xF1, 0x1A, 0xB0, 0xF0, 0x8A, 0x9C, 0xA8, 0x29, 0x51, 0x79, 0x8B, 0x29, 0x51, 0x79,
0x8A, 0x24, 0x70, 0x59, 0x8B, 0x20, 0x58, 0x71, 0x8A, 0x44, 0x69, 0x38, 0x8B, 0x39, 0x40, 0x68,
0x8A, 0x64, 0x48, 0x31, 0x8B, 0x30, 0x49, 0x60, 0xA5, 0x88, 0x20, 0x09, 0x71, 0x58, 0x44, 0x68,
// bank 6, 256 bytes
0x11, 0x39, 0x64, 0x49, 0x30, 0x19, 0xF1, 0xAC, 0x00, 0x2C, 0x54, 0x7C, 0xF0, 0x8C, 0xA8, 0x04,
0x28, 0x50, 0x78, 0xF1, 0x88, 0x97, 0x26, 0xA8, 0x59, 0x98, 0xAC, 0x8C, 0x02, 0x26, 0x46, 0x66,
0xF0, 0x89, 0x9C, 0xA8, 0x29, 0x51, 0x79, 0x24, 0x70, 0x59, 0x44, 0x69, 0x38, 0x64, 0x48, 0x31,
0xA9, 0x88, 0x09, 0x20, 0x59, 0x70, 0xAB, 0x11, 0x38, 0x40, 0x69, 0xA8, 0x19, 0x31, 0x48, 0x60,
0x8C, 0xA8, 0x3C, 0x41, 0x5C, 0x20, 0x7C, 0x00, 0xF1, 0x87, 0x98, 0x19, 0x86, 0xA8, 0x6E, 0x76,
0x7E, 0xA9, 0x99, 0x88, 0x2D, 0x55, 0x7D, 0x9E, 0xB9, 0xA3, 0x8A, 0x22, 0x8A, 0x6E, 0x8A, 0x56,
0x8A, 0x5E, 0x9F, 0xB1, 0x83, 0x06, 0x26, 0x46, 0x66, 0x0E, 0x2E, 0x4E, 0x6E, 0x9D, 0xB8, 0xAD,
0x00, 0x2C, 0x54, 0x7C, 0xF2, 0xB1, 0x8C, 0xB4, 0x99, 0xB9, 0xA3, 0x2D, 0x55, 0x7D, 0x81, 0x91,
0xAC, 0x38, 0xAD, 0x3A, 0xB5, 0x83, 0x91, 0xAC, 0x2D, 0xD9, 0x28, 0xD8, 0x4D, 0xD9, 0x48, 0xD8,
0x6D, 0xD9, 0x68, 0xD8, 0x8C, 0x9D, 0xAE, 0x29, 0xD9, 0x04, 0xAE, 0xD8, 0x51, 0xD9, 0x04, 0xAE,
0xD8, 0x79, 0xD9, 0x04, 0xD8, 0x81, 0xF3, 0x9D, 0xAD, 0x00, 0x8D, 0xAE, 0x19, 0x81, 0xAD, 0xD9,
0x01, 0xD8, 0xF2, 0xAE, 0xDA, 0x26, 0xD8, 0x8E, 0x91, 0x29, 0x83, 0xA7, 0xD9, 0xAD, 0xAD, 0xAD,
0xAD, 0xF3, 0x2A, 0xD8, 0xD8, 0xF1, 0xB0, 0xAC, 0x89, 0x91, 0x3E, 0x5E, 0x76, 0xF3, 0xAC, 0x2E,
0x2E, 0xF1, 0xB1, 0x8C, 0x5A, 0x9C, 0xAC, 0x2C, 0x28, 0x28, 0x28, 0x9C, 0xAC, 0x30, 0x18, 0xA8,
0x98, 0x81, 0x28, 0x34, 0x3C, 0x97, 0x24, 0xA7, 0x28, 0x34, 0x3C, 0x9C, 0x24, 0xF2, 0xB0, 0x89,
0xAC, 0x91, 0x2C, 0x4C, 0x6C, 0x8A, 0x9B, 0x2D, 0xD9, 0xD8, 0xD8, 0x51, 0xD9, 0xD8, 0xD8, 0x79,
// bank 7, 138 bytes (remainder)
0xD9, 0xD8, 0xD8, 0xF1, 0x9E, 0x88, 0xA3, 0x31, 0xDA, 0xD8, 0xD8, 0x91, 0x2D, 0xD9, 0x28, 0xD8,
0x4D, 0xD9, 0x48, 0xD8, 0x6D, 0xD9, 0x68, 0xD8, 0xB1, 0x83, 0x93, 0x35, 0x3D, 0x80, 0x25, 0xDA,
0xD8, 0xD8, 0x85, 0x69, 0xDA, 0xD8, 0xD8, 0xB4, 0x93, 0x81, 0xA3, 0x28, 0x34, 0x3C, 0xF3, 0xAB,
0x8B, 0xF8, 0xA3, 0x91, 0xB6, 0x09, 0xB4, 0xD9, 0xAB, 0xDE, 0xFA, 0xB0, 0x87, 0x9C, 0xB9, 0xA3,
0xDD, 0xF1, 0xA3, 0xA3, 0xA3, 0xA3, 0x95, 0xF1, 0xA3, 0xA3, 0xA3, 0x9D, 0xF1, 0xA3, 0xA3, 0xA3,
0xA3, 0xF2, 0xA3, 0xB4, 0x90, 0x80, 0xF2, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3,
0xA3, 0xB2, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xB0, 0x87, 0xB5, 0x99, 0xF1, 0xA3, 0xA3, 0xA3,
0x98, 0xF1, 0xA3, 0xA3, 0xA3, 0xA3, 0x97, 0xA3, 0xA3, 0xA3, 0xA3, 0xF3, 0x9B, 0xA3, 0xA3, 0xDC,
0xB9, 0xA7, 0xF1, 0x26, 0x26, 0x26, 0xD8, 0xD8, 0xFF
};
// thanks to Noah Zerkin for piecing this stuff together!
const unsigned char dmpConfig[MPU6050_DMP_CONFIG_SIZE] PROGMEM = {
// BANK OFFSET LENGTH [DATA]
0x03, 0x7B, 0x03, 0x4C, 0xCD, 0x6C, // FCFG_1 inv_set_gyro_calibration
0x03, 0xAB, 0x03, 0x36, 0x56, 0x76, // FCFG_3 inv_set_gyro_calibration
0x00, 0x68, 0x04, 0x02, 0xCB, 0x47, 0xA2, // D_0_104 inv_set_gyro_calibration
0x02, 0x18, 0x04, 0x00, 0x05, 0x8B, 0xC1, // D_0_24 inv_set_gyro_calibration
0x01, 0x0C, 0x04, 0x00, 0x00, 0x00, 0x00, // D_1_152 inv_set_accel_calibration
0x03, 0x7F, 0x06, 0x0C, 0xC9, 0x2C, 0x97, 0x97, 0x97, // FCFG_2 inv_set_accel_calibration
0x03, 0x89, 0x03, 0x26, 0x46, 0x66, // FCFG_7 inv_set_accel_calibration
0x00, 0x6C, 0x02, 0x20, 0x00, // D_0_108 inv_set_accel_calibration
0x02, 0x40, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_00 inv_set_compass_calibration
0x02, 0x44, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_01
0x02, 0x48, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_02
0x02, 0x4C, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_10
0x02, 0x50, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_11
0x02, 0x54, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_12
0x02, 0x58, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_20
0x02, 0x5C, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_21
0x02, 0xBC, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_22
0x01, 0xEC, 0x04, 0x00, 0x00, 0x40, 0x00, // D_1_236 inv_apply_endian_accel
0x03, 0x7F, 0x06, 0x0C, 0xC9, 0x2C, 0x97, 0x97, 0x97, // FCFG_2 inv_set_mpu_sensors
0x04, 0x02, 0x03, 0x0D, 0x35, 0x5D, // CFG_MOTION_BIAS inv_turn_on_bias_from_no_motion
0x04, 0x09, 0x04, 0x87, 0x2D, 0x35, 0x3D, // FCFG_5 inv_set_bias_update
0x00, 0xA3, 0x01, 0x00, // D_0_163 inv_set_dead_zone
// SPECIAL 0x01 = enable interrupts
0x00, 0x00, 0x00, 0x01, // SET INT_ENABLE at i=22, SPECIAL INSTRUCTION
0x07, 0x86, 0x01, 0xFE, // CFG_6 inv_set_fifo_interupt
0x07, 0x41, 0x05, 0xF1, 0x20, 0x28, 0x30, 0x38, // CFG_8 inv_send_quaternion
0x07, 0x7E, 0x01, 0x30, // CFG_16 inv_set_footer
0x07, 0x46, 0x01, 0x9A, // CFG_GYRO_SOURCE inv_send_gyro
0x07, 0x47, 0x04, 0xF1, 0x28, 0x30, 0x38, // CFG_9 inv_send_gyro -> inv_construct3_fifo
0x07, 0x6C, 0x04, 0xF1, 0x28, 0x30, 0x38, // CFG_12 inv_send_accel -> inv_construct3_fifo
0x02, 0x16, 0x02, 0x00, 0x09 // D_0_22 inv_set_fifo_rate
// This very last 0x01 WAS a 0x09, which drops the FIFO rate down to 20 Hz. 0x07 is 25 Hz,
// 0x01 is 100Hz. Going faster than 100Hz (0x00=200Hz) tends to result in very noisy data.
// DMP output frequency is calculated easily using this equation: (200Hz / (1 + value))
// It is important to make sure the host processor can keep up with reading and processing
// the FIFO output at the desired rate. Handling FIFO overflow cleanly is also a good idea.
};
const unsigned char dmpUpdates[MPU6050_DMP_UPDATES_SIZE] PROGMEM = {
0x01, 0xB2, 0x02, 0xFF, 0xFF,
0x01, 0x90, 0x04, 0x09, 0x23, 0xA1, 0x35,
0x01, 0x6A, 0x02, 0x06, 0x00,
0x01, 0x60, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x60, 0x04, 0x40, 0x00, 0x00, 0x00,
0x01, 0x62, 0x02, 0x00, 0x00,
0x00, 0x60, 0x04, 0x00, 0x40, 0x00, 0x00
};
uint8_t MPU6050::dmpInitialize() {
// reset device
DEBUG_PRINTLN(F("\n\nResetting MPU6050..."));
reset();
delay(30); // wait after reset
// enable sleep mode and wake cycle
/*Serial.println(F("Enabling sleep mode..."));
setSleepEnabled(true);
Serial.println(F("Enabling wake cycle..."));
setWakeCycleEnabled(true);*/
// disable sleep mode
DEBUG_PRINTLN(F("Disabling sleep mode..."));
setSleepEnabled(false);
// get MPU hardware revision
DEBUG_PRINTLN(F("Selecting user bank 16..."));
setMemoryBank(0x10, true, true);
DEBUG_PRINTLN(F("Selecting memory byte 6..."));
setMemoryStartAddress(0x06);
DEBUG_PRINTLN(F("Checking hardware revision..."));
uint8_t hwRevision = readMemoryByte();
DEBUG_PRINT(F("Revision @ user[16][6] = "));
DEBUG_PRINTLNF(hwRevision, HEX);
DEBUG_PRINTLN(F("Resetting memory bank selection to 0..."));
setMemoryBank(0, false, false);
// check OTP bank valid
DEBUG_PRINTLN(F("Reading OTP bank valid flag..."));
uint8_t otpValid = getOTPBankValid();
DEBUG_PRINT(F("OTP bank is "));
DEBUG_PRINTLN(otpValid ? F("valid!") : F("invalid!"));
// get X/Y/Z gyro offsets
DEBUG_PRINTLN(F("Reading gyro offset TC values..."));
int8_t xgOffsetTC = getXGyroOffsetTC();
int8_t ygOffsetTC = getYGyroOffsetTC();
int8_t zgOffsetTC = getZGyroOffsetTC();
DEBUG_PRINT(F("X gyro offset = "));
DEBUG_PRINTLN(xgOffset);
DEBUG_PRINT(F("Y gyro offset = "));
DEBUG_PRINTLN(ygOffset);
DEBUG_PRINT(F("Z gyro offset = "));
DEBUG_PRINTLN(zgOffset);
// setup weird slave stuff (?)
DEBUG_PRINTLN(F("Setting slave 0 address to 0x7F..."));
setSlaveAddress(0, 0x7F);
DEBUG_PRINTLN(F("Disabling I2C Master mode..."));
setI2CMasterModeEnabled(false);
DEBUG_PRINTLN(F("Setting slave 0 address to 0x68 (self)..."));
setSlaveAddress(0, 0x68);
DEBUG_PRINTLN(F("Resetting I2C Master control..."));
resetI2CMaster();
delay(20);
// load DMP code into memory banks
DEBUG_PRINT(F("Writing DMP code to MPU memory banks ("));
DEBUG_PRINT(MPU6050_DMP_CODE_SIZE);
DEBUG_PRINTLN(F(" bytes)"));
if (writeProgMemoryBlock(dmpMemory, MPU6050_DMP_CODE_SIZE)) {
DEBUG_PRINTLN(F("Success! DMP code written and verified."));
// write DMP configuration
DEBUG_PRINT(F("Writing DMP configuration to MPU memory banks ("));
DEBUG_PRINT(MPU6050_DMP_CONFIG_SIZE);
DEBUG_PRINTLN(F(" bytes in config def)"));
if (writeProgDMPConfigurationSet(dmpConfig, MPU6050_DMP_CONFIG_SIZE)) {
DEBUG_PRINTLN(F("Success! DMP configuration written and verified."));
DEBUG_PRINTLN(F("Setting clock source to Z Gyro..."));
setClockSource(MPU6050_CLOCK_PLL_ZGYRO);
DEBUG_PRINTLN(F("Setting DMP and FIFO_OFLOW interrupts enabled..."));
setIntEnabled(0x12);
DEBUG_PRINTLN(F("Setting sample rate to 200Hz..."));
setRate(4); // 1khz / (1 + 4) = 200 Hz
DEBUG_PRINTLN(F("Setting external frame sync to TEMP_OUT_L[0]..."));
setExternalFrameSync(MPU6050_EXT_SYNC_TEMP_OUT_L);
DEBUG_PRINTLN(F("Setting DLPF bandwidth to 42Hz..."));
setDLPFMode(MPU6050_DLPF_BW_42);
DEBUG_PRINTLN(F("Setting gyro sensitivity to +/- 2000 deg/sec..."));
setFullScaleGyroRange(MPU6050_GYRO_FS_2000);
DEBUG_PRINTLN(F("Setting DMP configuration bytes (function unknown)..."));
setDMPConfig1(0x03);
setDMPConfig2(0x00);
DEBUG_PRINTLN(F("Clearing OTP Bank flag..."));
setOTPBankValid(false);
DEBUG_PRINTLN(F("Setting X/Y/Z gyro offset TCs to previous values..."));
setXGyroOffsetTC(xgOffsetTC);
setYGyroOffsetTC(ygOffsetTC);
setZGyroOffsetTC(zgOffsetTC);
//DEBUG_PRINTLN(F("Setting X/Y/Z gyro user offsets to zero..."));
//setXGyroOffset(0);
//setYGyroOffset(0);
//setZGyroOffset(0);
DEBUG_PRINTLN(F("Writing final memory update 1/7 (function unknown)..."));
uint8_t dmpUpdate[16], j;
uint16_t pos = 0;
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
DEBUG_PRINTLN(F("Writing final memory update 2/7 (function unknown)..."));
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
DEBUG_PRINTLN(F("Resetting FIFO..."));
resetFIFO();
DEBUG_PRINTLN(F("Reading FIFO count..."));
uint16_t fifoCount = getFIFOCount();
uint8_t fifoBuffer[128];
DEBUG_PRINT(F("Current FIFO count="));
DEBUG_PRINTLN(fifoCount);
getFIFOBytes(fifoBuffer, fifoCount);
DEBUG_PRINTLN(F("Setting motion detection threshold to 2..."));
setMotionDetectionThreshold(2);
DEBUG_PRINTLN(F("Setting zero-motion detection threshold to 156..."));
setZeroMotionDetectionThreshold(156);
DEBUG_PRINTLN(F("Setting motion detection duration to 80..."));
setMotionDetectionDuration(80);
DEBUG_PRINTLN(F("Setting zero-motion detection duration to 0..."));
setZeroMotionDetectionDuration(0);
DEBUG_PRINTLN(F("Resetting FIFO..."));
resetFIFO();
DEBUG_PRINTLN(F("Enabling FIFO..."));
setFIFOEnabled(true);
DEBUG_PRINTLN(F("Enabling DMP..."));
setDMPEnabled(true);
DEBUG_PRINTLN(F("Resetting DMP..."));
resetDMP();
DEBUG_PRINTLN(F("Writing final memory update 3/7 (function unknown)..."));
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
DEBUG_PRINTLN(F("Writing final memory update 4/7 (function unknown)..."));
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
DEBUG_PRINTLN(F("Writing final memory update 5/7 (function unknown)..."));
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
DEBUG_PRINTLN(F("Waiting for FIFO count > 2..."));
while ((fifoCount = getFIFOCount()) < 3);
DEBUG_PRINT(F("Current FIFO count="));
DEBUG_PRINTLN(fifoCount);
DEBUG_PRINTLN(F("Reading FIFO data..."));
getFIFOBytes(fifoBuffer, fifoCount);
DEBUG_PRINTLN(F("Reading interrupt status..."));
uint8_t mpuIntStatus = getIntStatus();
DEBUG_PRINT(F("Current interrupt status="));
DEBUG_PRINTLNF(mpuIntStatus, HEX);
DEBUG_PRINTLN(F("Reading final memory update 6/7 (function unknown)..."));
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
readMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
DEBUG_PRINTLN(F("Waiting for FIFO count > 2..."));
while ((fifoCount = getFIFOCount()) < 3);
DEBUG_PRINT(F("Current FIFO count="));
DEBUG_PRINTLN(fifoCount);
DEBUG_PRINTLN(F("Reading FIFO data..."));
getFIFOBytes(fifoBuffer, fifoCount);
DEBUG_PRINTLN(F("Reading interrupt status..."));
mpuIntStatus = getIntStatus();
DEBUG_PRINT(F("Current interrupt status="));
DEBUG_PRINTLNF(mpuIntStatus, HEX);
DEBUG_PRINTLN(F("Writing final memory update 7/7 (function unknown)..."));
for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);
DEBUG_PRINTLN(F("DMP is good to go! Finally."));
DEBUG_PRINTLN(F("Disabling DMP (you turn it on later)..."));
setDMPEnabled(false);
DEBUG_PRINTLN(F("Setting up internal 42-byte (default) DMP packet buffer..."));
dmpPacketSize = 42;
/*if ((dmpPacketBuffer = (uint8_t *)malloc(42)) == 0) {
return 3; // TODO: proper error code for no memory
}*/
DEBUG_PRINTLN(F("Resetting FIFO and clearing INT status one last time..."));
resetFIFO();
getIntStatus();
} else {
DEBUG_PRINTLN(F("ERROR! DMP configuration verification failed."));
return 2; // configuration block loading failed
}
} else {
DEBUG_PRINTLN(F("ERROR! DMP code verification failed."));
return 1; // main binary block loading failed
}
return 0; // success
}
bool MPU6050::dmpPacketAvailable() {
return getFIFOCount() >= dmpGetFIFOPacketSize();
}
// uint8_t MPU6050::dmpSetFIFORate(uint8_t fifoRate);
// uint8_t MPU6050::dmpGetFIFORate();
// uint8_t MPU6050::dmpGetSampleStepSizeMS();
// uint8_t MPU6050::dmpGetSampleFrequency();
// int32_t MPU6050::dmpDecodeTemperature(int8_t tempReg);
//uint8_t MPU6050::dmpRegisterFIFORateProcess(inv_obj_func func, int16_t priority);
//uint8_t MPU6050::dmpUnregisterFIFORateProcess(inv_obj_func func);
//uint8_t MPU6050::dmpRunFIFORateProcesses();
// uint8_t MPU6050::dmpSendQuaternion(uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendGyro(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendAccel(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendLinearAccel(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendLinearAccelInWorld(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendControlData(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendSensorData(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendExternalSensorData(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendGravity(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendPacketNumber(uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendQuantizedAccel(uint_fast16_t elements, uint_fast16_t accuracy);
// uint8_t MPU6050::dmpSendEIS(uint_fast16_t elements, uint_fast16_t accuracy);
uint8_t MPU6050::dmpGetAccel(int32_t *data, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
data[0] = ((packet[28] << 24) + (packet[29] << 16) + (packet[30] << 8) + packet[31]);
data[1] = ((packet[32] << 24) + (packet[33] << 16) + (packet[34] << 8) + packet[35]);
data[2] = ((packet[36] << 24) + (packet[37] << 16) + (packet[38] << 8) + packet[39]);
return 0;
}
uint8_t MPU6050::dmpGetAccel(int16_t *data, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
data[0] = (packet[28] << 8) + packet[29];
data[1] = (packet[32] << 8) + packet[33];
data[2] = (packet[36] << 8) + packet[37];
return 0;
}
uint8_t MPU6050::dmpGetAccel(VectorInt16 *v, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
v -> x = (packet[28] << 8) + packet[29];
v -> y = (packet[32] << 8) + packet[33];
v -> z = (packet[36] << 8) + packet[37];
return 0;
}
uint8_t MPU6050::dmpGetQuaternion(int32_t *data, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
data[0] = ((packet[0] << 24) + (packet[1] << 16) + (packet[2] << 8) + packet[3]);
data[1] = ((packet[4] << 24) + (packet[5] << 16) + (packet[6] << 8) + packet[7]);
data[2] = ((packet[8] << 24) + (packet[9] << 16) + (packet[10] << 8) + packet[11]);
data[3] = ((packet[12] << 24) + (packet[13] << 16) + (packet[14] << 8) + packet[15]);
return 0;
}
uint8_t MPU6050::dmpGetQuaternion(int16_t *data, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
data[0] = ((packet[0] << 8) + packet[1]);
data[1] = ((packet[4] << 8) + packet[5]);
data[2] = ((packet[8] << 8) + packet[9]);
data[3] = ((packet[12] << 8) + packet[13]);
return 0;
}
uint8_t MPU6050::dmpGetQuaternion(Quaternion *q, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
int16_t qI[4];
uint8_t status = dmpGetQuaternion(qI, packet);
if (status == 0) {
q -> w = (float)qI[0] / 16384.0f;
q -> x = (float)qI[1] / 16384.0f;
q -> y = (float)qI[2] / 16384.0f;
q -> z = (float)qI[3] / 16384.0f;
return 0;
}
return status; // int16 return value, indicates error if this line is reached
}
// uint8_t MPU6050::dmpGet6AxisQuaternion(long *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetRelativeQuaternion(long *data, const uint8_t* packet);
uint8_t MPU6050::dmpGetGyro(int32_t *data, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
data[0] = ((packet[16] << 24) + (packet[17] << 16) + (packet[18] << 8) + packet[19]);
data[1] = ((packet[20] << 24) + (packet[21] << 16) + (packet[22] << 8) + packet[23]);
data[2] = ((packet[24] << 24) + (packet[25] << 16) + (packet[26] << 8) + packet[27]);
return 0;
}
uint8_t MPU6050::dmpGetGyro(int16_t *data, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
data[0] = (packet[16] << 8) + packet[17];
data[1] = (packet[20] << 8) + packet[21];
data[2] = (packet[24] << 8) + packet[25];
return 0;
}
uint8_t MPU6050::dmpGetGyro(VectorInt16 *v, const uint8_t* packet) {
// TODO: accommodate different arrangements of sent data (ONLY default supported now)
if (packet == 0) packet = dmpPacketBuffer;
v -> x = (packet[16] << 8) + packet[17];
v -> y = (packet[20] << 8) + packet[21];
v -> z = (packet[24] << 8) + packet[25];
return 0;
}
// uint8_t MPU6050::dmpSetLinearAccelFilterCoefficient(float coef);
// uint8_t MPU6050::dmpGetLinearAccel(long *data, const uint8_t* packet);
uint8_t MPU6050::dmpGetLinearAccel(VectorInt16 *v, VectorInt16 *vRaw, VectorFloat *gravity) {
// get rid of the gravity component (+1g = +8192 in standard DMP FIFO packet, sensitivity is 2g)
v -> x = vRaw -> x - gravity -> x*8192;
v -> y = vRaw -> y - gravity -> y*8192;
v -> z = vRaw -> z - gravity -> z*8192;
return 0;
}
// uint8_t MPU6050::dmpGetLinearAccelInWorld(long *data, const uint8_t* packet);
uint8_t MPU6050::dmpGetLinearAccelInWorld(VectorInt16 *v, VectorInt16 *vReal, Quaternion *q) {
// rotate measured 3D acceleration vector into original state
// frame of reference based on orientation quaternion
memcpy(v, vReal, sizeof(VectorInt16));
v -> rotate(q);
return 0;
}
// uint8_t MPU6050::dmpGetGyroAndAccelSensor(long *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetGyroSensor(long *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetControlData(long *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetTemperature(long *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetGravity(long *data, const uint8_t* packet);
uint8_t MPU6050::dmpGetGravity(VectorFloat *v, Quaternion *q) {
v -> x = 2 * (q -> x*q -> z - q -> w*q -> y);
v -> y = 2 * (q -> w*q -> x + q -> y*q -> z);
v -> z = q -> w*q -> w - q -> x*q -> x - q -> y*q -> y + q -> z*q -> z;
return 0;
}
// uint8_t MPU6050::dmpGetUnquantizedAccel(long *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetQuantizedAccel(long *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetExternalSensorData(long *data, int size, const uint8_t* packet);
// uint8_t MPU6050::dmpGetEIS(long *data, const uint8_t* packet);
uint8_t MPU6050::dmpGetEuler(float *data, Quaternion *q) {
data[0] = atan2(2*q -> x*q -> y - 2*q -> w*q -> z, 2*q -> w*q -> w + 2*q -> x*q -> x - 1); // psi
data[1] = -asin(2*q -> x*q -> z + 2*q -> w*q -> y); // theta
data[2] = atan2(2*q -> y*q -> z - 2*q -> w*q -> x, 2*q -> w*q -> w + 2*q -> z*q -> z - 1); // phi
return 0;
}
uint8_t MPU6050::dmpGetYawPitchRoll(float *data, Quaternion *q, VectorFloat *gravity) {
// yaw: (about Z axis)
data[0] = atan2(2*q -> x*q -> y - 2*q -> w*q -> z, 2*q -> w*q -> w + 2*q -> x*q -> x - 1);
// pitch: (nose up/down, about Y axis)
data[1] = atan(gravity -> x / sqrt(gravity -> y*gravity -> y + gravity -> z*gravity -> z));
// roll: (tilt left/right, about X axis)
data[2] = atan(gravity -> y / sqrt(gravity -> x*gravity -> x + gravity -> z*gravity -> z));
return 0;
}
// uint8_t MPU6050::dmpGetAccelFloat(float *data, const uint8_t* packet);
// uint8_t MPU6050::dmpGetQuaternionFloat(float *data, const uint8_t* packet);
uint8_t MPU6050::dmpProcessFIFOPacket(const unsigned char *dmpData) {
/*for (uint8_t k = 0; k < dmpPacketSize; k++) {
if (dmpData[k] < 0x10) Serial.print("0");
Serial.print(dmpData[k], HEX);
Serial.print(" ");
}
Serial.print("\n");*/
//Serial.println((uint16_t)dmpPacketBuffer);
return 0;
}
uint8_t MPU6050::dmpReadAndProcessFIFOPacket(uint8_t numPackets, uint8_t *processed) {
uint8_t status;
uint8_t buf[dmpPacketSize];
for (uint8_t i = 0; i < numPackets; i++) {
// read packet from FIFO
getFIFOBytes(buf, dmpPacketSize);
// process packet
if ((status = dmpProcessFIFOPacket(buf)) > 0) return status;
// increment external process count variable, if supplied
if (processed != 0) *processed++;
}
return 0;
}
// uint8_t MPU6050::dmpSetFIFOProcessedCallback(void (*func) (void));
// uint8_t MPU6050::dmpInitFIFOParam();
// uint8_t MPU6050::dmpCloseFIFO();
// uint8_t MPU6050::dmpSetGyroDataSource(uint_fast8_t source);
// uint8_t MPU6050::dmpDecodeQuantizedAccel();
// uint32_t MPU6050::dmpGetGyroSumOfSquare();
// uint32_t MPU6050::dmpGetAccelSumOfSquare();
// void MPU6050::dmpOverrideQuaternion(long *q);
uint16_t MPU6050::dmpGetFIFOPacketSize() {
return dmpPacketSize;
}
#endif /* _MPU6050_6AXIS_MOTIONAPPS20_H_ */
| 41,027 | C | 53.704 | 114 | 0.617106 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/cassie_description-UMich-BipedLab/README.md | # cassie_description
This repository contains the .urdf model of the CASSIE robot from Agility Robotics.
It also includes a a way to visualize the robot using ROS and rviz.
Installation to view .urdf using rviz
=====================================
- Download and install ROS by following the instructions at http://wiki.ros.org/indigo/Installation/Ubuntu.
- Create a folder for the catkin workspace
```
mkdir ~/catkin_ws
cd ~/catkin_ws
mkdir src
cd src
catkin_init_workspace
```
- Clone the repository to get the cassie_description package
```
git clone https://github.com/UMich-BipedLab/cassie_description.git
```
- Build the package
```
cd ../
catkin_make
source devel/setup.bash
```
- Launch rviz to visualize the .urdf file
```
roslaunch cassie_description display.launch
```
| 790 | Markdown | 22.264705 | 107 | 0.720253 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/cassie_description-UMich-BipedLab/config/dependent_joints.yaml | dependent_joints:
knee_to_shin_left: {parent: knee_joint_left, factor: -1 }
ankle_joint_left: {parent: knee_joint_left, factor: 0 }
knee_to_shin_right: {parent: knee_joint_right, factor: 0 }
ankle_joint_right: {parent: knee_joint_right, factor: -1 }
zeros:
knee_to_shin_left: 0
ankle_joint_left: 0.226893
knee_to_shin_right: 0
ankle_joint_right: 0.226893
| 374 | YAML | 30.249997 | 60 | 0.68984 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/calibrate_servos.py | from pupper.HardwareInterface import HardwareInterface
from pupper.Config import PWMParams, ServoParams
import numpy as np
import re
def get_motor_name(i, j):
motor_type = {0: "abduction", 1: "inner", 2: "outer"} # Top # Bottom
leg_pos = {0: "front-right", 1: "front-left", 2: "back-right", 3: "back-left"}
final_name = motor_type[i] + " " + leg_pos[j]
return final_name
def get_motor_setpoint(i, j):
data = np.array([[0, 0, 0, 0], [45, 45, 45, 45], [45, 45, 45, 45]])
return data[i, j]
def degrees_to_radians(input_array):
"""Converts degrees to radians.
Parameters
----------
input_array : Numpy array or float
Degrees
Returns
-------
Numpy array or float
Radians
"""
return input_array * np.pi / 180.0
def radians_to_degrees(input_array):
"""Converts degrees to radians.
Parameters
----------
input_array : Numpy array or float
Radians
Returns
-------
Numpy array or float
Degrees
"""
return input_array * 180.0 / np.pi
def step_until(hardware_interface, axis, leg, set_point):
"""Returns the angle offset needed to correct a given link by asking the user for input.
Returns
-------
Float
Angle offset needed to correct the link.
"""
found_position = False
set_names = ["horizontal", "horizontal", "vertical"]
offset = 0
while not found_position:
move_input = str(
input("Enter 'a' or 'b' to move the link until it is **" + set_names[axis] + "**. Enter 'd' when done. Input: "
)
)
if move_input == "a":
offset += 1.0
hardware_interface.set_actuator_position(
degrees_to_radians(set_point + offset),
axis,
leg,
)
elif move_input == "b":
offset -= 1.0
hardware_interface.set_actuator_position(
degrees_to_radians(set_point + offset),
axis,
leg,
)
elif move_input == "d":
found_position = True
print("Offset: ", offset)
return offset
def calibrate_angle_offset(hardware_interface):
"""Calibrate the angle offset for the twelve motors on the robot. Note that servo_params is modified in-place.
Parameters
----------
servo_params : ServoParams
Servo parameters. This variable is updated in-place.
pi_board : Pi
RaspberryPi object.
pwm_params : PWMParams
PWMParams object.
"""
# Found K value of (11.4)
print("The scaling constant for your servo represents how much you have to increase\nthe pwm pulse width (in microseconds) to rotate the servo output 1 degree.")
print("This value is currently set to: {:.3f}".format(degrees_to_radians(hardware_interface.servo_params.micros_per_rad)))
print("For newer CLS6336 and CLS6327 servos the value should be 11.333.")
ks = input("Press <Enter> to keep the current value, or enter a new value: ")
if ks != '':
k = float(ks)
hardware_interface.servo_params.micros_per_rad = k * 180 / np.pi
hardware_interface.servo_params.neutral_angle_degrees = np.zeros((3, 4))
for leg_index in range(4):
for axis in range(3):
# Loop until we're satisfied with the calibration
completed = False
while not completed:
motor_name = get_motor_name(axis, leg_index)
print("\n\nCalibrating the **" + motor_name + " motor **")
set_point = get_motor_setpoint(axis, leg_index)
# Zero out the neutral angle
hardware_interface.servo_params.neutral_angle_degrees[axis, leg_index] = 0
# Move servo to set_point angle
hardware_interface.set_actuator_position(
degrees_to_radians(set_point),
axis,
leg_index,
)
# Adjust the angle using keyboard input until it matches the reference angle
offset = step_until(
hardware_interface, axis, leg_index, set_point
)
print("Final offset: ", offset)
# The upper leg link has a different equation because we're calibrating to make it horizontal, not vertical
if axis == 1:
hardware_interface.servo_params.neutral_angle_degrees[axis, leg_index] = set_point - offset
else:
hardware_interface.servo_params.neutral_angle_degrees[axis, leg_index] = -(set_point + offset)
print("Calibrated neutral angle: ", hardware_interface.servo_params.neutral_angle_degrees[axis, leg_index])
# Send the servo command using the new beta value and check that it's ok
hardware_interface.set_actuator_position(
degrees_to_radians([0, 45, -45][axis]),
axis,
leg_index,
)
okay = ""
prompt = "The leg should be at exactly **" + ["horizontal", "45 degrees", "45 degrees"][axis] + "**. Are you satisfied? Enter 'yes' or 'no': "
while okay not in ["y", "n", "yes", "no"]:
okay = str(
input(prompt)
)
completed = okay == "y" or okay == "yes"
def overwrite_ServoCalibration_file(servo_params):
preamble = """# WARNING: This file is machine generated. Edit at your own risk.
import numpy as np
"""
# Format array object string for np.array
p1 = re.compile("([0-9]\.) ( *)") # pattern to replace the space that follows each number with a comma
partially_formatted_matrix = p1.sub(r"\1,\2", str(servo_params.neutral_angle_degrees))
p2 = re.compile("(\]\n)") # pattern to add a comma at the end of the first two lines
formatted_matrix_with_required_commas = p2.sub("],\n", partially_formatted_matrix)
# Overwrite pupper/ServoCalibration.py file with modified values
with open("pupper/ServoCalibration.py", "w") as f:
print(preamble, file = f)
print("MICROS_PER_RAD = {:.3f} * 180.0 / np.pi".format(degrees_to_radians(servo_params.micros_per_rad)), file = f)
print("NEUTRAL_ANGLE_DEGREES = np.array(", file = f)
print(formatted_matrix_with_required_commas, file = f)
print(")", file = f)
def main():
"""Main program
"""
hardware_interface = HardwareInterface()
calibrate_angle_offset(hardware_interface)
overwrite_ServoCalibration_file(hardware_interface.servo_params)
print("\n\n CALIBRATION COMPLETE!\n")
print("Calibrated neutral angles:")
print(hardware_interface.servo_params.neutral_angle_degrees)
main()
| 6,862 | Python | 34.376288 | 165 | 0.581609 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/run_robot.py | import numpy as np
import time
from src.IMU import IMU
from src.Controller import Controller
from src.JoystickInterface import JoystickInterface
from src.State import State
from pupper.HardwareInterface import HardwareInterface
from pupper.Config import Configuration
from pupper.Kinematics import four_legs_inverse_kinematics
def main(use_imu=False):
"""Main program
"""
# Create config
config = Configuration()
hardware_interface = HardwareInterface()
# Create imu handle
if use_imu:
imu = IMU(port="/dev/ttyACM0")
imu.flush_buffer()
# Create controller and user input handles
controller = Controller(
config,
four_legs_inverse_kinematics,
)
state = State()
print("Creating joystick listener...")
joystick_interface = JoystickInterface(config)
print("Done.")
last_loop = time.time()
print("Summary of gait parameters:")
print("overlap time: ", config.overlap_time)
print("swing time: ", config.swing_time)
print("z clearance: ", config.z_clearance)
print("x shift: ", config.x_shift)
# Wait until the activate button has been pressed
while True:
print("Waiting for L1 to activate robot.")
while True:
command = joystick_interface.get_command(state)
joystick_interface.set_color(config.ps4_deactivated_color)
if command.activate_event == 1:
break
time.sleep(0.1)
print("Robot activated.")
joystick_interface.set_color(config.ps4_color)
while True:
now = time.time()
if now - last_loop < config.dt:
continue
last_loop = time.time()
# Parse the udp joystick commands and then update the robot controller's parameters
command = joystick_interface.get_command(state)
if command.activate_event == 1:
print("Deactivating Robot")
break
# Read imu data. Orientation will be None if no data was available
quat_orientation = (
imu.read_orientation() if use_imu else np.array([1, 0, 0, 0])
)
state.quat_orientation = quat_orientation
# Step the controller forward by dt
controller.run(state, command)
# Update the pwm widths going to the servos
hardware_interface.set_actuator_postions(state.joint_angles)
main()
| 2,473 | Python | 29.925 | 95 | 0.627982 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/src/Gaits.py | class GaitController:
def __init__(self, config):
self.config = config
def phase_index(self, ticks):
"""Calculates which part of the gait cycle the robot should be in given the time in ticks.
Parameters
----------
ticks : int
Number of timesteps since the program started
gaitparams : GaitParams
GaitParams object
Returns
-------
Int
The index of the gait phase that the robot should be in.
"""
phase_time = ticks % self.config.phase_length
phase_sum = 0
for i in range(self.config.num_phases):
phase_sum += self.config.phase_ticks[i]
if phase_time < phase_sum:
return i
assert False
def subphase_ticks(self, ticks):
"""Calculates the number of ticks (timesteps) since the start of the current phase.
Parameters
----------
ticks : Int
Number of timesteps since the program started
gaitparams : GaitParams
GaitParams object
Returns
-------
Int
Number of ticks since the start of the current phase.
"""
phase_time = ticks % self.config.phase_length
phase_sum = 0
subphase_ticks = 0
for i in range(self.config.num_phases):
phase_sum += self.config.phase_ticks[i]
if phase_time < phase_sum:
subphase_ticks = phase_time - phase_sum + self.config.phase_ticks[i]
return subphase_ticks
assert False
def contacts(self, ticks):
"""Calculates which feet should be in contact at the given number of ticks
Parameters
----------
ticks : Int
Number of timesteps since the program started.
gaitparams : GaitParams
GaitParams object
Returns
-------
numpy array (4,)
Numpy vector with 0 indicating flight and 1 indicating stance.
"""
return self.config.contact_phases[:, self.phase_index(ticks)]
| 2,154 | Python | 28.930555 | 98 | 0.545032 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/src/Command.py | import numpy as np
class Command:
"""Stores movement command
"""
def __init__(self):
self.horizontal_velocity = np.array([0, 0])
self.yaw_rate = 0.0
self.height = -0.16
self.pitch = 0.0
self.roll = 0.0
self.activation = 0
self.hop_event = False
self.trot_event = False
self.activate_event = False | 392 | Python | 20.833332 | 51 | 0.533163 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/src/SwingLegController.py | import numpy as np
from transforms3d.euler import euler2mat
class SwingController:
def __init__(self, config):
self.config = config
def raibert_touchdown_location(
self, leg_index, command
):
delta_p_2d = (
self.config.alpha
* self.config.stance_ticks
* self.config.dt
* command.horizontal_velocity
)
delta_p = np.array([delta_p_2d[0], delta_p_2d[1], 0])
theta = (
self.config.beta
* self.config.stance_ticks
* self.config.dt
* command.yaw_rate
)
R = euler2mat(0, 0, theta)
return R @ self.config.default_stance[:, leg_index] + delta_p
def swing_height(self, swing_phase, triangular=True):
if triangular:
if swing_phase < 0.5:
swing_height_ = swing_phase / 0.5 * self.config.z_clearance
else:
swing_height_ = self.config.z_clearance * (1 - (swing_phase - 0.5) / 0.5)
return swing_height_
def next_foot_location(
self,
swing_prop,
leg_index,
state,
command,
):
assert swing_prop >= 0 and swing_prop <= 1
foot_location = state.foot_locations[:, leg_index]
swing_height_ = self.swing_height(swing_prop)
touchdown_location = self.raibert_touchdown_location(leg_index, command)
time_left = self.config.dt * self.config.swing_ticks * (1.0 - swing_prop)
v = (touchdown_location - foot_location) / time_left * np.array([1, 1, 0])
delta_foot_location = v * self.config.dt
z_vector = np.array([0, 0, swing_height_ + command.height])
return foot_location * np.array([1, 1, 0]) + z_vector + delta_foot_location
| 1,781 | Python | 32.622641 | 89 | 0.563167 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/src/State.py | import numpy as np
from enum import Enum
class State:
def __init__(self):
self.horizontal_velocity = np.array([0.0, 0.0])
self.yaw_rate = 0.0
self.height = -0.16
self.pitch = 0.0
self.roll = 0.0
self.activation = 0
self.behavior_state = BehaviorState.REST
self.ticks = 0
self.foot_locations = np.zeros((3, 4))
self.joint_angles = np.zeros((3, 4))
self.behavior_state = BehaviorState.REST
class BehaviorState(Enum):
DEACTIVATED = -1
REST = 0
TROT = 1
HOP = 2
FINISHHOP = 3 | 589 | Python | 20.851851 | 55 | 0.568761 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/src/StanceController.py | import numpy as np
from transforms3d.euler import euler2mat
class StanceController:
def __init__(self, config):
self.config = config
def position_delta(self, leg_index, state, command):
"""Calculate the difference between the next desired body location and the current body location
Parameters
----------
z_measured : float
Z coordinate of the feet relative to the body.
stance_params : StanceParams
Stance parameters object.
movement_reference : MovementReference
Movement reference object.
gait_params : GaitParams
Gait parameters object.
Returns
-------
(Numpy array (3), Numpy array (3, 3))
(Position increment, rotation matrix increment)
"""
z = state.foot_locations[2, leg_index]
v_xy = np.array(
[
-command.horizontal_velocity[0],
-command.horizontal_velocity[1],
1.0
/ self.config.z_time_constant
* (state.height - z),
]
)
delta_p = v_xy * self.config.dt
delta_R = euler2mat(0, 0, -command.yaw_rate * self.config.dt)
return (delta_p, delta_R)
# TODO: put current foot location into state
def next_foot_location(self, leg_index, state, command):
foot_location = state.foot_locations[:, leg_index]
(delta_p, delta_R) = self.position_delta(leg_index, state, command)
incremented_location = delta_R @ foot_location + delta_p
return incremented_location
| 1,628 | Python | 32.244897 | 104 | 0.57801 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/src/IMU.py | import serial
import numpy as np
import time
class IMU:
def __init__(self, port, baudrate=500000):
self.serial_handle = serial.Serial(
port=port,
baudrate=baudrate,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=0,
)
self.last_quat = np.array([1, 0, 0, 0])
self.start_time = time.time()
def flush_buffer(self):
self.serial_handle.reset_input_buffer()
def read_orientation(self):
"""Reads quaternion measurements from the Teensy until none are left. Returns the last read quaternion.
Parameters
----------
serial_handle : Serial object
Handle to the pyserial Serial object
Returns
-------
np array (4,)
If there was quaternion data to read on the serial port returns the quaternion as a numpy array, otherwise returns the last read quaternion.
"""
while True:
x = self.serial_handle.readline().decode("utf").strip()
if x is "" or x is None:
return self.last_quat
else:
parsed = x.split(",")
if len(parsed) == 4:
self.last_quat = np.array(parsed, dtype=np.float64)
else:
print("Did not receive 4-vector from imu")
| 1,440 | Python | 30.326086 | 152 | 0.543056 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/src/Tests.py | # using LinearAlgebra
# using Profile
# using StaticArrays
# using Plots
# using BenchmarkTools
# include("Kinematics.jl")
# include("PupperConfig.jl")
# include("Gait.jl")
# include("StanceController.jl")
# include("SwingLegController.jl")
# include("Types.jl")
# include("Controller.jl")
import numpy as np
import matplotlib.pyplot as plt
from Kinematics import leg_explicit_inverse_kinematics
from PupperConfig import *
from Gaits import *
from StanceController import position_delta, stance_foot_location
from SwingLegController import *
from Types import MovementReference, GaitParams, StanceParams, SwingParams
from Controller import *
# function round_(a, dec)
# return map(x -> round(x, digits=dec), a)
# end
# function testInverseKinematicsExplicit!()
# println("\n-------------- Testing Inverse Kinematics -----------")
# config = PupperConfig()
# println("\nTesting Inverse Kinematics")
# function testHelper(r, alpha_true, i; do_assert=true)
# eps = 1e-6
# @time α = leg_explicitinversekinematics_prismatic(r, i, config)
# println("Leg ", i, ": r: ", r, " -> α: ", α)
# if do_assert
# @assert norm(α - alpha_true) < eps
# end
# end
# c = config.LEG_L/sqrt(2)
# offset = config.ABDUCTION_OFFSET
# testHelper(SVector(0, offset, -0.125), SVector(0, 0, 0), 2)
# testHelper(SVector(c, offset, -c), SVector(0, -pi/4, 0), 2)
# testHelper(SVector(-c, offset, -c), SVector(0, pi/4, 0), 2)
# testHelper(SVector(0, c, -c), missing, 2, do_assert=false)
# testHelper(SVector(-c, -offset, -c), [0, pi/4, 0], 1)
# testHelper(SVector(config.LEG_L * sqrt(3)/2, offset, -config.LEG_L / 2), SVector(0, -pi/3, 0), 2)
# end
def test_inverse_kinematics_linkage():
print("\n-------------- Testing Five-bar Linkage Inverse Kinematics -----------")
config = PupperConfig()
print("\nTesting Inverse Kinematics")
def testHelper(r, alpha_true, i, do_assert=True):
eps = 1e-6
alpha = leg_explicit_inverse_kinematics(r, i, config)
print("Leg ", i, ": r: ", r, " -> α: ", alpha)
if do_assert:
assert np.linalg.norm(alpha - alpha_true) < eps
c = config.LEG_L / (2 ** 0.5)
offset = config.ABDUCTION_OFFSET
testHelper(np.array([0, offset, -0.125]), None, 1, do_assert=False)
testHelper(np.array([c, offset, -c]), None, 1, do_assert=False)
testHelper(np.array([-c, offset, -c]), None, 1, do_assert=False)
testHelper(np.array([0, c, -c]), None, 1, do_assert=False)
testHelper(np.array([-c, -offset, -c]), None, 0, do_assert=False)
testHelper(
np.array([config.LEG_L * (3 ** 0.5) / 2, offset, -config.LEG_L / 2]),
None,
1,
do_assert=False,
)
# function testForwardKinematics!()
# println("\n-------------- Testing Forward Kinematics -----------")
# config = PupperConfig()
# println("\nTesting Forward Kinematics")
# function testHelper(alpha, r_true, i; do_assert=true)
# eps = 1e-6
# r = zeros(3)
# println("Vectors")
# a = [alpha.data...]
# @time legForwardKinematics!(r, a, i, config)
# println("SVectors")
# @time r = legForwardKinematics(alpha, i, config)
# println("Leg ", i, ": α: ", alpha, " -> r: ", r)
# if do_assert
# @assert norm(r_true - r) < eps
# end
# end
# l = config.LEG_L
# offset = config.ABDUCTION_OFFSET
# testHelper(SVector{3}([0.0, 0.0, 0.0]), SVector{3}([0, offset, -l]), 2)
# testHelper(SVector{3}([0.0, pi/4, 0.0]), missing, 2, do_assert=false)
# # testHelper([0.0, 0.0, 0.0], [0, offset, -l], 2)
# # testHelper([0.0, pi/4, 0.0], missing, 2, do_assert=false)
# end
# function testForwardInverseAgreeance()
# println("\n-------------- Testing Forward/Inverse Consistency -----------")
# config = PupperConfig()
# println("\nTest forward/inverse consistency")
# eps = 1e-6
# for i in 1:10
# alpha = SVector(rand()-0.5, rand()-0.5, (rand()-0.5)*0.05)
# leg = rand(1:4)
# @time r = legForwardKinematics(alpha, leg, config)
# # @code_warntype legForwardKinematics!(r, alpha, leg, config)
# @time alpha_prime = leg_explicitinversekinematics_prismatic(r, leg, config)
# # @code_warntype inverseKinematicsExplicit!(alpha_prime, r, leg, config)
# println("Leg ", leg, ": α: ", round_(alpha, 3), " -> r_body_foot: ", round_(r, 3), " -> α': ", round_(alpha_prime, 3))
# @assert norm(alpha_prime - alpha) < eps
# end
# end
# function testAllInverseKinematics()
# println("\n-------------- Testing Four Leg Inverse Kinematics -----------")
# function helper(r_body, alpha_true; do_assert=true)
# println("Timing for fourlegs_inversekinematics")
# config = PupperConfig()
# @time alpha = fourlegs_inversekinematics(SMatrix(r_body), config)
# @code_warntype fourlegs_inversekinematics(SMatrix(r_body), config)
# println("r: ", r_body, " -> α: ", alpha)
# if do_assert
# @assert norm(alpha - alpha_true) < 1e-10
# end
# end
# config = PupperConfig()
# f = config.LEG_FB
# l = config.LEG_LR
# s = -0.125
# o = config.ABDUCTION_OFFSET
# r_body = MMatrix{3,4}(zeros(3,4))
# r_body[:,1] = [f, -l-o, s]
# r_body[:,2] = [f, l+o, s]
# r_body[:,3] = [-f, -l-o, s]
# r_body[:,4] = [-f, l+o, s]
# helper(r_body, zeros(3,4))
# helper(SMatrix{3,4}(zeros(3,4)), missing, do_assert=false)
# end
# function testKinematics()
# testInverseKinematicsExplicit!()
# testForwardKinematics!()
# testForwardInverseAgreeance()
# testAllInverseKinematics()
# end
# function testGait()
# println("\n-------------- Testing Gait -----------")
# p = GaitParams()
# # println("Gait params=",p)
# t = 680
# println("Timing for phaseindex")
# @time ph = phaseindex(t, p)
# # @code_warntype phaseindex(t, p)
# println("t=",t," phase=",ph)
# @assert ph == 4
# @assert phaseindex(0, p) == 1
# println("Timing for contacts")
# @time c = contacts(t, p)
# # @code_warntype contacts(t, p)
# @assert typeof(c) == SArray{Tuple{4},Int64,1,4}
# println("t=", t, " contacts=", c)
# end
def test_stance_controller():
print("\n-------------- Testing Stance Controller -----------")
stanceparams = StanceParams()
gaitparams = GaitParams()
zmeas = -0.20
mvref = MovementReference()
dp, dR = position_delta(zmeas, stanceparams, mvref, gaitparams)
assert np.linalg.norm(dR - np.eye(3)) < 1e-10
assert np.linalg.norm(dp - np.array([0, 0, gaitparams.dt * 0.04])) < 1e-10
zmeas = -0.18
mvref = MovementReference()
mvref.v_xy_ref = np.array([1.0, 0.0])
mvref.z_ref = -0.18
dp, dR = position_delta(zmeas, stanceparams, mvref, gaitparams)
zmeas = -0.20
mvref = MovementReference()
mvref.wz_ref = 1.0
mvref.z_ref = -0.20
dp, dR = position_delta(zmeas, stanceparams, mvref, gaitparams)
assert np.linalg.norm(dp - np.array([0, 0, 0])) < 1e-10
assert np.linalg.norm(dR[0, 1] - (gaitparams.dt)) < 1e-6
stancefootloc = np.zeros(3)
sloc = stance_foot_location(stancefootloc, stanceparams, gaitparams, mvref)
# function typeswinglegcontroller()
# println("\n--------------- Code warn type for raibert_tdlocation[s] ----------")
# swp = SwingParams()
# stp = StanceParams()
# gp = GaitParams()
# mvref = MovementReference(SVector(1.0, 0.0), 0, -0.18)
# raibert_tdlocations(swp, stp, gp, mvref)
# mvref = MovementReference(SVector(1.0, 0.0), 0, -0.18)
# raibert_tdlocation(1, swp, stp, gp, mvref)
# end
# function TestSwingLegController()
# println("\n-------------- Testing Swing Leg Controller -----------")
# swp = SwingParams()
# stp = StanceParams()
# gp = GaitParams()
# p = ControllerParams()
# println("Timing for swingheight:")
# @time z = swingheight(0.5, swp)
# println("z clearance at t=1/2swingtime =>",z)
# @assert abs(z - swp.zclearance) < 1e-10
# println("Timing for swingheight:")
# @time z = swingheight(0, swp)
# println("Z clearance at t=0 =>",z)
# @assert abs(z) < 1e-10
# mvref = MovementReference(SVector(1.0, 0.0), 0, -0.18)
# println("Timing for raibert tdlocation*s*:")
# @time l = raibert_tdlocations(swp, stp, gp, mvref)
# target = stp.defaultstance .+ [gp.stanceticks*gp.dt*0.5*1, 0, 0]
# println("Touchdown locations =>", l, " <?=> ", target)
# @assert norm(l - target) <= 1e-10
# mvref = MovementReference(SVector(1.0, 0.0), 0, -0.18)
# println("Timing for raibert tdlocation:")
# @time l = raibert_tdlocation(1, swp, stp, gp, mvref)
# fcurrent = SMatrix{3, 4, Float64}(stp.defaultstance)
# mvref = MovementReference()
# tswing = 0.125
# println("Timing for swingfootlocation*s* increment")
# @time l = swingfootlocations(tswing, fcurrent, swp, stp, gp, mvref)
# println(l)
# fcurrent = SVector{3, Float64}(0.0, 0.0, 0.0)
# println("Timing for swingfootlocation")
# @time swingfootlocation(tswing, fcurrent, 1, swp, stp, gp, mvref)
# typeswinglegcontroller()
# return nothing
# end
def test_run():
print("Run timing")
foot_loc_history, joint_angle_history = run()
plt.subplot(211)
x = plt.plot(foot_loc_history[0, :, :].T, label="x")
y = plt.plot(foot_loc_history[1, :, :].T, label="y")
z = plt.plot(foot_loc_history[2, :, :].T, label="z")
plt.subplot(212)
alpha = plt.plot(joint_angle_history[0, :, :].T, label="alpha")
beta = plt.plot(joint_angle_history[1, :, :].T, label="beta")
gamma = plt.plot(joint_angle_history[2, :, :].T, label="gamma")
plt.show()
# plot(x, β, y, α, z, γ, layout=(3,2), legend=false))
# function teststep()
# swingparams = SwingParams()
# stanceparams = StanceParams()
# gaitparams = GaitParams()
# mvref = MovementReference(vxyref=SVector{2}(0.2, 0.0), wzref=0.0)
# conparams = ControllerParams()
# robotconfig = PupperConfig()
# footlocations::SMatrix{3, 4, Float64, 12} = stanceparams.defaultstance .+ SVector{3, Float64}(0, 0, mvref.zref)
# ticks = 1
# println("Timing for step!")
# @btime step($ticks, $footlocations, $swingparams, $stanceparams, $gaitparams, $mvref, $conparams)
# @code_warntype step(ticks, footlocations, swingparams, stanceparams, gaitparams, mvref, conparams)
# end
# # testGait()
# # testKinematics()
# # TestStanceController()
# # testStaticArrays()
# # TestSwingLegController()
# test_inversekinematics_linkage()
# # teststep()
# # testrun()
test_inverse_kinematics_linkage()
test_stance_controller()
test_run()
| 10,778 | Python | 33.548077 | 128 | 0.59705 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/src/JoystickInterface.py | import UDPComms
import numpy as np
import time
from src.State import BehaviorState, State
from src.Command import Command
from src.Utilities import deadband, clipped_first_order_filter
class JoystickInterface:
def __init__(
self, config, udp_port=8830, udp_publisher_port = 8840,
):
self.config = config
self.previous_gait_toggle = 0
self.previous_state = BehaviorState.REST
self.previous_hop_toggle = 0
self.previous_activate_toggle = 0
self.message_rate = 50
self.udp_handle = UDPComms.Subscriber(udp_port, timeout=0.3)
self.udp_publisher = UDPComms.Publisher(udp_publisher_port)
def get_command(self, state, do_print=False):
try:
msg = self.udp_handle.get()
command = Command()
####### Handle discrete commands ########
# Check if requesting a state transition to trotting, or from trotting to resting
gait_toggle = msg["R1"]
command.trot_event = (gait_toggle == 1 and self.previous_gait_toggle == 0)
# Check if requesting a state transition to hopping, from trotting or resting
hop_toggle = msg["x"]
command.hop_event = (hop_toggle == 1 and self.previous_hop_toggle == 0)
activate_toggle = msg["L1"]
command.activate_event = (activate_toggle == 1 and self.previous_activate_toggle == 0)
# Update previous values for toggles and state
self.previous_gait_toggle = gait_toggle
self.previous_hop_toggle = hop_toggle
self.previous_activate_toggle = activate_toggle
####### Handle continuous commands ########
x_vel = msg["ly"] * self.config.max_x_velocity
y_vel = msg["lx"] * -self.config.max_y_velocity
command.horizontal_velocity = np.array([x_vel, y_vel])
command.yaw_rate = msg["rx"] * -self.config.max_yaw_rate
message_rate = msg["message_rate"]
message_dt = 1.0 / message_rate
pitch = msg["ry"] * self.config.max_pitch
deadbanded_pitch = deadband(
pitch, self.config.pitch_deadband
)
pitch_rate = clipped_first_order_filter(
state.pitch,
deadbanded_pitch,
self.config.max_pitch_rate,
self.config.pitch_time_constant,
)
command.pitch = state.pitch + message_dt * pitch_rate
height_movement = msg["dpady"]
command.height = state.height - message_dt * self.config.z_speed * height_movement
roll_movement = - msg["dpadx"]
command.roll = state.roll + message_dt * self.config.roll_speed * roll_movement
return command
except UDPComms.timeout:
if do_print:
print("UDP Timed out")
return Command()
def set_color(self, color):
joystick_msg = {"ps4_color": color}
self.udp_publisher.send(joystick_msg) | 3,099 | Python | 36.349397 | 98 | 0.575992 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/src/Utilities.py | import numpy as np
def deadband(value, band_radius):
return max(value - band_radius, 0) + min(value + band_radius, 0)
def clipped_first_order_filter(input, target, max_rate, tau):
rate = (target - input) / tau
return np.clip(rate, -max_rate, max_rate)
| 268 | Python | 23.454543 | 68 | 0.671642 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/src/Controller.py | from src.Gaits import GaitController
from src.StanceController import StanceController
from src.SwingLegController import SwingController
from src.Utilities import clipped_first_order_filter
from src.State import BehaviorState, State
import numpy as np
from transforms3d.euler import euler2mat, quat2euler
from transforms3d.quaternions import qconjugate, quat2axangle
from transforms3d.axangles import axangle2mat
class Controller:
"""Controller and planner object
"""
def __init__(
self,
config,
inverse_kinematics,
):
self.config = config
self.smoothed_yaw = 0.0 # for REST mode only
self.inverse_kinematics = inverse_kinematics
self.contact_modes = np.zeros(4)
self.gait_controller = GaitController(self.config)
self.swing_controller = SwingController(self.config)
self.stance_controller = StanceController(self.config)
self.hop_transition_mapping = {BehaviorState.REST: BehaviorState.HOP, BehaviorState.HOP: BehaviorState.FINISHHOP, BehaviorState.FINISHHOP: BehaviorState.REST, BehaviorState.TROT: BehaviorState.HOP}
self.trot_transition_mapping = {BehaviorState.REST: BehaviorState.TROT, BehaviorState.TROT: BehaviorState.REST, BehaviorState.HOP: BehaviorState.TROT, BehaviorState.FINISHHOP: BehaviorState.TROT}
self.activate_transition_mapping = {BehaviorState.DEACTIVATED: BehaviorState.REST, BehaviorState.REST: BehaviorState.DEACTIVATED}
def step_gait(self, state, command):
"""Calculate the desired foot locations for the next timestep
Returns
-------
Numpy array (3, 4)
Matrix of new foot locations.
"""
contact_modes = self.gait_controller.contacts(state.ticks)
new_foot_locations = np.zeros((3, 4))
for leg_index in range(4):
contact_mode = contact_modes[leg_index]
foot_location = state.foot_locations[:, leg_index]
if contact_mode == 1:
new_location = self.stance_controller.next_foot_location(leg_index, state, command)
else:
swing_proportion = (
self.gait_controller.subphase_ticks(state.ticks) / self.config.swing_ticks
)
new_location = self.swing_controller.next_foot_location(
swing_proportion,
leg_index,
state,
command
)
new_foot_locations[:, leg_index] = new_location
return new_foot_locations, contact_modes
def run(self, state, command):
"""Steps the controller forward one timestep
Parameters
----------
controller : Controller
Robot controller object.
"""
########## Update operating state based on command ######
if command.activate_event:
state.behavior_state = self.activate_transition_mapping[state.behavior_state]
elif command.trot_event:
state.behavior_state = self.trot_transition_mapping[state.behavior_state]
elif command.hop_event:
state.behavior_state = self.hop_transition_mapping[state.behavior_state]
if state.behavior_state == BehaviorState.TROT:
state.foot_locations, contact_modes = self.step_gait(
state,
command,
)
# Apply the desired body rotation
rotated_foot_locations = (
euler2mat(
command.roll, command.pitch, 0.0
)
@ state.foot_locations
)
# Construct foot rotation matrix to compensate for body tilt
(roll, pitch, yaw) = quat2euler(state.quat_orientation)
correction_factor = 0.8
max_tilt = 0.4
roll_compensation = correction_factor * np.clip(roll, -max_tilt, max_tilt)
pitch_compensation = correction_factor * np.clip(pitch, -max_tilt, max_tilt)
rmat = euler2mat(roll_compensation, pitch_compensation, 0)
rotated_foot_locations = rmat.T @ rotated_foot_locations
state.joint_angles = self.inverse_kinematics(
rotated_foot_locations, self.config
)
elif state.behavior_state == BehaviorState.HOP:
state.foot_locations = (
self.config.default_stance
+ np.array([0, 0, -0.09])[:, np.newaxis]
)
state.joint_angles = self.inverse_kinematics(
state.foot_locations, self.config
)
elif state.behavior_state == BehaviorState.FINISHHOP:
state.foot_locations = (
self.config.default_stance
+ np.array([0, 0, -0.22])[:, np.newaxis]
)
state.joint_angles = self.inverse_kinematics(
state.foot_locations, self.config
)
elif state.behavior_state == BehaviorState.REST:
yaw_proportion = command.yaw_rate / self.config.max_yaw_rate
self.smoothed_yaw += (
self.config.dt
* clipped_first_order_filter(
self.smoothed_yaw,
yaw_proportion * -self.config.max_stance_yaw,
self.config.max_stance_yaw_rate,
self.config.yaw_time_constant,
)
)
# Set the foot locations to the default stance plus the standard height
state.foot_locations = (
self.config.default_stance
+ np.array([0, 0, command.height])[:, np.newaxis]
)
# Apply the desired body rotation
rotated_foot_locations = (
euler2mat(
command.roll,
command.pitch,
self.smoothed_yaw,
)
@ state.foot_locations
)
state.joint_angles = self.inverse_kinematics(
rotated_foot_locations, self.config
)
state.ticks += 1
state.pitch = command.pitch
state.roll = command.roll
state.height = command.height
def set_pose_to_default(self):
state.foot_locations = (
self.config.default_stance
+ np.array([0, 0, self.config.default_z_ref])[:, np.newaxis]
)
state.joint_angles = controller.inverse_kinematics(
state.foot_locations, self.config
)
| 6,547 | Python | 37.292397 | 205 | 0.583168 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/pupper/ServoCalibration.py | # WARNING: This file is machine generated. Edit at your own risk.
import numpy as np
MICROS_PER_RAD = 11.333 * 180.0 / np.pi
NEUTRAL_ANGLE_DEGREES = np.array(
[[ 0., 0., 0., 0.],
[ 45., 45., 45., 45.],
[-45.,-45.,-45.,-45.]]
)
| 236 | Python | 18.749998 | 65 | 0.576271 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/pupper/HardwareInterface.py | import pigpio
from pupper.Config import ServoParams, PWMParams
class HardwareInterface:
def __init__(self):
self.pi = pigpio.pi()
self.pwm_params = PWMParams()
self.servo_params = ServoParams()
initialize_pwm(self.pi, self.pwm_params)
def set_actuator_postions(self, joint_angles):
send_servo_commands(self.pi, self.pwm_params, self.servo_params, joint_angles)
def set_actuator_position(self, joint_angle, axis, leg):
send_servo_command(self.pi, self.pwm_params, self.servo_params, joint_angle, axis, leg)
def pwm_to_duty_cycle(pulsewidth_micros, pwm_params):
"""Converts a pwm signal (measured in microseconds) to a corresponding duty cycle on the gpio pwm pin
Parameters
----------
pulsewidth_micros : float
Width of the pwm signal in microseconds
pwm_params : PWMParams
PWMParams object
Returns
-------
float
PWM duty cycle corresponding to the pulse width
"""
return int(pulsewidth_micros / 1e6 * pwm_params.freq * pwm_params.range)
def angle_to_pwm(angle, servo_params, axis_index, leg_index):
"""Converts a desired servo angle into the corresponding PWM command
Parameters
----------
angle : float
Desired servo angle, relative to the vertical (z) axis
servo_params : ServoParams
ServoParams object
axis_index : int
Specifies which joint of leg to control. 0 is abduction servo, 1 is inner hip servo, 2 is outer hip servo.
leg_index : int
Specifies which leg to control. 0 is front-right, 1 is front-left, 2 is back-right, 3 is back-left.
Returns
-------
float
PWM width in microseconds
"""
angle_deviation = (
angle - servo_params.neutral_angles[axis_index, leg_index]
) * servo_params.servo_multipliers[axis_index, leg_index]
pulse_width_micros = (
servo_params.neutral_position_pwm
+ servo_params.micros_per_rad * angle_deviation
)
return pulse_width_micros
def angle_to_duty_cycle(angle, pwm_params, servo_params, axis_index, leg_index):
return pwm_to_duty_cycle(
angle_to_pwm(angle, servo_params, axis_index, leg_index), pwm_params
)
def initialize_pwm(pi, pwm_params):
for leg_index in range(4):
for axis_index in range(3):
pi.set_PWM_frequency(
pwm_params.pins[axis_index, leg_index], pwm_params.freq
)
pi.set_PWM_range(pwm_params.pins[axis_index, leg_index], pwm_params.range)
def send_servo_commands(pi, pwm_params, servo_params, joint_angles):
for leg_index in range(4):
for axis_index in range(3):
duty_cycle = angle_to_duty_cycle(
joint_angles[axis_index, leg_index],
pwm_params,
servo_params,
axis_index,
leg_index,
)
pi.set_PWM_dutycycle(pwm_params.pins[axis_index, leg_index], duty_cycle)
def send_servo_command(pi, pwm_params, servo_params, joint_angle, axis, leg):
duty_cycle = angle_to_duty_cycle(joint_angle, pwm_params, servo_params, axis, leg)
pi.set_PWM_dutycycle(pwm_params.pins[axis, leg], duty_cycle)
def deactivate_servos(pi, pwm_params):
for leg_index in range(4):
for axis_index in range(3):
pi.set_PWM_dutycycle(pwm_params.pins[axis_index, leg_index], 0)
| 3,408 | Python | 32.097087 | 114 | 0.639085 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/pupper/Kinematics.py | import numpy as np
from transforms3d.euler import euler2mat
def leg_explicit_inverse_kinematics(r_body_foot, leg_index, config):
"""Find the joint angles corresponding to the given body-relative foot position for a given leg and configuration
Parameters
----------
r_body_foot : [type]
[description]
leg_index : [type]
[description]
config : [type]
[description]
Returns
-------
numpy array (3)
Array of corresponding joint angles.
"""
(x, y, z) = r_body_foot
# Distance from the leg origin to the foot, projected into the y-z plane
R_body_foot_yz = (y ** 2 + z ** 2) ** 0.5
# Distance from the leg's forward/back point of rotation to the foot
R_hip_foot_yz = (R_body_foot_yz ** 2 - config.ABDUCTION_OFFSET ** 2) ** 0.5
# Interior angle of the right triangle formed in the y-z plane by the leg that is coincident to the ab/adduction axis
# For feet 2 (front left) and 4 (back left), the abduction offset is positive, for the right feet, the abduction offset is negative.
arccos_argument = config.ABDUCTION_OFFSETS[leg_index] / R_body_foot_yz
arccos_argument = np.clip(arccos_argument, -0.99, 0.99)
phi = np.arccos(arccos_argument)
# Angle of the y-z projection of the hip-to-foot vector, relative to the positive y-axis
hip_foot_angle = np.arctan2(z, y)
# Ab/adduction angle, relative to the positive y-axis
abduction_angle = phi + hip_foot_angle
# theta: Angle between the tilted negative z-axis and the hip-to-foot vector
theta = np.arctan2(-x, R_hip_foot_yz)
# Distance between the hip and foot
R_hip_foot = (R_hip_foot_yz ** 2 + x ** 2) ** 0.5
# Angle between the line going from hip to foot and the link L1
arccos_argument = (config.LEG_L1 ** 2 + R_hip_foot ** 2 - config.LEG_L2 ** 2) / (
2 * config.LEG_L1 * R_hip_foot
)
arccos_argument = np.clip(arccos_argument, -0.99, 0.99)
trident = np.arccos(arccos_argument)
# Angle of the first link relative to the tilted negative z axis
hip_angle = theta + trident
# Angle between the leg links L1 and L2
arccos_argument = (config.LEG_L1 ** 2 + config.LEG_L2 ** 2 - R_hip_foot ** 2) / (
2 * config.LEG_L1 * config.LEG_L2
)
arccos_argument = np.clip(arccos_argument, -0.99, 0.99)
beta = np.arccos(arccos_argument)
# Angle of the second link relative to the tilted negative z axis
knee_angle = hip_angle - (np.pi - beta)
return np.array([abduction_angle, hip_angle, knee_angle])
def four_legs_inverse_kinematics(r_body_foot, config):
"""Find the joint angles for all twelve DOF correspoinding to the given matrix of body-relative foot positions.
Parameters
----------
r_body_foot : numpy array (3,4)
Matrix of the body-frame foot positions. Each column corresponds to a separate foot.
config : Config object
Object of robot configuration parameters.
Returns
-------
numpy array (3,4)
Matrix of corresponding joint angles.
"""
alpha = np.zeros((3, 4))
for i in range(4):
body_offset = config.LEG_ORIGINS[:, i]
alpha[:, i] = leg_explicit_inverse_kinematics(
r_body_foot[:, i] - body_offset, i, config
)
return alpha
| 3,324 | Python | 34.752688 | 136 | 0.639892 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/pupper/HardwareConfig.py | """
Per-robot configuration file that is particular to each individual robot, not just the type of robot.
"""
PS4_COLOR = {"red": 0, "blue": 0, "green": 255}
PS4_DEACTIVATED_COLOR = {"red": 0, "blue": 0, "green": 50} | 217 | Python | 35.333327 | 101 | 0.658986 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/pupper/Config.py | import numpy as np
from pupper.ServoCalibration import MICROS_PER_RAD, NEUTRAL_ANGLE_DEGREES
from pupper.HardwareConfig import PS4_COLOR, PS4_DEACTIVATED_COLOR
from enum import Enum
# TODO: put these somewhere else
class PWMParams:
def __init__(self):
self.pins = np.array([[2, 14, 18, 23], [3, 15, 27, 24], [4, 17, 22, 25]])
self.range = 4000
self.freq = 250
class ServoParams:
def __init__(self):
self.neutral_position_pwm = 1500 # Middle position
self.micros_per_rad = MICROS_PER_RAD # Must be calibrated
# The neutral angle of the joint relative to the modeled zero-angle in degrees, for each joint
self.neutral_angle_degrees = NEUTRAL_ANGLE_DEGREES
self.servo_multipliers = np.array(
[[1, 1, 1, 1], [-1, 1, -1, 1], [1, -1, 1, -1]]
)
@property
def neutral_angles(self):
return self.neutral_angle_degrees * np.pi / 180.0 # Convert to radians
class Configuration:
def __init__(self):
################# CONTROLLER BASE COLOR ##############
self.ps4_color = PS4_COLOR
self.ps4_deactivated_color = PS4_DEACTIVATED_COLOR
#################### COMMANDS ####################
self.max_x_velocity = 0.4
self.max_y_velocity = 0.3
self.max_yaw_rate = 2.0
self.max_pitch = 30.0 * np.pi / 180.0
#################### MOVEMENT PARAMS ####################
self.z_time_constant = 0.02
self.z_speed = 0.03 # maximum speed [m/s]
self.pitch_deadband = 0.02
self.pitch_time_constant = 0.25
self.max_pitch_rate = 0.15
self.roll_speed = 0.16 # maximum roll rate [rad/s]
self.yaw_time_constant = 0.3
self.max_stance_yaw = 1.2
self.max_stance_yaw_rate = 2.0
#################### STANCE ####################
self.delta_x = 0.1
self.delta_y = 0.09
self.x_shift = 0.0
self.default_z_ref = -0.16
#################### SWING ######################
self.z_coeffs = None
self.z_clearance = 0.07
self.alpha = (
0.5 # Ratio between touchdown distance and total horizontal stance movement
)
self.beta = (
0.5 # Ratio between touchdown distance and total horizontal stance movement
)
#################### GAIT #######################
self.dt = 0.01
self.num_phases = 4
self.contact_phases = np.array(
[[1, 1, 1, 0], [1, 0, 1, 1], [1, 0, 1, 1], [1, 1, 1, 0]]
)
self.overlap_time = (
0.10 # duration of the phase where all four feet are on the ground
)
self.swing_time = (
0.15 # duration of the phase when only two feet are on the ground
)
######################## GEOMETRY ######################
self.LEG_FB = 0.10 # front-back distance from center line to leg axis
self.LEG_LR = 0.04 # left-right distance from center line to leg plane
self.LEG_L2 = 0.115
self.LEG_L1 = 0.1235
self.ABDUCTION_OFFSET = 0.03 # distance from abduction axis to leg
self.FOOT_RADIUS = 0.01
self.HIP_L = 0.0394
self.HIP_W = 0.0744
self.HIP_T = 0.0214
self.HIP_OFFSET = 0.0132
self.L = 0.276
self.W = 0.100
self.T = 0.050
self.LEG_ORIGINS = np.array(
[
[self.LEG_FB, self.LEG_FB, -self.LEG_FB, -self.LEG_FB],
[-self.LEG_LR, self.LEG_LR, -self.LEG_LR, self.LEG_LR],
[0, 0, 0, 0],
]
)
self.ABDUCTION_OFFSETS = np.array(
[
-self.ABDUCTION_OFFSET,
self.ABDUCTION_OFFSET,
-self.ABDUCTION_OFFSET,
self.ABDUCTION_OFFSET,
]
)
################### INERTIAL ####################
self.FRAME_MASS = 0.560 # kg
self.MODULE_MASS = 0.080 # kg
self.LEG_MASS = 0.030 # kg
self.MASS = self.FRAME_MASS + (self.MODULE_MASS + self.LEG_MASS) * 4
# Compensation factor of 3 because the inertia measurement was just
# of the carbon fiber and plastic parts of the frame and did not
# include the hip servos and electronics
self.FRAME_INERTIA = tuple(
map(lambda x: 3.0 * x, (1.844e-4, 1.254e-3, 1.337e-3))
)
self.MODULE_INERTIA = (3.698e-5, 7.127e-6, 4.075e-5)
leg_z = 1e-6
leg_mass = 0.010
leg_x = 1 / 12 * self.LEG_L1 ** 2 * leg_mass
leg_y = leg_x
self.LEG_INERTIA = (leg_x, leg_y, leg_z)
@property
def default_stance(self):
return np.array(
[
[
self.delta_x + self.x_shift,
self.delta_x + self.x_shift,
-self.delta_x + self.x_shift,
-self.delta_x + self.x_shift,
],
[-self.delta_y, self.delta_y, -self.delta_y, self.delta_y],
[0, 0, 0, 0],
]
)
################## SWING ###########################
@property
def z_clearance(self):
return self.__z_clearance
@z_clearance.setter
def z_clearance(self, z):
self.__z_clearance = z
# b_z = np.array([0, 0, 0, 0, self.__z_clearance])
# A_z = np.array(
# [
# [0, 0, 0, 0, 1],
# [1, 1, 1, 1, 1],
# [0, 0, 0, 1, 0],
# [4, 3, 2, 1, 0],
# [0.5 ** 4, 0.5 ** 3, 0.5 ** 2, 0.5 ** 1, 0.5 ** 0],
# ]
# )
# self.z_coeffs = solve(A_z, b_z)
########################### GAIT ####################
@property
def overlap_ticks(self):
return int(self.overlap_time / self.dt)
@property
def swing_ticks(self):
return int(self.swing_time / self.dt)
@property
def stance_ticks(self):
return 2 * self.overlap_ticks + self.swing_ticks
@property
def phase_ticks(self):
return np.array(
[self.overlap_ticks, self.swing_ticks, self.overlap_ticks, self.swing_ticks]
)
@property
def phase_length(self):
return 2 * self.overlap_ticks + 2 * self.swing_ticks
class SimulationConfig:
def __init__(self):
self.XML_IN = "pupper.xml"
self.XML_OUT = "pupper_out.xml"
self.START_HEIGHT = 0.3
self.MU = 1.5 # coeff friction
self.DT = 0.001 # seconds between simulation steps
self.JOINT_SOLREF = "0.001 1" # time constant and damping ratio for joints
self.JOINT_SOLIMP = "0.9 0.95 0.001" # joint constraint parameters
self.GEOM_SOLREF = "0.01 1" # time constant and damping ratio for geom contacts
self.GEOM_SOLIMP = "0.9 0.95 0.001" # geometry contact parameters
# Joint params
G = 220 # Servo gear ratio
m_rotor = 0.016 # Servo rotor mass
r_rotor = 0.005 # Rotor radius
self.ARMATURE = G ** 2 * m_rotor * r_rotor ** 2 # Inertia of rotational joints
# print("Servo armature", self.ARMATURE)
NATURAL_DAMPING = 1.0 # Damping resulting from friction
ELECTRICAL_DAMPING = 0.049 # Damping resulting from back-EMF
self.REV_DAMPING = (
NATURAL_DAMPING + ELECTRICAL_DAMPING
) # Damping torque on the revolute joints
# Servo params
self.SERVO_REV_KP = 300 # Position gain [Nm/rad]
# Force limits
self.MAX_JOINT_TORQUE = 3.0
self.REVOLUTE_RANGE = 1.57
| 7,666 | Python | 32.480349 | 102 | 0.501435 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/woofer/HardwareInterface.py | import odrive
from odrive.enums import *
from woofer.Config import RobotConfig
from woofer.HardwareConfig import (
ODRIVE_SERIAL_NUMBERS,
ACTUATOR_DIRECTIONS,
ANGLE_OFFSETS,
map_actuators_to_axes,
)
import time
import threading
import numpy as np
class HardwareInterface:
def __init__(self):
self.config = RobotConfig()
assert len(ODRIVE_SERIAL_NUMBERS) == self.config.NUM_ODRIVES
self.odrives = [None for _ in range(self.config.NUM_ODRIVES)]
threads = []
for i in range(self.config.NUM_ODRIVES):
t = threading.Thread(target=find_odrive, args=(i, self.odrives))
threads.append(t)
t.start()
for t in threads:
t.join()
input("Press enter to calibrate odrives...")
calibrate_odrives(self.odrives)
set_position_control(self.odrives)
self.axes = assign_axes(self.odrives)
def set_actuator_postions(self, joint_angles):
set_all_odrive_positions(self.axes, joint_angles, self.config)
def deactivate_actuators(self):
set_odrives_idle(self.odrives)
def find_odrive(i, odrives):
o = odrive.find_any(serial_number=ODRIVE_SERIAL_NUMBERS[i])
print("Found odrive: ", i)
odrives[i] = o
def calibrate_odrives(odrives):
for odrv in odrives:
odrv.axis0.requested_state = AXIS_STATE_FULL_CALIBRATION_SEQUENCE
odrv.axis1.requested_state = AXIS_STATE_FULL_CALIBRATION_SEQUENCE
for odrv in odrives:
while (
odrv.axis0.current_state != AXIS_STATE_IDLE
or odrv.axis1.current_state != AXIS_STATE_IDLE
):
time.sleep(0.1) # busy waiting - not ideal
def set_position_control(odrives):
for odrv in odrives:
for axis in [odrv.axis0, odrv.axis1]:
axis.controller.config.pos_gain = 60
axis.controller.config.vel_gain = 0.002
axis.controller.config.vel_limit_tolerance = 0
axis.controller.config.vel_integrator_gain = 0
axis.motor.config.current_lim = 15
print("Updated gains")
odrv.axis0.requested_state = AXIS_STATE_CLOSED_LOOP_CONTROL
odrv.axis1.requested_state = AXIS_STATE_CLOSED_LOOP_CONTROL
def set_odrives_idle(odrives):
for odrv in odrives:
odrv.axis0.requested_state = AXIS_STATE_IDLE
odrv.axis1.requested_state = AXIS_STATE_IDLE
def assign_axes(odrives):
return map_actuators_to_axes(odrives)
def set_all_odrive_positions(axes, joint_angles, config):
for i in range(joint_angles.shape[0]):
for j in range(joint_angles.shape[1]):
axes[i][j].controller.pos_setpoint = actuator_angle_to_odrive(
joint_angles, i, j, config
)
def radians_to_encoder_count(angle, config):
return (angle / (2 * np.pi)) * config.ENCODER_CPR * config.MOTOR_REDUCTION
def actuator_angle_to_odrive(joint_angles, i, j, config):
offset_angle = joint_angles[i][j] + ANGLE_OFFSETS[i][j]
odrive_radians = offset_angle * ACTUATOR_DIRECTIONS[i][j]
return radians_to_encoder_count(odrive_radians, config)
| 3,118 | Python | 30.82653 | 78 | 0.652341 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/woofer/Kinematics.py | import numpy as np
def leg_forward_kinematics(alpha, leg_index, config):
"""Find the body-centric coordinates of a given foot given the joint angles.
Parameters
----------
alpha : Numpy array (3)
Joint angles ordered as (abduction, hip, knee)
leg_index : int
Leg index.
config : Config object
Robot parameters object
Returns
-------
Numpy array (3)
Body-centric coordinates of the specified foot
"""
pass
def leg_explicit_inverse_kinematics(r_body_foot, leg_index, config):
"""Find the joint angles corresponding to the given body-relative foot position for a given leg and configuration
Parameters
----------
r_body_foot : [type]
[description]
leg_index : [type]
[description]
config : [type]
[description]
Returns
-------
numpy array (3)
Array of corresponding joint angles.
"""
(x, y, z) = r_body_foot
# Distance from the leg origin to the foot, projected into the y-z plane
R_body_foot_yz = (y ** 2 + z ** 2) ** 0.5
# Distance from the leg's forward/back point of rotation to the foot
R_hip_foot_yz = (R_body_foot_yz ** 2 - config.ABDUCTION_OFFSET ** 2) ** 0.5
# Interior angle of the right triangle formed in the y-z plane by the leg that is coincident to the ab/adduction axis
# For feet 2 (front left) and 4 (back left), the abduction offset is positive, for the right feet, the abduction offset is negative.
cos_param = config.ABDUCTION_OFFSETS[leg_index] / R_body_foot_yz
if abs(cos_param) > 0.9:
print("Clipping 1st cos param")
cos_param = np.clip(cos_param, -0.9, 0.9)
phi = np.arccos(cos_param)
# Angle of the y-z projection of the hip-to-foot vector, relative to the positive y-axis
hip_foot_angle = np.arctan2(z, y)
# Ab/adduction angle, relative to the positive y-axis
abduction_angle = phi + hip_foot_angle
# theta: Angle between the tilted negative z-axis and the hip-to-foot vector
theta = np.arctan2(-x, R_hip_foot_yz)
# Distance between the hip and foot
R_hip_foot = (R_hip_foot_yz ** 2 + x ** 2) ** 0.5
# Using law of cosines to determine the angle between upper leg links
cos_param = (config.UPPER_LEG ** 2 + R_hip_foot ** 2 - config.LOWER_LEG ** 2) / (2.0*config.UPPER_LEG*R_hip_foot)
# Ensure that the leg isn't over or under extending
cos_param = np.clip(cos_param, -0.9, 0.9)
if abs(cos_param) > 0.9:
print("Clipping 2nd cos param")
# gamma: Angle between upper leg links and the center of the leg
gamma = np.arccos(cos_param)
return np.array([abduction_angle, theta - gamma, theta + gamma])
def four_legs_inverse_kinematics(r_body_foot, config):
"""Find the joint angles for all twelve DOF correspoinding to the given matrix of body-relative foot positions.
Parameters
----------
r_body_foot : numpy array (3,4)
Matrix of the body-frame foot positions. Each column corresponds to a separate foot.
config : Config object
Object of robot configuration parameters.
Returns
-------
numpy array (3,4)
Matrix of corresponding joint angles.
"""
alpha = np.zeros((3, 4))
for i in range(4):
body_offset = config.LEG_ORIGINS[:, i]
alpha[:, i] = leg_explicit_inverse_kinematics(
r_body_foot[:, i] - body_offset, i, config
)
return alpha | 3,449 | Python | 34.204081 | 136 | 0.636416 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/woofer/HardwareConfig.py | """
Per-robot configuration file that is particular to each individual robot, not just the type of robot.
"""
import numpy as np
ODRIVE_SERIAL_NUMBERS = [
"2065339F304B",
"208F3384304B",
"365833753037",
"207E35753748",
"208F3385304B",
"208E3387304B",
]
ACTUATOR_DIRECTIONS = np.array([[1, 1, -1, -1], [-1, -1, -1, -1], [1, 1, 1, 1]])
ANGLE_OFFSETS = np.array(
[
[0, 0, 0, 0],
[np.pi / 2, np.pi / 2, np.pi / 2, np.pi / 2],
[-np.pi / 2, -np.pi / 2, -np.pi / 2, -np.pi / 2],
]
)
def map_actuators_to_axes(odrives):
axes = [[None for _ in range(4)] for _ in range(3)]
axes[0][0] = odrives[1].axis1
axes[1][0] = odrives[0].axis0
axes[2][0] = odrives[0].axis1
axes[0][1] = odrives[1].axis0
axes[1][1] = odrives[2].axis1
axes[2][1] = odrives[2].axis0
axes[0][2] = odrives[4].axis1
axes[1][2] = odrives[5].axis0
axes[2][2] = odrives[5].axis1
axes[0][3] = odrives[4].axis0
axes[1][3] = odrives[3].axis1
axes[2][3] = odrives[3].axis0
return axes
| 1,057 | Python | 22.511111 | 101 | 0.553453 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/StanfordQuadruped-pupper/woofer/Config.py | import numpy as np
from scipy.linalg import solve
class BehaviorState(Enum):
REST = 0
TROT = 1
HOP = 2
FINISHHOP = 3
class UserInputParams:
def __init__(self):
self.max_x_velocity = 0.5
self.max_y_velocity = 0.24
self.max_yaw_rate = 0.2
self.max_pitch = 30.0 * np.pi / 180.0
class MovementReference:
"""Stores movement reference
"""
def __init__(self):
self.v_xy_ref = np.array([0, 0])
self.wz_ref = 0.0
self.z_ref = -0.265
self.pitch = 0.0
self.roll = 0.0
class SwingParams:
"""Swing Parameters
"""
def __init__(self):
self.z_coeffs = None
self.z_clearance = 0.05
self.alpha = (
0.5
) # Ratio between touchdown distance and total horizontal stance movement
self.beta = (
0.5
) # Ratio between touchdown distance and total horizontal stance movement
@property
def z_clearance(self):
return self.__z_clearance
@z_clearance.setter
def z_clearance(self, z):
self.__z_clearance = z
b_z = np.array([0, 0, 0, 0, self.__z_clearance])
A_z = np.array(
[
[0, 0, 0, 0, 1],
[1, 1, 1, 1, 1],
[0, 0, 0, 1, 0],
[4, 3, 2, 1, 0],
[0.5 ** 4, 0.5 ** 3, 0.5 ** 2, 0.5 ** 1, 0.5 ** 0],
]
)
self.z_coeffs = solve(A_z, b_z)
class StanceParams:
"""Stance parameters
"""
def __init__(self):
self.z_time_constant = 0.02
self.z_speed = 0.03 # maximum speed [m/s]
self.pitch_deadband = 0.02
self.pitch_time_constant = 0.25
self.max_pitch_rate = 0.15
self.roll_speed = 0.16 # maximum roll rate [rad/s]
self.delta_x = 0.23
self.delta_y = 0.173
self.x_shift = -0.01
@property
def default_stance(self):
return np.array(
[
[
self.delta_x + self.x_shift,
self.delta_x + self.x_shift,
-self.delta_x + self.x_shift,
-self.delta_x + self.x_shift,
],
[-self.delta_y, self.delta_y, -self.delta_y, self.delta_y],
[0, 0, 0, 0],
]
)
class GaitParams:
"""Gait Parameters
"""
def __init__(self):
self.dt = 0.01
self.num_phases = 4
self.contact_phases = np.array(
[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
)
self.overlap_time = (
0.5 # duration of the phase where all four feet are on the ground
)
self.swing_time = (
0.5 # duration of the phase when only two feet are on the ground
)
@property
def overlap_ticks(self):
return int(self.overlap_time / self.dt)
@property
def swing_ticks(self):
return int(self.swing_time / self.dt)
@property
def stance_ticks(self):
return 2 * self.overlap_ticks + self.swing_ticks
@property
def phase_times(self):
return np.array(
[self.overlap_ticks, self.swing_ticks, self.overlap_ticks, self.swing_ticks]
)
@property
def phase_length(self):
return 2 * self.overlap_ticks + 2 * self.swing_ticks
class RobotConfig:
"""Woofer hardware parameters
"""
def __init__(self):
# Robot geometry
self.LEG_FB = 0.23 # front-back distance from center line to leg axis
self.LEG_LR = 0.109 # left-right distance from center line to leg plane
self.ABDUCTION_OFFSET = 0.064 # distance from abduction axis to leg
self.FOOT_RADIUS = 0.02
self.UPPER_LEG = 0.18
self.LOWER_LEG = 0.32
# Update hip geometry
self.HIP_L = 0.0394
self.HIP_W = 0.0744
self.HIP_T = 0.0214
self.HIP_OFFSET = 0.0132
self.L = 0.66
self.W = 0.176
self.T = 0.092
self.LEG_ORIGINS = np.array(
[
[self.LEG_FB, self.LEG_FB, -self.LEG_FB, -self.LEG_FB],
[-self.LEG_LR, self.LEG_LR, -self.LEG_LR, self.LEG_LR],
[0, 0, 0, 0],
]
)
self.ABDUCTION_OFFSETS = np.array(
[
-self.ABDUCTION_OFFSET,
self.ABDUCTION_OFFSET,
-self.ABDUCTION_OFFSET,
self.ABDUCTION_OFFSET,
]
)
self.START_HEIGHT = 0.3
# Robot inertia params
self.FRAME_MASS = 3.0 # kg
self.MODULE_MASS = 1.033 # kg
self.LEG_MASS = 0.15 # kg
self.MASS = self.FRAME_MASS + (self.MODULE_MASS + self.LEG_MASS) * 4
# Compensation factor of 3 because the inertia measurement was just
# of the carbon fiber and plastic parts of the frame and did not
# include the hip servos and electronics
self.FRAME_INERTIA = tuple(
map(lambda x: 3.0 * x, (1.844e-4, 1.254e-3, 1.337e-3))
)
self.MODULE_INERTIA = (3.698e-5, 7.127e-6, 4.075e-5)
leg_z = 1e-6
leg_mass = 0.010
leg_x = 1 / 12 * self.LOWER_LEG ** 2 * leg_mass
leg_y = leg_x
self.LEG_INERTIA = (leg_x, leg_y, leg_z)
# Joint params
G = 220 # Servo gear ratio
m_rotor = 0.016 # Servo rotor mass
r_rotor = 0.005 # Rotor radius
self.ARMATURE = G ** 2 * m_rotor * r_rotor ** 2 # Inertia of rotational joints
# print("Servo armature", self.ARMATURE)
NATURAL_DAMPING = 1.0 # Damping resulting from friction
ELECTRICAL_DAMPING = 0.049 # Damping resulting from back-EMF
self.REV_DAMPING = (
NATURAL_DAMPING + ELECTRICAL_DAMPING
) # Damping torque on the revolute joints
# Force limits
self.MAX_JOINT_TORQUE = 12.0
self.REVOLUTE_RANGE = 3
self.NUM_ODRIVES = 6
self.ENCODER_CPR = 2000
self.MOTOR_REDUCTION = 4
class EnvironmentConfig:
"""Environmental parameters
"""
def __init__(self):
self.MU = 1.5 # coeff friction
self.DT = 0.001 # seconds between simulation steps
class SolverConfig:
"""MuJoCo solver parameters
"""
def __init__(self):
self.JOINT_SOLREF = "0.001 1" # time constant and damping ratio for joints
self.JOINT_SOLIMP = "0.9 0.95 0.001" # joint constraint parameters
self.GEOM_SOLREF = "0.01 1" # time constant and damping ratio for geom contacts
self.GEOM_SOLIMP = "0.9 0.95 0.001" # geometry contact parameters
| 6,661 | Python | 26.643153 | 88 | 0.523945 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/mini_pupper_simplified/README.md | # Mini Pupper Robot Description (URDF)
## Overview
This package contains a simplified robot description (URDF) of the [Mini Pupper](https://www.kickstarter.com/projects/336477435/mini-pupper-open-sourceros-robot-dog-kit) developed by [MangDang](https://twitter.com/LeggedRobot).
STL filesare forked from [mayataka/mini_pupper_trajopt](https://github.com/mayataka/mini_pupper_trajopt).
## License
This software is released under a [BSD 3-Clause license](LICENSE).
## Usage
See [CHAMP](https://github.com/chvmp/champ)
| 523 | Markdown | 31.749998 | 227 | 0.768642 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/UDPComms/rover.py | #!/usr/bin/env python3
import sys
import argparse
import json
import time
import select
import pexpect
import UDPComms
import msgpack
def peek_func(port):
sub = UDPComms.Subscriber(port, timeout = 10)
while 1:
try:
data = sub.recv()
print( json.dumps(data) )
except UDPComms.timeout:
exit()
def poke_func(port, rate):
pub = UDPComms.Publisher(port)
data = None
while 1:
if select.select([sys.stdin], [], [], 0)[0]:
line = sys.stdin.readline()
# detailed behaviour
# reading from file: -ignores empty lines -repeats last line forever
# reading from terminal: -repeats last command
if line.rstrip():
data = line.rstrip()
elif len(line) == 0:
# exit() #uncomment to quit on end of file
pass
else:
continue
if data != None:
pub.send( json.loads(data) )
time.sleep( rate/1000 )
def call_func(command, ssh = True):
child = pexpect.spawn(command)
if ssh:
i = 1
while i == 1:
try:
i = child.expect(['password:',
'Are you sure you want to continue connecting',
'Welcome'], timeout=20)
except pexpect.EOF:
print("Can't connect to device")
exit()
except pexpect.TIMEOUT:
print("Interaction with device failed")
exit()
if i == 1:
child.sendline('yes')
if i == 0:
child.sendline('raspberry')
else:
try:
child.expect('robot:', timeout=1)
child.sendline('hello')
except pexpect.TIMEOUT:
pass
child.interact()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest='subparser')
peek = subparsers.add_parser("peek")
peek.add_argument('port', help="UDP port to subscribe to", type=int)
poke = subparsers.add_parser("poke")
poke.add_argument('port', help="UDP port to publish the data to", type=int)
poke.add_argument('rate', help="how often to republish (ms)", type=float)
peek = subparsers.add_parser("discover")
commands = ['status', 'log', 'start', 'stop', 'restart', 'enable', 'disable']
for command in commands:
status = subparsers.add_parser(command)
status.add_argument('host', help="Which device to look for this program on")
status.add_argument('unit', help="The unit whose status we want to know",
nargs='?', default=None)
connect = subparsers.add_parser('connect')
connect.add_argument('host', help="Which device to log into")
args = parser.parse_args()
if args.subparser == 'peek':
peek_func(args.port)
elif args.subparser == 'poke':
poke_func(args.port, args.rate)
elif args.subparser == 'connect':
call_func("ssh pi@"+args.host+".local")
elif args.subparser == 'discover':
call_func("nmap -sP 10.0.0.0/24", ssh=False)
elif args.subparser in commands:
if args.unit is None:
args.unit = args.host
if args.host == 'local':
prefix = ""
ssh = False
else:
prefix = "ssh pi@"+args.host+".local "
ssh = True
if args.subparser == 'status':
call_func(prefix + "sudo systemctl status "+args.unit, ssh)
elif args.subparser == 'log':
call_func(prefix + "sudo journalctl -f -u "+args.unit, ssh)
elif args.subparser == 'start':
call_func(prefix + "sudo systemctl start "+args.unit, ssh)
elif args.subparser == 'stop':
call_func(prefix + "sudo systemctl stop "+args.unit, ssh)
elif args.subparser == 'restart':
call_func(prefix + "sudo systemctl restart "+args.unit, ssh)
elif args.subparser == 'enable':
call_func(prefix + "sudo systemctl enable "+args.unit, ssh)
elif args.subparser == 'disable':
call_func(prefix + "sudo systemctl disable "+args.unit, ssh)
else:
parser.print_help()
| 4,329 | Python | 30.838235 | 84 | 0.546778 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/UDPComms/__init__.py | from .UDPComms import Publisher
from .UDPComms import Subscriber
from .UDPComms import timeout
| 95 | Python | 22.999994 | 32 | 0.842105 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/UDPComms/setup.py | #!/usr/bin/env python
from distutils.core import setup
setup(name='UDPComms',
version='1.1dev',
py_modules=['UDPComms'],
description='Simple library for sending messages over UDP',
author='Michal Adamkiewicz',
author_email='mikadam@stanford.edu',
url='https://github.com/stanfordroboticsclub/UDP-Comms',
)
| 349 | Python | 25.923075 | 65 | 0.673352 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/UDPComms/UDPComms.py |
import socket
import struct
from collections import namedtuple
from time import monotonic
import msgpack
import time
timeout = socket.timeout
MAX_SIZE = 65507
class Publisher:
def __init__(self, port_tx,port):
""" Create a Publisher Object
Arguments:
port -- the port to publish the messages on
"""
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.des_address = ("127.0.0.1",port_tx)
self.sock.bind(("127.0.0.1", port))
self.sock.settimeout(0.2)
def send(self, obj):
""" Publish a message. The obj can be any nesting of standard python types """
msg = msgpack.dumps(obj, use_bin_type=False)
assert len(msg) < MAX_SIZE, "Encoded message too big!"
self.sock.sendto(msg,self.des_address)
def __del__(self):
self.sock.close()
class Subscriber:
def __init__(self, port_rx, timeout=0.2):
""" Create a Subscriber Object
Arguments:
port -- the port to listen to messages on
timeout -- how long to wait before a message is considered out of date
"""
self.max_size = MAX_SIZE
self.timeout = timeout
self.last_data = None
self.last_time = float('-inf')
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.settimeout(timeout)
self.sock.bind(("127.0.0.1", port_rx))
def recv(self):
""" Receive a single message from the socket buffer. It blocks for up to timeout seconds.
If no message is received before timeout it raises a UDPComms.timeout exception"""
try:
self.last_data, address = self.sock.recvfrom(3)
except BlockingIOError:
raise socket.timeout("no messages in buffer and called with timeout = 0")
print(self.last_data)
self.last_time = monotonic()
return msgpack.loads(self.last_data, raw=False)
def get(self):
""" Returns the latest message it can without blocking. If the latest massage is
older then timeout seconds it raises a UDPComms.timeout exception"""
try:
self.sock.settimeout(0)
while True:
self.last_data, address = self.sock.recvfrom(self.max_size)
self.last_time = monotonic()
except socket.error:
pass
finally:
self.sock.settimeout(self.timeout)
current_time = monotonic()
if (current_time - self.last_time) < self.timeout:
return msgpack.loads(self.last_data, raw=False)
else:
raise socket.timeout("timeout=" + str(self.timeout) + \
", last message time=" + str(self.last_time) + \
", current time=" + str(current_time))
def get_list(self):
""" Returns list of messages, in the order they were received"""
msg_bufer = []
try:
self.sock.settimeout(0)
while True:
self.last_data, address = self.sock.recvfrom(self.max_size)
self.last_time = monotonic()
msg = msgpack.loads(self.last_data, raw=False)
msg_bufer.append(msg)
except socket.error:
pass
finally:
self.sock.settimeout(self.timeout)
return msg_bufer
def __del__(self):
self.sock.close()
class Subscriber:
def __init__(self, port, timeout=0.2):
""" Create a Subscriber Object
Arguments:
port -- the port to listen to messages on
timeout -- how long to wait before a message is considered out of date
"""
self.max_size = MAX_SIZE
self.port = port
self.timeout = timeout
self.last_data = None
self.last_time = float('-inf')
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if hasattr(socket, "SO_REUSEPORT"):
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
self.sock.settimeout(timeout)
self.sock.bind(("", port))
def recv(self):
""" Receive a single message from the socket buffer. It blocks for up to timeout seconds.
If no message is received before timeout it raises a UDPComms.timeout exception"""
try:
self.last_data, address = self.sock.recvfrom(self.max_size)
except BlockingIOError:
raise socket.timeout("no messages in buffer and called with timeout = 0")
self.last_time = monotonic()
return msgpack.loads(self.last_data, raw=False)
def get(self):
""" Returns the latest message it can without blocking. If the latest massage is
older then timeout seconds it raises a UDPComms.timeout exception"""
try:
self.sock.settimeout(0)
while True:
self.last_data, address = self.sock.recvfrom(self.max_size)
self.last_time = monotonic()
except socket.error:
pass
finally:
self.sock.settimeout(self.timeout)
current_time = monotonic()
if (current_time - self.last_time) < self.timeout:
return msgpack.loads(self.last_data, raw=False)
else:
raise socket.timeout("timeout=" + str(self.timeout) + \
", last message time=" + str(self.last_time) + \
", current time=" + str(current_time))
def get_list(self):
""" Returns list of messages, in the order they were received"""
msg_bufer = []
try:
self.sock.settimeout(0)
while True:
self.last_data, address = self.sock.recvfrom(self.max_size)
self.last_time = monotonic()
msg = msgpack.loads(self.last_data, raw=False)
msg_bufer.append(msg)
except socket.error:
pass
finally:
self.sock.settimeout(self.timeout)
return msg_bufer
def __del__(self):
self.sock.close()
if __name__ == "__main__":
msg = 'very important data'
a = Publisher(1000)
a.send( {"text": "magic", "number":5.5, "bool":False} )
| 6,463 | Python | 33.021052 | 97 | 0.573727 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/UDPComms/README.md | # UDPComms
This is a simple library to enable communication between different processes (potentially on different machines) over a network using UDP. It's goals a simplicity and easy of understanding and reliability. It works for devices on the `10.0.0.X` subnet although this can easiliy be changed.
Currently it works in python 2 and 3 but it should be relatively simple to extend it to other languages such as C (to run on embeded devices) or Julia (to interface with faster solvers).
This new verison of the library automatically determines the type of the message and trasmits it along with it, so the subscribers can decode it correctly. While faster to prototype with then systems with explicit type declaration (such as ROS) its easy to shoot yourself in the foot if types are mismatched between publisher and subscriber.
### To Send Messages
```
>>> from UDPComms import Publisher
>>> a = Publisher(5500)
>>> a.send({"name":"Bob", "age": 20, "height": 180.5, "mass": 70.1})
```
### To Receive Messages
#### recv Method
Note: before using the `Subsciber.recv()` method read about the `Subsciber.get()` and understand the difference between them. The `Subsciber.recv()` method will pull a message from the socket buffer and it won't necessary be the most recent message. If you are calling it too slowly and there is a lot of messages you will be getting old messages. The `Subsciber.recv()` can also block for up to `timeout` seconds messing up timing.
```
>>> from UDPComms import Subscriber
>>> a = Subscriber(5500)
>>> message = a.recv()
>>> message['age']
20
>>> message['height']
180.5
>>> message['name']
"Bob"
>>> message
{"name":"Bob", "age": 20, "height": 180.5, "mass": 70.1}
```
#### get Method
The preferred way of accessing messages is the `Subsciber.get()` method (as opposed to the `recv()` method). It is guaranteed to be nonblocking so it can be used in places without messing with timing. It checks for any new messages and returns the newest one.
If the newest message is older then `timeout` seconds it raises the `UDPComms.timeout` exception. **This is an important safety feature!** Make sure to catch the timeout using `try: ... except UDPComms.timeout: ...` and put the robot in a safe configuration (e.g. turn off motors, when the joystick stop sending messages)
Note that if you call `.get` immediately after creating a subscriber it is possible its hasn't received any messages yet and it will timeout. In general it is better to have a short timeout and gracefully catch timeouts then to have long timeouts
```
>>> from UDPComms import Subscriber, timout
>>> a = Subscriber(5500)
>>> while 1:
>>> try:
>>> message = a.get()
>>> print("got", message)
>>> except timeout:
>>> print("safing robot")
```
#### get_list Method
Although UDPComms isn't ideal for commands that need to be processed in order (as the underlying UDP protocol has no guarantees of deliverry) it can be used as such in a pinch. The `Subsciber.get_list()` method will return all the messages we haven't seen yet in a list
```
>>> from UDPComms import Subscriber, timout
>>> a = Subscriber(5500)
>>> messages = a.get_list()
>>> for message in messages:
>>> print("got", message)
```
### Publisher Arguments
- `port`
The port the messages will be sent on. If you are part of Stanford Student Robotics make sure there isn't any port conflicts by checking the `UDP Ports` sheet of the [CS Comms System](https://docs.google.com/spreadsheets/d/1pqduUwYa1_sWiObJDrvCCz4Al3pl588ytE4u-Dwa6Pw/edit?usp=sharing) document. If you are not I recommend keep track of your port numbers somewhere. It's possible that in the future UDPComms will have a system of naming (with a string) as opposed to numbering publishers.
- `ip` By default UDPComms sends to the `10.0.0.X` subnet, but can be changed to a different ip using this argument. Set to localhost (`127.0.0.1`) for development on the same computer.
### Subscriber Arguments
- `port`
The port the subscriber will be listen on.
- `timeout`
If the `recv()` method don't get a message in `timeout` seconds it throws a `UDPComms.timeout` exception
### Rover
The library also comes with the `rover` command that can be used to interact with the messages manually.
| Command | Descripion |
|---------|------------|
| `rover peek port` | print messages sent on port `port` |
| `rover poke port rate` | send messages to `port` once every `rate` milliseconds. Type message in json format and press return |
There are more commands used for starting and stoping services described in [this repo](https://github.com/stanfordroboticsclub/RPI-Setup/blob/master/README.md)
### To Install
```
$git clone https://github.com/stanfordroboticsclub/UDPComms.git
$sudo bash UDPComms/install.sh
```
### To Update
```
$cd UDPComms
$git pull
$sudo bash install.sh
```
### Developing without hardware
Because this library expects you to be connected to the robot (`10.0.0.X`) network you won't be able to send messages between two programs on your computer without any other hardware connected. You can get around this by forcing your (unused) ethernet interface to get an ip on the rover network without anything being connected to it. On my computer you can do this using this command:
`sudo ifconfig en1 10.0.0.52 netmask 255.255.255.0`
Note that the exact command depends which interface on your computer is unused and what ip you want. So only use this if you know what you are doing.
If you have internet access a slightly cleaner way to do it is to setup [RemoteVPN](https://github.com/stanfordroboticsclub/RemoteVPN) on your development computer and simply connect to a development network (given if you are the only computer there)
### Known issues:
- Macs have issues sending large messages. They are fine receiving them. I think it is related to [this issue](https://github.com/BanTheRewind/Cinder-Asio/issues/9). I wonder does it work on Linux by chance (as the packets happen to be in order) but so far we didn't have issues.
- Messages over the size of one MTU (typically 1500 bytes) will be split up into multiple frames which reduces their chance of getting to their destination on wireless networks.
| 6,216 | Markdown | 50.380165 | 489 | 0.742117 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Doc/guide/software_installation.rst | =====================
Software Installation
=====================
.. contents:: :depth: 4
Setting up your Raspberry Pi
------------------------------
* Raspberry Pi 4(2GB DDR for normal use, 4GB DDR for install and debug by self)
* SD Card (32GB recommended)
* Raspberry Pi 4 power supply (USB-C, 5V, >=3A)
* Ethernet cable
Preparing the Pi's SD card
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
From your desktop / laptop:
1. Put the SD card into your desktop / laptop.
###############################################
2. Download this version of Ubuntu 21.10
#################################################################
Download Ubuntu21.10 server version 64bit image(NOT including desktop). Use `this version <https://drive.google.com/file/d/1JVtjFTKE6FloG3giyMN_VuS0dKt4n2xq/view?usp=sharing>`_ so everyone is using the same version. Unzip and extract the file.
You can also check the version from `ubuntu offical website. <https://ubuntu.com/download/raspberry-pi>`_
3. Use `etcher <https://www.balena.io/etcher/>`_ to flash the card.
##########################################################################################
* For quick start, you can also download the `pre-installed image <https://drive.google.com/drive/folders/12FDFbZzO61Euh8pJI9oCxN-eLVm5zjyi?usp=sharing>`_ , (username: ubuntu , password: mangdang ) flash it into the card, then skip all the following steps and start to calibarte the Pupper Mini.
* If you are using the recommended etcher, this is the start-up menu. Select ubuntu-21.10-preinstalled-server-arm64+raspi.img (file inside zip )and the SD card.
.. image:: ../_static/flash1.png
:align: center
* Image of SD card being flashed.
.. image:: ../_static/flash2.png
:align: center
* Done!
.. image:: ../_static/flash3.png
:align: center
Enabling Basic Functionality
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1. Turn on your Raspberry Pi.
###################################################################################################
Remove SD card from computer and put it into your Raspberry Pi.
Connect the IO board to the Pi,
Connect battery power from IO board power interface,
Connect keyboard, and mouse to the Pi as well.
Connect the Pi to a displayer by HDMI line.
Switch power on/off button to set up the Pi.
Follow the prompts to change the password((The default password is ``mangdang``)), and then install desktop.
Before installation, please make sure that raspberry pi is plugged into the network cable to access the Internet.
After installing the desktop, you only need to reboot it one time. The system will enter the desktop system by default.
Run ``$sudo apt install ubuntu-desktop``
.. image:: ../_static/installDesktop.jpg
:align: center
2. Initial Ubuntu server
########################################################
* The install time depends on your network speed, probably dozens of minutes.
Input "Y" to continue, and then input "startx" to boot up desktop at first time.
.. image:: ../_static/installDesktop2.jpg
:align: center
Reboot it only at first time, and then check the IP address, you can connect it later by SSH.
.. image:: ../_static/bootupDesktop4.jpg
:align: center
2. SSH into the pi from your computer and install the robot program.
######################################
Run ``ssh ubuntu@IP address`` (The default password is ``mangdang``)
.. image:: ../_static/ssh.png
:align: center
Make ``Robotics`` folder and download the source code.
Run ``git clone -b MiniPupper_V2 https://github.com/mangdangroboticsclub/QuadrupedRobot.git``
.. image:: ../_static/gitclonesourcecode.png
:align: center
Install requirements (on the Pi).
Run ``sudo bash Legacy/pre_install.sh``, the pre-install time depends on your network speed, maybe dezons of minutes, or several hours.
.. image:: ../_static/preInstall.png
:align: center
Insall the pupper robot program.
* ``cd QuadrupedRobot``
* ``sudo bash install.sh``
.. image:: ../_static/preInstall.png
:align: center
3. Power-cycle the robot
#############################
Unplug the battery, wait about 30 seconds, and then plug it back in.
4. Verify everything is working
###############################
#. If you just powered on the Pi, wait about 30 seconds until the green light stops blinking.
#. SSH into the robot
* Run ``ssh pi@10.0.0.xx (where xx is the IP address you chose for the robot)``
#. Check the status for the joystick service
* Run ``sudo systemctl status joystick``
* If you haven't yet connected the PS4 controller, it should say something like ::
pi@pupper(rw):~/StanfordQuadruped$ sudo systemctl status joystick
● joystick.service - Pupper Joystick service
Loaded: loaded (/home/pi/PupperCommand/joystick.service; enabled; vendor preset: enabled)
Active: active (running) since Sun 2020-03-01 06:57:20 GMT; 1s ago
Main PID: 5692 (python3)
Tasks: 3 (limit: 4035)
Memory: 7.1M
CGroup: /system.slice/joystick.service
├─5692 /usr/bin/python3 /home/pi/PupperCommand/joystick.py
└─5708 hcitool scan --flush
Mar 01 06:57:20 pupper systemd[1]: Started Pupper Joystick service.
Mar 01 06:57:21 pupper python3[5692]: [info][controller 1] Created devices /dev/input/js0 (joystick) /dev/input/event0 (evdev)
Mar 01 06:57:21 pupper python3[5692]: [info][bluetooth] Scanning for devices
#. Connect the PS4 controller to the Pi by putting it pairing mode.
* To put it into pairing mode, hold the share button and circular Playstation button at the same time until it starts making quick double flashes.
* If it starts making slow single flashes, hold the Playstation button down until it stops blinking and try again.
#. Once the controller is connected, check the status again
* Run ``sudo systemctl status joystick``
* It should now look something like::
pi@pupper(rw):~/StanfordQuadruped$ sudo systemctl status joystick
● joystick.service - Pupper Joystick service
Loaded: loaded (/home/pi/PupperCommand/joystick.service; enabled; vendor preset: enabled)
Active: active (running) since Sun 2020-03-01 06:57:20 GMT; 55s ago
Main PID: 5692 (python3)
Tasks: 2 (limit: 4035)
Memory: 7.3M
CGroup: /system.slice/joystick.service
└─5692 /usr/bin/python3 /home/pi/PupperCommand/joystick.py
Mar 01 06:57:20 pupper systemd[1]: Started Pupper Joystick service.
Mar 01 06:57:21 pupper python3[5692]: [info][controller 1] Created devices /dev/input/js0 (joystick) /dev/input/event0 (evdev)
Mar 01 06:57:21 pupper python3[5692]: [info][bluetooth] Scanning for devices
Mar 01 06:58:12 pupper python3[5692]: [info][bluetooth] Found device A0:AB:51:33:B5:A0
Mar 01 06:58:13 pupper python3[5692]: [info][controller 1] Connected to Bluetooth Controller (A0:AB:51:33:B5:A0)
Mar 01 06:58:14 pupper python3[5692]: running
Mar 01 06:58:14 pupper python3[5692]: [info][controller 1] Battery: 50%
* If the pi can't find the joystick after a minute or two, it's possible that the pi's bluetooth controller was never turned on. Run ``sudo hciconfig hci0 up`` to turn the radio on. Then restart the pi.
#. Check the status of the robot service
* Run ``sudo systemctl status robot``
* The output varies depending on the order of you running various programs, but just check that it doesn't have any red text saying that it failed.
* If it did fail, usually this fixes it: ``sudo systemctl restart robot``
7. Done!
#########
Continue to Calibration.
| 7,709 | reStructuredText | 40.675675 | 297 | 0.652354 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Mangdang/Example/display/demo.py | import os
import sys
from PIL import Image
sys.path.append("/home/ubuntu/Robotics/QuadrupedRobot")
sys.path.extend([os.path.join(root, name) for root, dirs, _ in os.walk("/home/ubuntu/Robotics/QuadrupedRobot") for name in dirs])
from Mangdang.LCD.ST7789 import ST7789
def main():
""" The demo for picture show
"""
# init st7789 device
disp = ST7789()
disp.begin()
disp.clear()
# show exaple picture
image=Image.open("./dog.png")
image.resize((320,240))
disp.display(image)
main()
| 527 | Python | 20.119999 | 129 | 0.671727 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Mangdang/PWMController/pwm-pca9685.c | // SPDX-License-Identifier: GPL-2.0-only
/*
* Driver for PCA9685 16-channel 12-bit PWM LED controller
*
* Copyright (C) 2013 Steffen Trumtrar <s.trumtrar@pengutronix.de>
* Copyright (C) 2015 Clemens Gruber <clemens.gruber@pqgruber.com>
*
* based on the pwm-twl-led.c driver
*/
#include <linux/acpi.h>
#include <linux/gpio/driver.h>
#include <linux/i2c.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/platform_device.h>
#include <linux/property.h>
#include <linux/pwm.h>
#include <linux/regmap.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/pm_runtime.h>
#include <linux/bitmap.h>
/*
* Because the PCA9685 has only one prescaler per chip, only the first channel
* that is enabled is allowed to change the prescale register.
* PWM channels requested afterwards must use a period that results in the same
* prescale setting as the one set by the first requested channel.
* GPIOs do not count as enabled PWMs as they are not using the prescaler.
*/
#define PCA9685_MODE1 0x00
#define PCA9685_MODE2 0x01
#define PCA9685_SUBADDR1 0x02
#define PCA9685_SUBADDR2 0x03
#define PCA9685_SUBADDR3 0x04
#define PCA9685_ALLCALLADDR 0x05
#define PCA9685_LEDX_ON_L 0x06
#define PCA9685_LEDX_ON_H 0x07
#define PCA9685_LEDX_OFF_L 0x08
#define PCA9685_LEDX_OFF_H 0x09
#define PCA9685_ALL_LED_ON_L 0xFA
#define PCA9685_ALL_LED_ON_H 0xFB
#define PCA9685_ALL_LED_OFF_L 0xFC
#define PCA9685_ALL_LED_OFF_H 0xFD
#define PCA9685_PRESCALE 0xFE
#define PCA9685_PRESCALE_MIN 0x03 /* => max. frequency of 1526 Hz */
#define PCA9685_PRESCALE_MAX 0xFF /* => min. frequency of 24 Hz */
#define PCA9685_COUNTER_RANGE 4096
#define PCA9685_OSC_CLOCK_MHZ 25 /* Internal oscillator with 25 MHz */
#define PCA9685_NUMREGS 0xFF
#define PCA9685_MAXCHAN 0x10
#define LED_FULL BIT(4)
#define MODE1_ALLCALL BIT(0)
#define MODE1_SUB3 BIT(1)
#define MODE1_SUB2 BIT(2)
#define MODE1_SUB1 BIT(3)
#define MODE1_SLEEP BIT(4)
#define MODE2_INVRT BIT(4)
#define MODE2_OUTDRV BIT(2)
#define LED_N_ON_H(N) (PCA9685_LEDX_ON_H + (4 * (N)))
#define LED_N_ON_L(N) (PCA9685_LEDX_ON_L + (4 * (N)))
#define LED_N_OFF_H(N) (PCA9685_LEDX_OFF_H + (4 * (N)))
#define LED_N_OFF_L(N) (PCA9685_LEDX_OFF_L + (4 * (N)))
#define REG_ON_H(C) ((C) >= PCA9685_MAXCHAN ? PCA9685_ALL_LED_ON_H : LED_N_ON_H((C)))
#define REG_ON_L(C) ((C) >= PCA9685_MAXCHAN ? PCA9685_ALL_LED_ON_L : LED_N_ON_L((C)))
#define REG_OFF_H(C) ((C) >= PCA9685_MAXCHAN ? PCA9685_ALL_LED_OFF_H : LED_N_OFF_H((C)))
#define REG_OFF_L(C) ((C) >= PCA9685_MAXCHAN ? PCA9685_ALL_LED_OFF_L : LED_N_OFF_L((C)))
struct pca9685 {
struct pwm_chip chip;
struct regmap *regmap;
struct mutex lock;
DECLARE_BITMAP(pwms_enabled, PCA9685_MAXCHAN + 1);
#if IS_ENABLED(CONFIG_GPIOLIB)
struct gpio_chip gpio;
DECLARE_BITMAP(pwms_inuse, PCA9685_MAXCHAN + 1);
#endif
};
static inline struct pca9685 *to_pca(struct pwm_chip *chip)
{
return container_of(chip, struct pca9685, chip);
}
/* This function is supposed to be called with the lock mutex held */
static bool pca9685_prescaler_can_change(struct pca9685 *pca, int channel)
{
/* No PWM enabled: Change allowed */
if (bitmap_empty(pca->pwms_enabled, PCA9685_MAXCHAN + 1))
return true;
/* More than one PWM enabled: Change not allowed */
if (bitmap_weight(pca->pwms_enabled, PCA9685_MAXCHAN + 1) > 1)
return false;
/*
* Only one PWM enabled: Change allowed if the PWM about to
* be changed is the one that is already enabled
*/
return test_bit(channel, pca->pwms_enabled);
}
/* Helper function to set the duty cycle ratio to duty/4096 (e.g. duty=2048 -> 50%) */
static void pca9685_pwm_set_duty(struct pca9685 *pca, int channel, unsigned int duty)
{
if (duty == 0) {
/* Set the full OFF bit, which has the highest precedence */
regmap_write(pca->regmap, REG_OFF_H(channel), LED_FULL);
} else if (duty >= PCA9685_COUNTER_RANGE) {
/* Set the full ON bit and clear the full OFF bit */
regmap_write(pca->regmap, REG_ON_H(channel), LED_FULL);
regmap_write(pca->regmap, REG_OFF_H(channel), 0);
} else {
/* Set OFF time (clears the full OFF bit) */
regmap_write(pca->regmap, REG_OFF_L(channel), duty & 0xff);
regmap_write(pca->regmap, REG_OFF_H(channel), (duty >> 8) & 0xf);
/* Clear the full ON bit */
regmap_write(pca->regmap, REG_ON_H(channel), 0);
}
}
static unsigned int pca9685_pwm_get_duty(struct pca9685 *pca, int channel)
{
unsigned int off_h = 0, val = 0;
if (WARN_ON(channel >= PCA9685_MAXCHAN)) {
/* HW does not support reading state of "all LEDs" channel */
return 0;
}
regmap_read(pca->regmap, LED_N_OFF_H(channel), &off_h);
if (off_h & LED_FULL) {
/* Full OFF bit is set */
return 0;
}
regmap_read(pca->regmap, LED_N_ON_H(channel), &val);
if (val & LED_FULL) {
/* Full ON bit is set */
return PCA9685_COUNTER_RANGE;
}
if (regmap_read(pca->regmap, LED_N_OFF_L(channel), &val)) {
/* Reset val to 0 in case reading LED_N_OFF_L failed */
val = 0;
}
return ((off_h & 0xf) << 8) | (val & 0xff);
}
#if IS_ENABLED(CONFIG_GPIOLIB)
static bool pca9685_pwm_test_and_set_inuse(struct pca9685 *pca, int pwm_idx)
{
bool is_inuse;
mutex_lock(&pca->lock);
if (pwm_idx >= PCA9685_MAXCHAN) {
/*
* "All LEDs" channel:
* pretend already in use if any of the PWMs are requested
*/
if (!bitmap_empty(pca->pwms_inuse, PCA9685_MAXCHAN)) {
is_inuse = true;
goto out;
}
} else {
/*
* Regular channel:
* pretend already in use if the "all LEDs" channel is requested
*/
if (test_bit(PCA9685_MAXCHAN, pca->pwms_inuse)) {
is_inuse = true;
goto out;
}
}
is_inuse = test_and_set_bit(pwm_idx, pca->pwms_inuse);
out:
mutex_unlock(&pca->lock);
return is_inuse;
}
static void pca9685_pwm_clear_inuse(struct pca9685 *pca, int pwm_idx)
{
mutex_lock(&pca->lock);
clear_bit(pwm_idx, pca->pwms_inuse);
mutex_unlock(&pca->lock);
}
static int pca9685_pwm_gpio_request(struct gpio_chip *gpio, unsigned int offset)
{
struct pca9685 *pca = gpiochip_get_data(gpio);
if (pca9685_pwm_test_and_set_inuse(pca, offset))
return -EBUSY;
pm_runtime_get_sync(pca->chip.dev);
return 0;
}
static int pca9685_pwm_gpio_get(struct gpio_chip *gpio, unsigned int offset)
{
struct pca9685 *pca = gpiochip_get_data(gpio);
return pca9685_pwm_get_duty(pca, offset) != 0;
}
static void pca9685_pwm_gpio_set(struct gpio_chip *gpio, unsigned int offset,
int value)
{
struct pca9685 *pca = gpiochip_get_data(gpio);
pca9685_pwm_set_duty(pca, offset, value ? PCA9685_COUNTER_RANGE : 0);
}
static void pca9685_pwm_gpio_free(struct gpio_chip *gpio, unsigned int offset)
{
struct pca9685 *pca = gpiochip_get_data(gpio);
pca9685_pwm_set_duty(pca, offset, 0);
pm_runtime_put(pca->chip.dev);
pca9685_pwm_clear_inuse(pca, offset);
}
static int pca9685_pwm_gpio_get_direction(struct gpio_chip *chip,
unsigned int offset)
{
/* Always out */
return GPIO_LINE_DIRECTION_OUT;
}
static int pca9685_pwm_gpio_direction_input(struct gpio_chip *gpio,
unsigned int offset)
{
return -EINVAL;
}
static int pca9685_pwm_gpio_direction_output(struct gpio_chip *gpio,
unsigned int offset, int value)
{
pca9685_pwm_gpio_set(gpio, offset, value);
return 0;
}
/*
* The PCA9685 has a bit for turning the PWM output full off or on. Some
* boards like Intel Galileo actually uses these as normal GPIOs so we
* expose a GPIO chip here which can exclusively take over the underlying
* PWM channel.
*/
static int pca9685_pwm_gpio_probe(struct pca9685 *pca)
{
struct device *dev = pca->chip.dev;
pca->gpio.label = dev_name(dev);
pca->gpio.parent = dev;
pca->gpio.request = pca9685_pwm_gpio_request;
pca->gpio.free = pca9685_pwm_gpio_free;
pca->gpio.get_direction = pca9685_pwm_gpio_get_direction;
pca->gpio.direction_input = pca9685_pwm_gpio_direction_input;
pca->gpio.direction_output = pca9685_pwm_gpio_direction_output;
pca->gpio.get = pca9685_pwm_gpio_get;
pca->gpio.set = pca9685_pwm_gpio_set;
pca->gpio.base = -1;
pca->gpio.ngpio = PCA9685_MAXCHAN;
pca->gpio.can_sleep = true;
return devm_gpiochip_add_data(dev, &pca->gpio, pca);
}
#else
static inline bool pca9685_pwm_test_and_set_inuse(struct pca9685 *pca,
int pwm_idx)
{
return false;
}
static inline void
pca9685_pwm_clear_inuse(struct pca9685 *pca, int pwm_idx)
{
}
static inline int pca9685_pwm_gpio_probe(struct pca9685 *pca)
{
return 0;
}
#endif
static void pca9685_set_sleep_mode(struct pca9685 *pca, bool enable)
{
regmap_update_bits(pca->regmap, PCA9685_MODE1,
MODE1_SLEEP, enable ? MODE1_SLEEP : 0);
if (!enable) {
/* Wait 500us for the oscillator to be back up */
udelay(500);
}
}
static int __pca9685_pwm_apply(struct pwm_chip *chip, struct pwm_device *pwm,
const struct pwm_state *state)
{
struct pca9685 *pca = to_pca(chip);
unsigned long long duty, prescale;
unsigned int val = 0;
if (state->polarity != PWM_POLARITY_NORMAL)
return -EINVAL;
prescale = DIV_ROUND_CLOSEST_ULL(PCA9685_OSC_CLOCK_MHZ * state->period,
PCA9685_COUNTER_RANGE * 1000) - 1;
if (prescale < PCA9685_PRESCALE_MIN || prescale > PCA9685_PRESCALE_MAX) {
dev_err(chip->dev, "pwm not changed: period out of bounds!\n");
return -EINVAL;
}
if (!state->enabled) {
pca9685_pwm_set_duty(pca, pwm->hwpwm, 0);
return 0;
}
regmap_read(pca->regmap, PCA9685_PRESCALE, &val);
if (prescale != val) {
if (!pca9685_prescaler_can_change(pca, pwm->hwpwm)) {
dev_err(chip->dev,
"pwm not changed: periods of enabled pwms must match!\n");
return -EBUSY;
}
/*
* Putting the chip briefly into SLEEP mode
* at this point won't interfere with the
* pm_runtime framework, because the pm_runtime
* state is guaranteed active here.
*/
/* Put chip into sleep mode */
pca9685_set_sleep_mode(pca, true);
/* Change the chip-wide output frequency */
regmap_write(pca->regmap, PCA9685_PRESCALE, prescale);
/* Wake the chip up */
pca9685_set_sleep_mode(pca, false);
}
duty = PCA9685_COUNTER_RANGE * state->duty_cycle;
duty = DIV_ROUND_UP_ULL(duty, state->period);
pca9685_pwm_set_duty(pca, pwm->hwpwm, duty);
return 0;
}
static int pca9685_pwm_apply(struct pwm_chip *chip, struct pwm_device *pwm,
const struct pwm_state *state)
{
struct pca9685 *pca = to_pca(chip);
int ret;
mutex_lock(&pca->lock);
ret = __pca9685_pwm_apply(chip, pwm, state);
if (ret == 0) {
if (state->enabled)
set_bit(pwm->hwpwm, pca->pwms_enabled);
else
clear_bit(pwm->hwpwm, pca->pwms_enabled);
}
mutex_unlock(&pca->lock);
return ret;
}
static void pca9685_pwm_get_state(struct pwm_chip *chip, struct pwm_device *pwm,
struct pwm_state *state)
{
struct pca9685 *pca = to_pca(chip);
unsigned long long duty;
unsigned int val = 0;
/* Calculate (chip-wide) period from prescale value */
regmap_read(pca->regmap, PCA9685_PRESCALE, &val);
/*
* PCA9685_OSC_CLOCK_MHZ is 25, i.e. an integer divider of 1000.
* The following calculation is therefore only a multiplication
* and we are not losing precision.
*/
state->period = (PCA9685_COUNTER_RANGE * 1000 / PCA9685_OSC_CLOCK_MHZ) *
(val + 1);
/* The (per-channel) polarity is fixed */
state->polarity = PWM_POLARITY_NORMAL;
if (pwm->hwpwm >= PCA9685_MAXCHAN) {
/*
* The "all LEDs" channel does not support HW readout
* Return 0 and disabled for backwards compatibility
*/
state->duty_cycle = 0;
state->enabled = false;
return;
}
state->enabled = true;
duty = pca9685_pwm_get_duty(pca, pwm->hwpwm);
state->duty_cycle = DIV_ROUND_DOWN_ULL(duty * state->period, PCA9685_COUNTER_RANGE);
}
static int pca9685_pwm_request(struct pwm_chip *chip, struct pwm_device *pwm)
{
struct pca9685 *pca = to_pca(chip);
if (pca9685_pwm_test_and_set_inuse(pca, pwm->hwpwm))
return -EBUSY;
if (pwm->hwpwm < PCA9685_MAXCHAN) {
/* PWMs - except the "all LEDs" channel - default to enabled */
mutex_lock(&pca->lock);
set_bit(pwm->hwpwm, pca->pwms_enabled);
mutex_unlock(&pca->lock);
}
pm_runtime_get_sync(chip->dev);
return 0;
}
static void pca9685_pwm_free(struct pwm_chip *chip, struct pwm_device *pwm)
{
struct pca9685 *pca = to_pca(chip);
mutex_lock(&pca->lock);
pca9685_pwm_set_duty(pca, pwm->hwpwm, 0);
clear_bit(pwm->hwpwm, pca->pwms_enabled);
mutex_unlock(&pca->lock);
pm_runtime_put(chip->dev);
pca9685_pwm_clear_inuse(pca, pwm->hwpwm);
}
static const struct pwm_ops pca9685_pwm_ops = {
.apply = pca9685_pwm_apply,
.get_state = pca9685_pwm_get_state,
.request = pca9685_pwm_request,
.free = pca9685_pwm_free,
.owner = THIS_MODULE,
};
static const struct regmap_config pca9685_regmap_i2c_config = {
.reg_bits = 8,
.val_bits = 8,
.max_register = PCA9685_NUMREGS,
.cache_type = REGCACHE_NONE,
};
static int pca9685_pwm_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct pca9685 *pca;
unsigned int reg;
int ret;
pca = devm_kzalloc(&client->dev, sizeof(*pca), GFP_KERNEL);
if (!pca)
return -ENOMEM;
pca->regmap = devm_regmap_init_i2c(client, &pca9685_regmap_i2c_config);
if (IS_ERR(pca->regmap)) {
ret = PTR_ERR(pca->regmap);
dev_err(&client->dev, "Failed to initialize register map: %d\n",
ret);
return ret;
}
i2c_set_clientdata(client, pca);
mutex_init(&pca->lock);
regmap_read(pca->regmap, PCA9685_MODE2, ®);
if (device_property_read_bool(&client->dev, "invert"))
reg |= MODE2_INVRT;
else
reg &= ~MODE2_INVRT;
if (device_property_read_bool(&client->dev, "open-drain"))
reg &= ~MODE2_OUTDRV;
else
reg |= MODE2_OUTDRV;
regmap_write(pca->regmap, PCA9685_MODE2, reg);
/* Disable all LED ALLCALL and SUBx addresses to avoid bus collisions */
regmap_read(pca->regmap, PCA9685_MODE1, ®);
reg &= ~(MODE1_ALLCALL | MODE1_SUB1 | MODE1_SUB2 | MODE1_SUB3);
regmap_write(pca->regmap, PCA9685_MODE1, reg);
/* Reset OFF registers to POR default */
regmap_write(pca->regmap, PCA9685_ALL_LED_OFF_L, LED_FULL);
regmap_write(pca->regmap, PCA9685_ALL_LED_OFF_H, LED_FULL);
pca->chip.ops = &pca9685_pwm_ops;
/* Add an extra channel for ALL_LED */
pca->chip.npwm = PCA9685_MAXCHAN + 1;
pca->chip.dev = &client->dev;
ret = pwmchip_add(&pca->chip);
if (ret < 0)
return ret;
ret = pca9685_pwm_gpio_probe(pca);
if (ret < 0) {
pwmchip_remove(&pca->chip);
return ret;
}
pm_runtime_enable(&client->dev);
if (pm_runtime_enabled(&client->dev)) {
/*
* Although the chip comes out of power-up in the sleep state,
* we force it to sleep in case it was woken up before
*/
pca9685_set_sleep_mode(pca, true);
pm_runtime_set_suspended(&client->dev);
} else {
/* Wake the chip up if runtime PM is disabled */
pca9685_set_sleep_mode(pca, false);
}
return 0;
}
static int pca9685_pwm_remove(struct i2c_client *client)
{
struct pca9685 *pca = i2c_get_clientdata(client);
int ret;
//ret = pwmchip_remove(&pca->chip);
pwmchip_remove(&pca->chip);
//if (ret)
// return ret;
if (!pm_runtime_enabled(&client->dev)) {
/* Put chip in sleep state if runtime PM is disabled */
pca9685_set_sleep_mode(pca, true);
}
pm_runtime_disable(&client->dev);
return 0;
}
static int __maybe_unused pca9685_pwm_runtime_suspend(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct pca9685 *pca = i2c_get_clientdata(client);
pca9685_set_sleep_mode(pca, true);
return 0;
}
static int __maybe_unused pca9685_pwm_runtime_resume(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct pca9685 *pca = i2c_get_clientdata(client);
pca9685_set_sleep_mode(pca, false);
return 0;
}
static const struct i2c_device_id pca9685_id[] = {
{ "pca9685", 0 },
{ /* sentinel */ },
};
MODULE_DEVICE_TABLE(i2c, pca9685_id);
#ifdef CONFIG_ACPI
static const struct acpi_device_id pca9685_acpi_ids[] = {
{ "INT3492", 0 },
{ /* sentinel */ },
};
MODULE_DEVICE_TABLE(acpi, pca9685_acpi_ids);
#endif
#ifdef CONFIG_OF
static const struct of_device_id pca9685_dt_ids[] = {
{ .compatible = "nxp,pca9685-pwm", },
{ /* sentinel */ }
};
MODULE_DEVICE_TABLE(of, pca9685_dt_ids);
#endif
static const struct dev_pm_ops pca9685_pwm_pm = {
SET_RUNTIME_PM_OPS(pca9685_pwm_runtime_suspend,
pca9685_pwm_runtime_resume, NULL)
};
static struct i2c_driver pca9685_i2c_driver = {
.driver = {
.name = "pca9685-pwm",
.acpi_match_table = ACPI_PTR(pca9685_acpi_ids),
.of_match_table = of_match_ptr(pca9685_dt_ids),
.pm = &pca9685_pwm_pm,
},
.probe = pca9685_pwm_probe,
.remove = pca9685_pwm_remove,
.id_table = pca9685_id,
};
module_i2c_driver(pca9685_i2c_driver);
MODULE_AUTHOR("Steffen Trumtrar <s.trumtrar@pengutronix.de>");
MODULE_DESCRIPTION("PWM driver for PCA9685");
MODULE_LICENSE("GPL");
| 16,597 | C | 25.901134 | 88 | 0.685124 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Mangdang/EEPROM/at24.c | // SPDX-License-Identifier: GPL-2.0-or-later
/*
* at24.c - handle most I2C EEPROMs
*
* Copyright (C) 2005-2007 David Brownell
* Copyright (C) 2008 Wolfram Sang, Pengutronix
*/
#include <linux/acpi.h>
#include <linux/bitops.h>
#include <linux/capability.h>
#include <linux/delay.h>
#include <linux/i2c.h>
#include <linux/init.h>
#include <linux/jiffies.h>
#include <linux/kernel.h>
#include <linux/mod_devicetable.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/nvmem-provider.h>
#include <linux/of_device.h>
#include <linux/pm_runtime.h>
#include <linux/property.h>
#include <linux/regmap.h>
#include <linux/regulator/consumer.h>
#include <linux/slab.h>
/* Address pointer is 16 bit. */
#define AT24_FLAG_ADDR16 BIT(7)
/* sysfs-entry will be read-only. */
#define AT24_FLAG_READONLY BIT(6)
/* sysfs-entry will be world-readable. */
#define AT24_FLAG_IRUGO BIT(5)
/* Take always 8 addresses (24c00). */
#define AT24_FLAG_TAKE8ADDR BIT(4)
/* Factory-programmed serial number. */
#define AT24_FLAG_SERIAL BIT(3)
/* Factory-programmed mac address. */
#define AT24_FLAG_MAC BIT(2)
/* Does not auto-rollover reads to the next slave address. */
#define AT24_FLAG_NO_RDROL BIT(1)
/*
* I2C EEPROMs from most vendors are inexpensive and mostly interchangeable.
* Differences between different vendor product lines (like Atmel AT24C or
* MicroChip 24LC, etc) won't much matter for typical read/write access.
* There are also I2C RAM chips, likewise interchangeable. One example
* would be the PCF8570, which acts like a 24c02 EEPROM (256 bytes).
*
* However, misconfiguration can lose data. "Set 16-bit memory address"
* to a part with 8-bit addressing will overwrite data. Writing with too
* big a page size also loses data. And it's not safe to assume that the
* conventional addresses 0x50..0x57 only hold eeproms; a PCF8563 RTC
* uses 0x51, for just one example.
*
* Accordingly, explicit board-specific configuration data should be used
* in almost all cases. (One partial exception is an SMBus used to access
* "SPD" data for DRAM sticks. Those only use 24c02 EEPROMs.)
*
* So this driver uses "new style" I2C driver binding, expecting to be
* told what devices exist. That may be in arch/X/mach-Y/board-Z.c or
* similar kernel-resident tables; or, configuration data coming from
* a bootloader.
*
* Other than binding model, current differences from "eeprom" driver are
* that this one handles write access and isn't restricted to 24c02 devices.
* It also handles larger devices (32 kbit and up) with two-byte addresses,
* which won't work on pure SMBus systems.
*/
struct at24_client {
struct i2c_client *client;
struct regmap *regmap;
};
struct at24_data {
/*
* Lock protects against activities from other Linux tasks,
* but not from changes by other I2C masters.
*/
struct mutex lock;
unsigned int write_max;
unsigned int num_addresses;
unsigned int offset_adj;
u32 byte_len;
u16 page_size;
u8 flags;
struct nvmem_device *nvmem;
struct regulator *vcc_reg;
void (*read_post)(unsigned int off, char *buf, size_t count);
/*
* Some chips tie up multiple I2C addresses; dummy devices reserve
* them for us, and we'll use them with SMBus calls.
*/
struct at24_client client[];
};
/*
* This parameter is to help this driver avoid blocking other drivers out
* of I2C for potentially troublesome amounts of time. With a 100 kHz I2C
* clock, one 256 byte read takes about 1/43 second which is excessive;
* but the 1/170 second it takes at 400 kHz may be quite reasonable; and
* at 1 MHz (Fm+) a 1/430 second delay could easily be invisible.
*
* This value is forced to be a power of two so that writes align on pages.
*/
static unsigned int at24_io_limit = 128;
module_param_named(io_limit, at24_io_limit, uint, 0);
MODULE_PARM_DESC(at24_io_limit, "Maximum bytes per I/O (default 128)");
/*
* Specs often allow 5 msec for a page write, sometimes 20 msec;
* it's important to recover from write timeouts.
*/
static unsigned int at24_write_timeout = 25;
module_param_named(write_timeout, at24_write_timeout, uint, 0);
MODULE_PARM_DESC(at24_write_timeout, "Time (in ms) to try writes (default 25)");
struct at24_chip_data {
u32 byte_len;
u8 flags;
void (*read_post)(unsigned int off, char *buf, size_t count);
};
#define AT24_CHIP_DATA(_name, _len, _flags) \
static const struct at24_chip_data _name = { \
.byte_len = _len, .flags = _flags, \
}
#define AT24_CHIP_DATA_CB(_name, _len, _flags, _read_post) \
static const struct at24_chip_data _name = { \
.byte_len = _len, .flags = _flags, \
.read_post = _read_post, \
}
static void at24_read_post_vaio(unsigned int off, char *buf, size_t count)
{
int i;
if (capable(CAP_SYS_ADMIN))
return;
/*
* Hide VAIO private settings to regular users:
* - BIOS passwords: bytes 0x00 to 0x0f
* - UUID: bytes 0x10 to 0x1f
* - Serial number: 0xc0 to 0xdf
*/
for (i = 0; i < count; i++) {
if ((off + i <= 0x1f) ||
(off + i >= 0xc0 && off + i <= 0xdf))
buf[i] = 0;
}
}
/* needs 8 addresses as A0-A2 are ignored */
AT24_CHIP_DATA(at24_data_24c00, 128 / 8, AT24_FLAG_TAKE8ADDR);
/* old variants can't be handled with this generic entry! */
AT24_CHIP_DATA(at24_data_24c01, 1024 / 8, 0);
AT24_CHIP_DATA(at24_data_24cs01, 16,
AT24_FLAG_SERIAL | AT24_FLAG_READONLY);
AT24_CHIP_DATA(at24_data_24c02, 2048 / 8, 0);
AT24_CHIP_DATA(at24_data_24cs02, 16,
AT24_FLAG_SERIAL | AT24_FLAG_READONLY);
AT24_CHIP_DATA(at24_data_24mac402, 48 / 8,
AT24_FLAG_MAC | AT24_FLAG_READONLY);
AT24_CHIP_DATA(at24_data_24mac602, 64 / 8,
AT24_FLAG_MAC | AT24_FLAG_READONLY);
/* spd is a 24c02 in memory DIMMs */
AT24_CHIP_DATA(at24_data_spd, 2048 / 8,
AT24_FLAG_READONLY | AT24_FLAG_IRUGO);
/* 24c02_vaio is a 24c02 on some Sony laptops */
AT24_CHIP_DATA_CB(at24_data_24c02_vaio, 2048 / 8,
AT24_FLAG_READONLY | AT24_FLAG_IRUGO,
at24_read_post_vaio);
AT24_CHIP_DATA(at24_data_24c04, 4096 / 8, 0);
AT24_CHIP_DATA(at24_data_24cs04, 16,
AT24_FLAG_SERIAL | AT24_FLAG_READONLY);
/* 24rf08 quirk is handled at i2c-core */
AT24_CHIP_DATA(at24_data_24c08, 8192 / 8, 0);
AT24_CHIP_DATA(at24_data_24cs08, 16,
AT24_FLAG_SERIAL | AT24_FLAG_READONLY);
AT24_CHIP_DATA(at24_data_24c16, 16384 / 8, 0);
AT24_CHIP_DATA(at24_data_24cs16, 16,
AT24_FLAG_SERIAL | AT24_FLAG_READONLY);
AT24_CHIP_DATA(at24_data_24c32, 32768 / 8, AT24_FLAG_ADDR16);
AT24_CHIP_DATA(at24_data_24cs32, 16,
AT24_FLAG_ADDR16 | AT24_FLAG_SERIAL | AT24_FLAG_READONLY);
AT24_CHIP_DATA(at24_data_24c64, 65536 / 8, AT24_FLAG_ADDR16);
AT24_CHIP_DATA(at24_data_24cs64, 16,
AT24_FLAG_ADDR16 | AT24_FLAG_SERIAL | AT24_FLAG_READONLY);
AT24_CHIP_DATA(at24_data_24c128, 131072 / 8, AT24_FLAG_ADDR16);
AT24_CHIP_DATA(at24_data_24c256, 262144 / 8, AT24_FLAG_ADDR16);
AT24_CHIP_DATA(at24_data_24c512, 524288 / 8, AT24_FLAG_ADDR16);
AT24_CHIP_DATA(at24_data_24c1024, 1048576 / 8, AT24_FLAG_ADDR16);
AT24_CHIP_DATA(at24_data_24c2048, 2097152 / 8, AT24_FLAG_ADDR16);
/* identical to 24c08 ? */
AT24_CHIP_DATA(at24_data_INT3499, 8192 / 8, 0);
static const struct i2c_device_id at24_ids[] = {
{ "24c00", (kernel_ulong_t)&at24_data_24c00 },
{ "24c01", (kernel_ulong_t)&at24_data_24c01 },
{ "24cs01", (kernel_ulong_t)&at24_data_24cs01 },
{ "24c02", (kernel_ulong_t)&at24_data_24c02 },
{ "24cs02", (kernel_ulong_t)&at24_data_24cs02 },
{ "24mac402", (kernel_ulong_t)&at24_data_24mac402 },
{ "24mac602", (kernel_ulong_t)&at24_data_24mac602 },
{ "spd", (kernel_ulong_t)&at24_data_spd },
{ "24c02-vaio", (kernel_ulong_t)&at24_data_24c02_vaio },
{ "24c04", (kernel_ulong_t)&at24_data_24c04 },
{ "24cs04", (kernel_ulong_t)&at24_data_24cs04 },
{ "24c08", (kernel_ulong_t)&at24_data_24c08 },
{ "24cs08", (kernel_ulong_t)&at24_data_24cs08 },
{ "24c16", (kernel_ulong_t)&at24_data_24c16 },
{ "24cs16", (kernel_ulong_t)&at24_data_24cs16 },
{ "24c32", (kernel_ulong_t)&at24_data_24c32 },
{ "24cs32", (kernel_ulong_t)&at24_data_24cs32 },
{ "24c64", (kernel_ulong_t)&at24_data_24c64 },
{ "24cs64", (kernel_ulong_t)&at24_data_24cs64 },
{ "24c128", (kernel_ulong_t)&at24_data_24c128 },
{ "24c256", (kernel_ulong_t)&at24_data_24c256 },
{ "24c512", (kernel_ulong_t)&at24_data_24c512 },
{ "24c1024", (kernel_ulong_t)&at24_data_24c1024 },
{ "24c2048", (kernel_ulong_t)&at24_data_24c2048 },
{ "at24", 0 },
{ /* END OF LIST */ }
};
MODULE_DEVICE_TABLE(i2c, at24_ids);
static const struct of_device_id at24_of_match[] = {
{ .compatible = "atmel,24c00", .data = &at24_data_24c00 },
{ .compatible = "atmel,24c01", .data = &at24_data_24c01 },
{ .compatible = "atmel,24cs01", .data = &at24_data_24cs01 },
{ .compatible = "atmel,24c02", .data = &at24_data_24c02 },
{ .compatible = "atmel,24cs02", .data = &at24_data_24cs02 },
{ .compatible = "atmel,24mac402", .data = &at24_data_24mac402 },
{ .compatible = "atmel,24mac602", .data = &at24_data_24mac602 },
{ .compatible = "atmel,spd", .data = &at24_data_spd },
{ .compatible = "atmel,24c04", .data = &at24_data_24c04 },
{ .compatible = "atmel,24cs04", .data = &at24_data_24cs04 },
{ .compatible = "atmel,24c08", .data = &at24_data_24c08 },
{ .compatible = "atmel,24cs08", .data = &at24_data_24cs08 },
{ .compatible = "atmel,24c16", .data = &at24_data_24c16 },
{ .compatible = "atmel,24cs16", .data = &at24_data_24cs16 },
{ .compatible = "atmel,24c32", .data = &at24_data_24c32 },
{ .compatible = "atmel,24cs32", .data = &at24_data_24cs32 },
{ .compatible = "atmel,24c64", .data = &at24_data_24c64 },
{ .compatible = "atmel,24cs64", .data = &at24_data_24cs64 },
{ .compatible = "atmel,24c128", .data = &at24_data_24c128 },
{ .compatible = "atmel,24c256", .data = &at24_data_24c256 },
{ .compatible = "atmel,24c512", .data = &at24_data_24c512 },
{ .compatible = "atmel,24c1024", .data = &at24_data_24c1024 },
{ .compatible = "atmel,24c2048", .data = &at24_data_24c2048 },
{ /* END OF LIST */ },
};
MODULE_DEVICE_TABLE(of, at24_of_match);
static const struct acpi_device_id __maybe_unused at24_acpi_ids[] = {
{ "INT3499", (kernel_ulong_t)&at24_data_INT3499 },
{ "TPF0001", (kernel_ulong_t)&at24_data_24c1024 },
{ /* END OF LIST */ }
};
MODULE_DEVICE_TABLE(acpi, at24_acpi_ids);
/*
* This routine supports chips which consume multiple I2C addresses. It
* computes the addressing information to be used for a given r/w request.
* Assumes that sanity checks for offset happened at sysfs-layer.
*
* Slave address and byte offset derive from the offset. Always
* set the byte address; on a multi-master board, another master
* may have changed the chip's "current" address pointer.
*/
static struct at24_client *at24_translate_offset(struct at24_data *at24,
unsigned int *offset)
{
unsigned int i;
if (at24->flags & AT24_FLAG_ADDR16) {
i = *offset >> 16;
*offset &= 0xffff;
} else {
i = *offset >> 8;
*offset &= 0xff;
}
return &at24->client[i];
}
static struct device *at24_base_client_dev(struct at24_data *at24)
{
return &at24->client[0].client->dev;
}
static size_t at24_adjust_read_count(struct at24_data *at24,
unsigned int offset, size_t count)
{
unsigned int bits;
size_t remainder;
/*
* In case of multi-address chips that don't rollover reads to
* the next slave address: truncate the count to the slave boundary,
* so that the read never straddles slaves.
*/
if (at24->flags & AT24_FLAG_NO_RDROL) {
bits = (at24->flags & AT24_FLAG_ADDR16) ? 16 : 8;
remainder = BIT(bits) - offset;
if (count > remainder)
count = remainder;
}
if (count > at24_io_limit)
count = at24_io_limit;
return count;
}
static ssize_t at24_regmap_read(struct at24_data *at24, char *buf,
unsigned int offset, size_t count)
{
unsigned long timeout, read_time;
struct at24_client *at24_client;
struct i2c_client *client;
struct regmap *regmap;
int ret;
at24_client = at24_translate_offset(at24, &offset);
regmap = at24_client->regmap;
client = at24_client->client;
count = at24_adjust_read_count(at24, offset, count);
/* adjust offset for mac and serial read ops */
offset += at24->offset_adj;
timeout = jiffies + msecs_to_jiffies(at24_write_timeout);
do {
/*
* The timestamp shall be taken before the actual operation
* to avoid a premature timeout in case of high CPU load.
*/
read_time = jiffies;
ret = regmap_bulk_read(regmap, offset, buf, count);
dev_dbg(&client->dev, "read %zu@%d --> %d (%ld)\n",
count, offset, ret, jiffies);
if (!ret)
return count;
usleep_range(1000, 1500);
} while (time_before(read_time, timeout));
return -ETIMEDOUT;
}
/*
* Note that if the hardware write-protect pin is pulled high, the whole
* chip is normally write protected. But there are plenty of product
* variants here, including OTP fuses and partial chip protect.
*
* We only use page mode writes; the alternative is sloooow. These routines
* write at most one page.
*/
static size_t at24_adjust_write_count(struct at24_data *at24,
unsigned int offset, size_t count)
{
unsigned int next_page;
/* write_max is at most a page */
if (count > at24->write_max)
count = at24->write_max;
/* Never roll over backwards, to the start of this page */
next_page = roundup(offset + 1, at24->page_size);
if (offset + count > next_page)
count = next_page - offset;
return count;
}
static ssize_t at24_regmap_write(struct at24_data *at24, const char *buf,
unsigned int offset, size_t count)
{
unsigned long timeout, write_time;
struct at24_client *at24_client;
struct i2c_client *client;
struct regmap *regmap;
int ret;
at24_client = at24_translate_offset(at24, &offset);
regmap = at24_client->regmap;
client = at24_client->client;
count = at24_adjust_write_count(at24, offset, count);
timeout = jiffies + msecs_to_jiffies(at24_write_timeout);
do {
/*
* The timestamp shall be taken before the actual operation
* to avoid a premature timeout in case of high CPU load.
*/
write_time = jiffies;
ret = regmap_bulk_write(regmap, offset, buf, count);
dev_dbg(&client->dev, "write %zu@%d --> %d (%ld)\n",
count, offset, ret, jiffies);
if (!ret)
return count;
usleep_range(1000, 1500);
} while (time_before(write_time, timeout));
return -ETIMEDOUT;
}
static int at24_read(void *priv, unsigned int off, void *val, size_t count)
{
struct at24_data *at24;
struct device *dev;
char *buf = val;
int i, ret;
at24 = priv;
dev = at24_base_client_dev(at24);
if (unlikely(!count))
return count;
if (off + count > at24->byte_len)
return -EINVAL;
ret = pm_runtime_get_sync(dev);
if (ret < 0) {
pm_runtime_put_noidle(dev);
return ret;
}
/*
* Read data from chip, protecting against concurrent updates
* from this host, but not from other I2C masters.
*/
mutex_lock(&at24->lock);
for (i = 0; count; i += ret, count -= ret) {
ret = at24_regmap_read(at24, buf + i, off + i, count);
if (ret < 0) {
mutex_unlock(&at24->lock);
pm_runtime_put(dev);
return ret;
}
}
mutex_unlock(&at24->lock);
pm_runtime_put(dev);
if (unlikely(at24->read_post))
at24->read_post(off, buf, i);
return 0;
}
static int at24_write(void *priv, unsigned int off, void *val, size_t count)
{
struct at24_data *at24;
struct device *dev;
char *buf = val;
int ret;
at24 = priv;
dev = at24_base_client_dev(at24);
if (unlikely(!count))
return -EINVAL;
if (off + count > at24->byte_len)
return -EINVAL;
ret = pm_runtime_get_sync(dev);
if (ret < 0) {
pm_runtime_put_noidle(dev);
return ret;
}
/*
* Write data to chip, protecting against concurrent updates
* from this host, but not from other I2C masters.
*/
mutex_lock(&at24->lock);
while (count) {
ret = at24_regmap_write(at24, buf, off, count);
if (ret < 0) {
mutex_unlock(&at24->lock);
pm_runtime_put(dev);
return ret;
}
buf += ret;
off += ret;
count -= ret;
}
mutex_unlock(&at24->lock);
pm_runtime_put(dev);
return 0;
}
static const struct at24_chip_data *at24_get_chip_data(struct device *dev)
{
struct device_node *of_node = dev->of_node;
const struct at24_chip_data *cdata;
const struct i2c_device_id *id;
id = i2c_match_id(at24_ids, to_i2c_client(dev));
/*
* The I2C core allows OF nodes compatibles to match against the
* I2C device ID table as a fallback, so check not only if an OF
* node is present but also if it matches an OF device ID entry.
*/
if (of_node && of_match_device(at24_of_match, dev))
cdata = of_device_get_match_data(dev);
else if (id)
cdata = (void *)id->driver_data;
else
cdata = acpi_device_get_match_data(dev);
if (!cdata)
return ERR_PTR(-ENODEV);
return cdata;
}
static int at24_make_dummy_client(struct at24_data *at24, unsigned int index,
struct regmap_config *regmap_config)
{
struct i2c_client *base_client, *dummy_client;
struct regmap *regmap;
struct device *dev;
base_client = at24->client[0].client;
dev = &base_client->dev;
dummy_client = devm_i2c_new_dummy_device(dev, base_client->adapter,
base_client->addr + index);
if (IS_ERR(dummy_client))
return PTR_ERR(dummy_client);
regmap = devm_regmap_init_i2c(dummy_client, regmap_config);
if (IS_ERR(regmap))
return PTR_ERR(regmap);
at24->client[index].client = dummy_client;
at24->client[index].regmap = regmap;
return 0;
}
static unsigned int at24_get_offset_adj(u8 flags, unsigned int byte_len)
{
if (flags & AT24_FLAG_MAC) {
/* EUI-48 starts from 0x9a, EUI-64 from 0x98 */
return 0xa0 - byte_len;
} else if (flags & AT24_FLAG_SERIAL && flags & AT24_FLAG_ADDR16) {
/*
* For 16 bit address pointers, the word address must contain
* a '10' sequence in bits 11 and 10 regardless of the
* intended position of the address pointer.
*/
return 0x0800;
} else if (flags & AT24_FLAG_SERIAL) {
/*
* Otherwise the word address must begin with a '10' sequence,
* regardless of the intended address.
*/
return 0x0080;
} else {
return 0;
}
}
static int at24_probe(struct i2c_client *client)
{
struct regmap_config regmap_config = { };
struct nvmem_config nvmem_config = { };
u32 byte_len, page_size, flags, addrw;
const struct at24_chip_data *cdata;
struct device *dev = &client->dev;
bool i2c_fn_i2c, i2c_fn_block;
unsigned int i, num_addresses;
struct at24_data *at24;
struct regmap *regmap;
bool writable;
u8 test_byte;
int err;
i2c_fn_i2c = i2c_check_functionality(client->adapter, I2C_FUNC_I2C);
i2c_fn_block = i2c_check_functionality(client->adapter,
I2C_FUNC_SMBUS_WRITE_I2C_BLOCK);
cdata = at24_get_chip_data(dev);
if (IS_ERR(cdata))
return PTR_ERR(cdata);
err = device_property_read_u32(dev, "pagesize", &page_size);
if (err)
/*
* This is slow, but we can't know all eeproms, so we better
* play safe. Specifying custom eeprom-types via device tree
* or properties is recommended anyhow.
*/
page_size = 1;
flags = cdata->flags;
if (device_property_present(dev, "read-only"))
flags |= AT24_FLAG_READONLY;
if (device_property_present(dev, "no-read-rollover"))
flags |= AT24_FLAG_NO_RDROL;
err = device_property_read_u32(dev, "address-width", &addrw);
if (!err) {
switch (addrw) {
case 8:
if (flags & AT24_FLAG_ADDR16)
dev_warn(dev,
"Override address width to be 8, while default is 16\n");
flags &= ~AT24_FLAG_ADDR16;
break;
case 16:
flags |= AT24_FLAG_ADDR16;
break;
default:
dev_warn(dev, "Bad \"address-width\" property: %u\n",
addrw);
}
}
err = device_property_read_u32(dev, "size", &byte_len);
if (err)
byte_len = cdata->byte_len;
if (!i2c_fn_i2c && !i2c_fn_block)
page_size = 1;
if (!page_size) {
dev_err(dev, "page_size must not be 0!\n");
return -EINVAL;
}
if (!is_power_of_2(page_size))
dev_warn(dev, "page_size looks suspicious (no power of 2)!\n");
err = device_property_read_u32(dev, "num-addresses", &num_addresses);
if (err) {
if (flags & AT24_FLAG_TAKE8ADDR)
num_addresses = 8;
else
num_addresses = DIV_ROUND_UP(byte_len,
(flags & AT24_FLAG_ADDR16) ? 65536 : 256);
}
if ((flags & AT24_FLAG_SERIAL) && (flags & AT24_FLAG_MAC)) {
dev_err(dev,
"invalid device data - cannot have both AT24_FLAG_SERIAL & AT24_FLAG_MAC.");
return -EINVAL;
}
regmap_config.val_bits = 8;
regmap_config.reg_bits = (flags & AT24_FLAG_ADDR16) ? 16 : 8;
regmap_config.disable_locking = true;
regmap = devm_regmap_init_i2c(client, ®map_config);
if (IS_ERR(regmap))
return PTR_ERR(regmap);
at24 = devm_kzalloc(dev, struct_size(at24, client, num_addresses),
GFP_KERNEL);
if (!at24)
return -ENOMEM;
mutex_init(&at24->lock);
at24->byte_len = byte_len;
at24->page_size = page_size;
at24->flags = flags;
at24->read_post = cdata->read_post;
at24->num_addresses = num_addresses;
at24->offset_adj = at24_get_offset_adj(flags, byte_len);
at24->client[0].client = client;
at24->client[0].regmap = regmap;
at24->vcc_reg = devm_regulator_get(dev, "vcc");
if (IS_ERR(at24->vcc_reg))
return PTR_ERR(at24->vcc_reg);
writable = !(flags & AT24_FLAG_READONLY);
if (writable) {
at24->write_max = min_t(unsigned int,
page_size, at24_io_limit);
if (!i2c_fn_i2c && at24->write_max > I2C_SMBUS_BLOCK_MAX)
at24->write_max = I2C_SMBUS_BLOCK_MAX;
}
/* use dummy devices for multiple-address chips */
for (i = 1; i < num_addresses; i++) {
err = at24_make_dummy_client(at24, i, ®map_config);
if (err)
return err;
}
/*
* We initialize nvmem_config.id to NVMEM_DEVID_AUTO even if the
* label property is set as some platform can have multiple eeproms
* with same label and we can not register each of those with same
* label. Failing to register those eeproms trigger cascade failure
* on such platform.
*/
nvmem_config.id = NVMEM_DEVID_AUTO;
if (device_property_present(dev, "label")) {
err = device_property_read_string(dev, "label",
&nvmem_config.name);
if (err)
return err;
} else {
nvmem_config.name = dev_name(dev);
}
nvmem_config.type = NVMEM_TYPE_EEPROM;
nvmem_config.dev = dev;
nvmem_config.read_only = !writable;
nvmem_config.root_only = !(flags & AT24_FLAG_IRUGO);
nvmem_config.owner = THIS_MODULE;
nvmem_config.compat = true;
nvmem_config.base_dev = dev;
nvmem_config.reg_read = at24_read;
nvmem_config.reg_write = at24_write;
nvmem_config.priv = at24;
nvmem_config.stride = 1;
nvmem_config.word_size = 1;
nvmem_config.size = byte_len;
i2c_set_clientdata(client, at24);
err = regulator_enable(at24->vcc_reg);
if (err) {
dev_err(dev, "Failed to enable vcc regulator\n");
return err;
}
/* enable runtime pm */
pm_runtime_set_active(dev);
pm_runtime_enable(dev);
at24->nvmem = devm_nvmem_register(dev, &nvmem_config);
if (IS_ERR(at24->nvmem)) {
pm_runtime_disable(dev);
if (!pm_runtime_status_suspended(dev))
regulator_disable(at24->vcc_reg);
return PTR_ERR(at24->nvmem);
}
/*
* Perform a one-byte test read to verify that the
* chip is functional.
*/
err = at24_read(at24, 0, &test_byte, 1);
if (err) {
pm_runtime_disable(dev);
if (!pm_runtime_status_suspended(dev))
regulator_disable(at24->vcc_reg);
return -ENODEV;
}
pm_runtime_idle(dev);
if (writable)
dev_info(dev, "%u byte %s EEPROM, writable, %u bytes/write\n",
byte_len, client->name, at24->write_max);
else
dev_info(dev, "%u byte %s EEPROM, read-only\n",
byte_len, client->name);
return 0;
}
static int at24_remove(struct i2c_client *client)
{
struct at24_data *at24 = i2c_get_clientdata(client);
pm_runtime_disable(&client->dev);
if (!pm_runtime_status_suspended(&client->dev))
regulator_disable(at24->vcc_reg);
pm_runtime_set_suspended(&client->dev);
return 0;
}
static int __maybe_unused at24_suspend(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct at24_data *at24 = i2c_get_clientdata(client);
return regulator_disable(at24->vcc_reg);
}
static int __maybe_unused at24_resume(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct at24_data *at24 = i2c_get_clientdata(client);
return regulator_enable(at24->vcc_reg);
}
static const struct dev_pm_ops at24_pm_ops = {
SET_SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend,
pm_runtime_force_resume)
SET_RUNTIME_PM_OPS(at24_suspend, at24_resume, NULL)
};
static struct i2c_driver at24_driver = {
.driver = {
.name = "at24",
.pm = &at24_pm_ops,
.of_match_table = at24_of_match,
.acpi_match_table = ACPI_PTR(at24_acpi_ids),
},
.probe_new = at24_probe,
.remove = at24_remove,
.id_table = at24_ids,
};
static int __init at24_init(void)
{
if (!at24_io_limit) {
pr_err("at24: at24_io_limit must not be 0!\n");
return -EINVAL;
}
at24_io_limit = rounddown_pow_of_two(at24_io_limit);
return i2c_add_driver(&at24_driver);
}
module_init(at24_init);
static void __exit at24_exit(void)
{
i2c_del_driver(&at24_driver);
}
module_exit(at24_exit);
MODULE_DESCRIPTION("Driver for most I2C EEPROMs");
MODULE_AUTHOR("David Brownell and Wolfram Sang");
MODULE_LICENSE("GPL");
| 24,923 | C | 28.015134 | 80 | 0.676443 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Mangdang/Adafruit_GPIO/__init__.py | from __future__ import absolute_import
from Mangdang.Adafruit_GPIO.GPIO import *
| 82 | Python | 19.749995 | 41 | 0.780488 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Mangdang/Adafruit_GPIO/Platform.py | # Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import platform
import re
# Platform identification constants.
UNKNOWN = 0
RASPBERRY_PI = 1
BEAGLEBONE_BLACK = 2
MINNOWBOARD = 3
JETSON_NANO = 4
def platform_detect():
"""Detect if running on the Raspberry Pi or Beaglebone Black and return the
platform type. Will return RASPBERRY_PI, BEAGLEBONE_BLACK, or UNKNOWN."""
# Handle Raspberry Pi
pi = pi_version()
if pi is not None:
return RASPBERRY_PI
# Handle Beaglebone Black
# TODO: Check the Beaglebone Black /proc/cpuinfo value instead of reading
# the platform.
plat = platform.platform()
if plat.lower().find('armv7l-with-debian') > -1:
return BEAGLEBONE_BLACK
elif plat.lower().find('armv7l-with-ubuntu') > -1:
return BEAGLEBONE_BLACK
elif plat.lower().find('armv7l-with-glibc2.4') > -1:
return BEAGLEBONE_BLACK
elif plat.lower().find('tegra-aarch64-with-ubuntu') > -1:
return JETSON_NANO
# Handle Minnowboard
# Assumption is that mraa is installed
try:
import mraa
if mraa.getPlatformName()=='MinnowBoard MAX':
return MINNOWBOARD
except ImportError:
pass
# Couldn't figure out the platform, just return unknown.
return UNKNOWN
def pi_revision():
"""Detect the revision number of a Raspberry Pi, useful for changing
functionality like default I2C bus based on revision."""
# Revision list available at: http://elinux.org/RPi_HardwareHistory#Board_Revision_History
with open('/proc/cpuinfo', 'r') as infile:
for line in infile:
# Match a line of the form "Revision : 0002" while ignoring extra
# info in front of the revsion (like 1000 when the Pi was over-volted).
match = re.match('Revision\s+:\s+.*(\w{4})$', line, flags=re.IGNORECASE)
if match and match.group(1) in ['0000', '0002', '0003']:
# Return revision 1 if revision ends with 0000, 0002 or 0003.
return 1
elif match:
# Assume revision 2 if revision ends with any other 4 chars.
return 2
# Couldn't find the revision, throw an exception.
raise RuntimeError('Could not determine Raspberry Pi revision.')
def pi_version():
"""Detect the version of the Raspberry Pi. Returns either 1, 2 or
None depending on if it's a Raspberry Pi 1 (model A, B, A+, B+),
Raspberry Pi 2 (model B+), or not a Raspberry Pi.
"""
# Check /proc/cpuinfo for the Hardware field value.
# 2708 is pi 1
# 2709 is pi 2
# 2835 is pi 3 on 4.9.x kernel
# Anything else is not a pi.
with open('/proc/cpuinfo', 'r') as infile:
cpuinfo = infile.read()
# Match a line like 'Hardware : BCM2709'
match = re.search('^Hardware\s+:\s+(\w+)$', cpuinfo,
flags=re.MULTILINE | re.IGNORECASE)
if not match:
# Couldn't find the hardware, assume it isn't a pi.
return None
if match.group(1) == 'BCM2708':
# Pi 1
return 1
elif match.group(1) == 'BCM2709':
# Pi 2
return 2
elif match.group(1) == 'BCM2835':
# Pi 3 / Pi on 4.9.x kernel
return 3
else:
# Something else, not a pi.
return None
| 4,413 | Python | 37.719298 | 94 | 0.65375 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Mangdang/Adafruit_GPIO/GPIO.py | # Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import Adafruit_GPIO.Platform as Platform
OUT = 0
IN = 1
HIGH = True
LOW = False
RISING = 1
FALLING = 2
BOTH = 3
PUD_OFF = 0
PUD_DOWN = 1
PUD_UP = 2
class BaseGPIO(object):
"""Base class for implementing simple digital IO for a platform.
Implementors are expected to subclass from this and provide an implementation
of the setup, output, and input functions."""
def setup(self, pin, mode, pull_up_down=PUD_OFF):
"""Set the input or output mode for a specified pin. Mode should be
either OUT or IN."""
raise NotImplementedError
def output(self, pin, value):
"""Set the specified pin the provided high/low value. Value should be
either HIGH/LOW or a boolean (true = high)."""
raise NotImplementedError
def input(self, pin):
"""Read the specified pin and return HIGH/true if the pin is pulled high,
or LOW/false if pulled low."""
raise NotImplementedError
def set_high(self, pin):
"""Set the specified pin HIGH."""
self.output(pin, HIGH)
def set_low(self, pin):
"""Set the specified pin LOW."""
self.output(pin, LOW)
def is_high(self, pin):
"""Return true if the specified pin is pulled high."""
return self.input(pin) == HIGH
def is_low(self, pin):
"""Return true if the specified pin is pulled low."""
return self.input(pin) == LOW
# Basic implementation of multiple pin methods just loops through pins and
# processes each one individually. This is not optimal, but derived classes can
# provide a more optimal implementation that deals with groups of pins
# simultaneously.
# See MCP230xx or PCF8574 classes for examples of optimized implementations.
def output_pins(self, pins):
"""Set multiple pins high or low at once. Pins should be a dict of pin
name to pin value (HIGH/True for 1, LOW/False for 0). All provided pins
will be set to the given values.
"""
# General implementation just loops through pins and writes them out
# manually. This is not optimized, but subclasses can choose to implement
# a more optimal batch output implementation. See the MCP230xx class for
# example of optimized implementation.
for pin, value in iter(pins.items()):
self.output(pin, value)
def setup_pins(self, pins):
"""Setup multiple pins as inputs or outputs at once. Pins should be a
dict of pin name to pin type (IN or OUT).
"""
# General implementation that can be optimized by derived classes.
for pin, value in iter(pins.items()):
self.setup(pin, value)
def input_pins(self, pins):
"""Read multiple pins specified in the given list and return list of pin values
GPIO.HIGH/True if the pin is pulled high, or GPIO.LOW/False if pulled low.
"""
# General implementation that can be optimized by derived classes.
return [self.input(pin) for pin in pins]
def add_event_detect(self, pin, edge):
"""Enable edge detection events for a particular GPIO channel. Pin
should be type IN. Edge must be RISING, FALLING or BOTH.
"""
raise NotImplementedError
def remove_event_detect(self, pin):
"""Remove edge detection for a particular GPIO channel. Pin should be
type IN.
"""
raise NotImplementedError
def add_event_callback(self, pin, callback):
"""Add a callback for an event already defined using add_event_detect().
Pin should be type IN.
"""
raise NotImplementedError
def event_detected(self, pin):
"""Returns True if an edge has occured on a given GPIO. You need to
enable edge detection using add_event_detect() first. Pin should be
type IN.
"""
raise NotImplementedError
def wait_for_edge(self, pin, edge):
"""Wait for an edge. Pin should be type IN. Edge must be RISING,
FALLING or BOTH."""
raise NotImplementedError
def cleanup(self, pin=None):
"""Clean up GPIO event detection for specific pin, or all pins if none
is specified.
"""
raise NotImplementedError
# helper functions useful to derived classes
def _validate_pin(self, pin):
# Raise an exception if pin is outside the range of allowed values.
if pin < 0 or pin >= self.NUM_GPIO:
raise ValueError('Invalid GPIO value, must be between 0 and {0}.'.format(self.NUM_GPIO))
def _bit2(self, src, bit, val):
bit = 1 << bit
return (src | bit) if val else (src & ~bit)
class RPiGPIOAdapter(BaseGPIO):
"""GPIO implementation for the Raspberry Pi using the RPi.GPIO library."""
def __init__(self, rpi_gpio, mode=None):
self.rpi_gpio = rpi_gpio
# Suppress warnings about GPIO in use.
rpi_gpio.setwarnings(False)
# Setup board pin mode.
if mode == rpi_gpio.BOARD or mode == rpi_gpio.BCM:
rpi_gpio.setmode(mode)
elif mode is not None:
raise ValueError('Unexpected value for mode. Must be BOARD or BCM.')
else:
# Default to BCM numbering if not told otherwise.
rpi_gpio.setmode(rpi_gpio.BCM)
# Define mapping of Adafruit GPIO library constants to RPi.GPIO constants.
self._dir_mapping = { OUT: rpi_gpio.OUT,
IN: rpi_gpio.IN }
self._pud_mapping = { PUD_OFF: rpi_gpio.PUD_OFF,
PUD_DOWN: rpi_gpio.PUD_DOWN,
PUD_UP: rpi_gpio.PUD_UP }
self._edge_mapping = { RISING: rpi_gpio.RISING,
FALLING: rpi_gpio.FALLING,
BOTH: rpi_gpio.BOTH }
def setup(self, pin, mode, pull_up_down=PUD_OFF):
"""Set the input or output mode for a specified pin. Mode should be
either OUTPUT or INPUT.
"""
self.rpi_gpio.setup(pin, self._dir_mapping[mode],
pull_up_down=self._pud_mapping[pull_up_down])
def output(self, pin, value):
"""Set the specified pin the provided high/low value. Value should be
either HIGH/LOW or a boolean (true = high).
"""
self.rpi_gpio.output(pin, value)
def input(self, pin):
"""Read the specified pin and return HIGH/true if the pin is pulled high,
or LOW/false if pulled low.
"""
return self.rpi_gpio.input(pin)
def input_pins(self, pins):
"""Read multiple pins specified in the given list and return list of pin values
GPIO.HIGH/True if the pin is pulled high, or GPIO.LOW/False if pulled low.
"""
# maybe rpi has a mass read... it would be more efficient to use it if it exists
return [self.rpi_gpio.input(pin) for pin in pins]
def add_event_detect(self, pin, edge, callback=None, bouncetime=-1):
"""Enable edge detection events for a particular GPIO channel. Pin
should be type IN. Edge must be RISING, FALLING or BOTH. Callback is a
function for the event. Bouncetime is switch bounce timeout in ms for
callback
"""
kwargs = {}
if callback:
kwargs['callback']=callback
if bouncetime > 0:
kwargs['bouncetime']=bouncetime
self.rpi_gpio.add_event_detect(pin, self._edge_mapping[edge], **kwargs)
def remove_event_detect(self, pin):
"""Remove edge detection for a particular GPIO channel. Pin should be
type IN.
"""
self.rpi_gpio.remove_event_detect(pin)
def add_event_callback(self, pin, callback):
"""Add a callback for an event already defined using add_event_detect().
Pin should be type IN.
"""
self.rpi_gpio.add_event_callback(pin, callback)
def event_detected(self, pin):
"""Returns True if an edge has occured on a given GPIO. You need to
enable edge detection using add_event_detect() first. Pin should be
type IN.
"""
return self.rpi_gpio.event_detected(pin)
def wait_for_edge(self, pin, edge):
"""Wait for an edge. Pin should be type IN. Edge must be RISING,
FALLING or BOTH.
"""
self.rpi_gpio.wait_for_edge(pin, self._edge_mapping[edge])
def cleanup(self, pin=None):
"""Clean up GPIO event detection for specific pin, or all pins if none
is specified.
"""
if pin is None:
self.rpi_gpio.cleanup()
else:
self.rpi_gpio.cleanup(pin)
class AdafruitBBIOAdapter(BaseGPIO):
"""GPIO implementation for the Beaglebone Black using the Adafruit_BBIO
library.
"""
def __init__(self, bbio_gpio):
self.bbio_gpio = bbio_gpio
# Define mapping of Adafruit GPIO library constants to RPi.GPIO constants.
self._dir_mapping = { OUT: bbio_gpio.OUT,
IN: bbio_gpio.IN }
self._pud_mapping = { PUD_OFF: bbio_gpio.PUD_OFF,
PUD_DOWN: bbio_gpio.PUD_DOWN,
PUD_UP: bbio_gpio.PUD_UP }
self._edge_mapping = { RISING: bbio_gpio.RISING,
FALLING: bbio_gpio.FALLING,
BOTH: bbio_gpio.BOTH }
def setup(self, pin, mode, pull_up_down=PUD_OFF):
"""Set the input or output mode for a specified pin. Mode should be
either OUTPUT or INPUT.
"""
self.bbio_gpio.setup(pin, self._dir_mapping[mode],
pull_up_down=self._pud_mapping[pull_up_down])
def output(self, pin, value):
"""Set the specified pin the provided high/low value. Value should be
either HIGH/LOW or a boolean (true = high).
"""
self.bbio_gpio.output(pin, value)
def input(self, pin):
"""Read the specified pin and return HIGH/true if the pin is pulled high,
or LOW/false if pulled low.
"""
return self.bbio_gpio.input(pin)
def input_pins(self, pins):
"""Read multiple pins specified in the given list and return list of pin values
GPIO.HIGH/True if the pin is pulled high, or GPIO.LOW/False if pulled low.
"""
# maybe bbb has a mass read... it would be more efficient to use it if it exists
return [self.bbio_gpio.input(pin) for pin in pins]
def add_event_detect(self, pin, edge, callback=None, bouncetime=-1):
"""Enable edge detection events for a particular GPIO channel. Pin
should be type IN. Edge must be RISING, FALLING or BOTH. Callback is a
function for the event. Bouncetime is switch bounce timeout in ms for
callback
"""
kwargs = {}
if callback:
kwargs['callback']=callback
if bouncetime > 0:
kwargs['bouncetime']=bouncetime
self.bbio_gpio.add_event_detect(pin, self._edge_mapping[edge], **kwargs)
def remove_event_detect(self, pin):
"""Remove edge detection for a particular GPIO channel. Pin should be
type IN.
"""
self.bbio_gpio.remove_event_detect(pin)
def add_event_callback(self, pin, callback, bouncetime=-1):
"""Add a callback for an event already defined using add_event_detect().
Pin should be type IN. Bouncetime is switch bounce timeout in ms for
callback
"""
kwargs = {}
if bouncetime > 0:
kwargs['bouncetime']=bouncetime
self.bbio_gpio.add_event_callback(pin, callback, **kwargs)
def event_detected(self, pin):
"""Returns True if an edge has occured on a given GPIO. You need to
enable edge detection using add_event_detect() first. Pin should be
type IN.
"""
return self.bbio_gpio.event_detected(pin)
def wait_for_edge(self, pin, edge):
"""Wait for an edge. Pin should be type IN. Edge must be RISING,
FALLING or BOTH.
"""
self.bbio_gpio.wait_for_edge(pin, self._edge_mapping[edge])
def cleanup(self, pin=None):
"""Clean up GPIO event detection for specific pin, or all pins if none
is specified.
"""
if pin is None:
self.bbio_gpio.cleanup()
else:
self.bbio_gpio.cleanup(pin)
class AdafruitMinnowAdapter(BaseGPIO):
"""GPIO implementation for the Minnowboard + MAX using the mraa library"""
def __init__(self,mraa_gpio):
self.mraa_gpio = mraa_gpio
# Define mapping of Adafruit GPIO library constants to mraa constants
self._dir_mapping = { OUT: self.mraa_gpio.DIR_OUT,
IN: self.mraa_gpio.DIR_IN }
self._pud_mapping = { PUD_OFF: self.mraa_gpio.MODE_STRONG,
PUD_UP: self.mraa_gpio.MODE_HIZ,
PUD_DOWN: self.mraa_gpio.MODE_PULLDOWN }
self._edge_mapping = { RISING: self.mraa_gpio.EDGE_RISING,
FALLING: self.mraa_gpio.EDGE_FALLING,
BOTH: self.mraa_gpio.EDGE_BOTH }
def setup(self,pin,mode):
"""Set the input or output mode for a specified pin. Mode should be
either DIR_IN or DIR_OUT.
"""
self.mraa_gpio.Gpio.dir(self.mraa_gpio.Gpio(pin),self._dir_mapping[mode])
def output(self,pin,value):
"""Set the specified pin the provided high/low value. Value should be
either 1 (ON or HIGH), or 0 (OFF or LOW) or a boolean.
"""
self.mraa_gpio.Gpio.write(self.mraa_gpio.Gpio(pin), value)
def input(self,pin):
"""Read the specified pin and return HIGH/true if the pin is pulled high,
or LOW/false if pulled low.
"""
return self.mraa_gpio.Gpio.read(self.mraa_gpio.Gpio(pin))
def add_event_detect(self, pin, edge, callback=None, bouncetime=-1):
"""Enable edge detection events for a particular GPIO channel. Pin
should be type IN. Edge must be RISING, FALLING or BOTH. Callback is a
function for the event. Bouncetime is switch bounce timeout in ms for
callback
"""
kwargs = {}
if callback:
kwargs['callback']=callback
if bouncetime > 0:
kwargs['bouncetime']=bouncetime
self.mraa_gpio.Gpio.isr(self.mraa_gpio.Gpio(pin), self._edge_mapping[edge], **kwargs)
def remove_event_detect(self, pin):
"""Remove edge detection for a particular GPIO channel. Pin should be
type IN.
"""
self.mraa_gpio.Gpio.isrExit(self.mraa_gpio.Gpio(pin))
def wait_for_edge(self, pin, edge):
"""Wait for an edge. Pin should be type IN. Edge must be RISING,
FALLING or BOTH.
"""
self.bbio_gpio.wait_for_edge(self.mraa_gpio.Gpio(pin), self._edge_mapping[edge])
def get_platform_gpio(**keywords):
"""Attempt to return a GPIO instance for the platform which the code is being
executed on. Currently supports only the Raspberry Pi using the RPi.GPIO
library and Beaglebone Black using the Adafruit_BBIO library. Will throw an
exception if a GPIO instance can't be created for the current platform. The
returned GPIO object is an instance of BaseGPIO.
"""
plat = Platform.platform_detect()
if plat == Platform.RASPBERRY_PI:
import RPi.GPIO
return RPiGPIOAdapter(RPi.GPIO, **keywords)
elif plat == Platform.BEAGLEBONE_BLACK:
import Adafruit_BBIO.GPIO
return AdafruitBBIOAdapter(Adafruit_BBIO.GPIO, **keywords)
elif plat == Platform.MINNOWBOARD:
import mraa
return AdafruitMinnowAdapter(mraa, **keywords)
elif plat == Platform.JETSON_NANO:
import Jetson.GPIO
return RPiGPIOAdapter(Jetson.GPIO, **keywords)
elif plat == Platform.UNKNOWN:
raise RuntimeError('Could not determine platform.')
| 17,268 | Python | 39.160465 | 100 | 0.618253 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Mangdang/Adafruit_GPIO/SPI.py | # Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import operator
import time
import Mangdang.Adafruit_GPIO as GPIO
MSBFIRST = 0
LSBFIRST = 1
class SpiDev(object):
"""Hardware-based SPI implementation using the spidev interface."""
def __init__(self, port, device, max_speed_hz=500000):
"""Initialize an SPI device using the SPIdev interface. Port and device
identify the device, for example the device /dev/spidev1.0 would be port
1 and device 0.
"""
import spidev
self._device = spidev.SpiDev()
self._device.open(port, device)
self._device.max_speed_hz=max_speed_hz
# Default to mode 0, and make sure CS is active low.
self._device.mode = 0
#self._device.cshigh = False
def set_clock_hz(self, hz):
"""Set the speed of the SPI clock in hertz. Note that not all speeds
are supported and a lower speed might be chosen by the hardware.
"""
self._device.max_speed_hz=hz
def set_mode(self, mode):
"""Set SPI mode which controls clock polarity and phase. Should be a
numeric value 0, 1, 2, or 3. See wikipedia page for details on meaning:
http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus
"""
if mode < 0 or mode > 3:
raise ValueError('Mode must be a value 0, 1, 2, or 3.')
self._device.mode = mode
def set_bit_order(self, order):
"""Set order of bits to be read/written over serial lines. Should be
either MSBFIRST for most-significant first, or LSBFIRST for
least-signifcant first.
"""
if order == MSBFIRST:
self._device.lsbfirst = False
elif order == LSBFIRST:
self._device.lsbfirst = True
else:
raise ValueError('Order must be MSBFIRST or LSBFIRST.')
def close(self):
"""Close communication with the SPI device."""
self._device.close()
def write(self, data):
"""Half-duplex SPI write. The specified array of bytes will be clocked
out the MOSI line.
"""
self._device.writebytes(data)
def read(self, length):
"""Half-duplex SPI read. The specified length of bytes will be clocked
in the MISO line and returned as a bytearray object.
"""
return bytearray(self._device.readbytes(length))
def transfer(self, data):
"""Full-duplex SPI read and write. The specified array of bytes will be
clocked out the MOSI line, while simultaneously bytes will be read from
the MISO line. Read bytes will be returned as a bytearray object.
"""
return bytearray(self._device.xfer2(data))
class SpiDevMraa(object):
"""Hardware SPI implementation with the mraa library on Minnowboard"""
def __init__(self, port, device, max_speed_hz=500000):
import mraa
self._device = mraa.Spi(0)
self._device.mode(0)
def set_clock_hz(self, hz):
"""Set the speed of the SPI clock in hertz. Note that not all speeds
are supported and a lower speed might be chosen by the hardware.
"""
self._device.frequency(hz)
def set_mode(self,mode):
"""Set SPI mode which controls clock polarity and phase. Should be a
numeric value 0, 1, 2, or 3. See wikipedia page for details on meaning:
http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus
"""
if mode < 0 or mode > 3:
raise ValueError('Mode must be a value 0, 1, 2, or 3.')
self._device.mode(mode)
def set_bit_order(self, order):
"""Set order of bits to be read/written over serial lines. Should be
either MSBFIRST for most-significant first, or LSBFIRST for
least-signifcant first.
"""
if order == MSBFIRST:
self._device.lsbmode(False)
elif order == LSBFIRST:
self._device.lsbmode(True)
else:
raise ValueError('Order must be MSBFIRST or LSBFIRST.')
def close(self):
"""Close communication with the SPI device."""
self._device.Spi()
def write(self, data):
"""Half-duplex SPI write. The specified array of bytes will be clocked
out the MOSI line.
"""
self._device.write(bytearray(data))
class BitBang(object):
"""Software-based implementation of the SPI protocol over GPIO pins."""
def __init__(self, gpio, sclk, mosi=None, miso=None, ss=None):
"""Initialize bit bang (or software) based SPI. Must provide a BaseGPIO
class, the SPI clock, and optionally MOSI, MISO, and SS (slave select)
pin numbers. If MOSI is set to None then writes will be disabled and fail
with an error, likewise for MISO reads will be disabled. If SS is set to
None then SS will not be asserted high/low by the library when
transfering data.
"""
self._gpio = gpio
self._sclk = sclk
self._mosi = mosi
self._miso = miso
self._ss = ss
# Set pins as outputs/inputs.
gpio.setup(sclk, GPIO.OUT)
if mosi is not None:
gpio.setup(mosi, GPIO.OUT)
if miso is not None:
gpio.setup(miso, GPIO.IN)
if ss is not None:
gpio.setup(ss, GPIO.OUT)
# Assert SS high to start with device communication off.
gpio.set_high(ss)
# Assume mode 0.
self.set_mode(0)
# Assume most significant bit first order.
self.set_bit_order(MSBFIRST)
def set_clock_hz(self, hz):
"""Set the speed of the SPI clock. This is unsupported with the bit
bang SPI class and will be ignored.
"""
pass
def set_mode(self, mode):
"""Set SPI mode which controls clock polarity and phase. Should be a
numeric value 0, 1, 2, or 3. See wikipedia page for details on meaning:
http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus
"""
if mode < 0 or mode > 3:
raise ValueError('Mode must be a value 0, 1, 2, or 3.')
if mode & 0x02:
# Clock is normally high in mode 2 and 3.
self._clock_base = GPIO.HIGH
else:
# Clock is normally low in mode 0 and 1.
self._clock_base = GPIO.LOW
if mode & 0x01:
# Read on trailing edge in mode 1 and 3.
self._read_leading = False
else:
# Read on leading edge in mode 0 and 2.
self._read_leading = True
# Put clock into its base state.
self._gpio.output(self._sclk, self._clock_base)
def set_bit_order(self, order):
"""Set order of bits to be read/written over serial lines. Should be
either MSBFIRST for most-significant first, or LSBFIRST for
least-signifcant first.
"""
# Set self._mask to the bitmask which points at the appropriate bit to
# read or write, and appropriate left/right shift operator function for
# reading/writing.
if order == MSBFIRST:
self._mask = 0x80
self._write_shift = operator.lshift
self._read_shift = operator.rshift
elif order == LSBFIRST:
self._mask = 0x01
self._write_shift = operator.rshift
self._read_shift = operator.lshift
else:
raise ValueError('Order must be MSBFIRST or LSBFIRST.')
def close(self):
"""Close the SPI connection. Unused in the bit bang implementation."""
pass
def write(self, data, assert_ss=True, deassert_ss=True):
"""Half-duplex SPI write. If assert_ss is True, the SS line will be
asserted low, the specified bytes will be clocked out the MOSI line, and
if deassert_ss is True the SS line be put back high.
"""
# Fail MOSI is not specified.
if self._mosi is None:
raise RuntimeError('Write attempted with no MOSI pin specified.')
if assert_ss and self._ss is not None:
self._gpio.set_low(self._ss)
for byte in data:
for i in range(8):
# Write bit to MOSI.
if self._write_shift(byte, i) & self._mask:
self._gpio.set_high(self._mosi)
else:
self._gpio.set_low(self._mosi)
# Flip clock off base.
self._gpio.output(self._sclk, not self._clock_base)
# Return clock to base.
self._gpio.output(self._sclk, self._clock_base)
if deassert_ss and self._ss is not None:
self._gpio.set_high(self._ss)
def read(self, length, assert_ss=True, deassert_ss=True):
"""Half-duplex SPI read. If assert_ss is true, the SS line will be
asserted low, the specified length of bytes will be clocked in the MISO
line, and if deassert_ss is true the SS line will be put back high.
Bytes which are read will be returned as a bytearray object.
"""
if self._miso is None:
raise RuntimeError('Read attempted with no MISO pin specified.')
if assert_ss and self._ss is not None:
self._gpio.set_low(self._ss)
result = bytearray(length)
for i in range(length):
for j in range(8):
# Flip clock off base.
self._gpio.output(self._sclk, not self._clock_base)
# Handle read on leading edge of clock.
if self._read_leading:
if self._gpio.is_high(self._miso):
# Set bit to 1 at appropriate location.
result[i] |= self._read_shift(self._mask, j)
else:
# Set bit to 0 at appropriate location.
result[i] &= ~self._read_shift(self._mask, j)
# Return clock to base.
self._gpio.output(self._sclk, self._clock_base)
# Handle read on trailing edge of clock.
if not self._read_leading:
if self._gpio.is_high(self._miso):
# Set bit to 1 at appropriate location.
result[i] |= self._read_shift(self._mask, j)
else:
# Set bit to 0 at appropriate location.
result[i] &= ~self._read_shift(self._mask, j)
if deassert_ss and self._ss is not None:
self._gpio.set_high(self._ss)
return result
def transfer(self, data, assert_ss=True, deassert_ss=True):
"""Full-duplex SPI read and write. If assert_ss is true, the SS line
will be asserted low, the specified bytes will be clocked out the MOSI
line while bytes will also be read from the MISO line, and if
deassert_ss is true the SS line will be put back high. Bytes which are
read will be returned as a bytearray object.
"""
if self._mosi is None:
raise RuntimeError('Write attempted with no MOSI pin specified.')
if self._miso is None:
raise RuntimeError('Read attempted with no MISO pin specified.')
if assert_ss and self._ss is not None:
self._gpio.set_low(self._ss)
result = bytearray(len(data))
for i in range(len(data)):
for j in range(8):
# Write bit to MOSI.
if self._write_shift(data[i], j) & self._mask:
self._gpio.set_high(self._mosi)
else:
self._gpio.set_low(self._mosi)
# Flip clock off base.
self._gpio.output(self._sclk, not self._clock_base)
# Handle read on leading edge of clock.
if self._read_leading:
if self._gpio.is_high(self._miso):
# Set bit to 1 at appropriate location.
result[i] |= self._read_shift(self._mask, j)
else:
# Set bit to 0 at appropriate location.
result[i] &= ~self._read_shift(self._mask, j)
# Return clock to base.
self._gpio.output(self._sclk, self._clock_base)
# Handle read on trailing edge of clock.
if not self._read_leading:
if self._gpio.is_high(self._miso):
# Set bit to 1 at appropriate location.
result[i] |= self._read_shift(self._mask, j)
else:
# Set bit to 0 at appropriate location.
result[i] &= ~self._read_shift(self._mask, j)
if deassert_ss and self._ss is not None:
self._gpio.set_high(self._ss)
return result
| 13,970 | Python | 41.465045 | 81 | 0.585827 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Mangdang/FuelGauge/max1720x_battery.c | /*
* Maxim MAX17201/MAX17205 fuel gauge driver
*
* Author: Mahir Ozturk <mahir.ozturk@maximintegrated.com>
* Copyright (C) 2019 Maxim Integrated
*
* 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 2 of the License, or (at your
* option) any later version.
*
* This driver is based on max17042/40_battery.c
*/
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/i2c.h>
#include <linux/module.h>
#include <linux/mod_devicetable.h>
#include <linux/mutex.h>
#include <linux/of.h>
#include <linux/power_supply.h>
#include <linux/platform_device.h>
#include <linux/pm.h>
#include <linux/regmap.h>
#include <linux/slab.h>
#define DRV_NAME "max1720x"
/* CONFIG register bits */
#define MAX1720X_CONFIG_ALRT_EN (1 << 2)
/* STATUS register bits */
#define MAX1720X_STATUS_BST (1 << 3)
#define MAX1720X_STATUS_POR (1 << 1)
/* STATUS interrupt status bits */
#define MAX1720X_STATUS_ALRT_CLR_MASK (0x88BB)
#define MAX1720X_STATUS_SOC_MAX_ALRT (1 << 14)
#define MAX1720X_STATUS_TEMP_MAX_ALRT (1 << 13)
#define MAX1720X_STATUS_VOLT_MAX_ALRT (1 << 12)
#define MAX1720X_STATUS_SOC_MIN_ALRT (1 << 10)
#define MAX1720X_STATUS_TEMP_MIN_ALRT (1 << 9)
#define MAX1720X_STATUS_VOLT_MIN_ALRT (1 << 8)
#define MAX1720X_STATUS_CURR_MAX_ALRT (1 << 6)
#define MAX1720X_STATUS_CURR_MIN_ALRT (1 << 2)
/* ProtStatus register bits */
#define MAX1730X_PROTSTATUS_CHGWDT (1 << 15)
#define MAX1730X_PROTSTATUS_TOOHOTC (1 << 14)
#define MAX1730X_PROTSTATUS_FULL (1 << 13)
#define MAX1730X_PROTSTATUS_TOOCOLDC (1 << 12)
#define MAX1730X_PROTSTATUS_OVP (1 << 11)
#define MAX1730X_PROTSTATUS_OCCP (1 << 10)
#define MAX1730X_PROTSTATUS_QOVFLW (1 << 9)
#define MAX1730X_PROTSTATUS_RESCFAULT (1 << 7)
#define MAX1730X_PROTSTATUS_PERMFAIL (1 << 6)
#define MAX1730X_PROTSTATUS_DIEHOT (1 << 5)
#define MAX1730X_PROTSTATUS_TOOHOTD (1 << 4)
#define MAX1730X_PROTSTATUS_UVP (1 << 3)
#define MAX1730X_PROTSTATUS_ODCP (1 << 2)
#define MAX1730X_PROTSTATUS_RESDFAULT (1 << 1)
#define MAX1730X_PROTSTATUS_SHDN (1 << 0)
#define MAX1720X_VMAX_TOLERANCE 50 /* 50 mV */
#define MODELGAUGE_DATA_I2C_ADDR 0x36
#define NONVOLATILE_DATA_I2C_ADDR 0x0B
struct max1720x_platform_data {
/*
* rsense in miliOhms.
* default 10 (if rsense = 0) as it is the recommended value by
* the datasheet although it can be changed by board designers.
*/
unsigned int rsense;
int volt_min; /* in mV */
int volt_max; /* in mV */
int temp_min; /* in DegreC */
int temp_max; /* in DegreeC */
int soc_max; /* in percent */
int soc_min; /* in percent */
int curr_max; /* in mA */
int curr_min; /* in mA */
};
struct max1720x_priv {
struct i2c_client *client;
struct device *dev;
struct regmap *regmap;
struct power_supply *battery;
struct max1720x_platform_data *pdata;
struct work_struct init_worker;
struct attribute_group *attr_grp;
const u8 *regs;
u8 nvmem_high_addr;
int cycles_reg_lsb_percent;
int (*get_charging_status)(void);
int (*get_battery_health)(struct max1720x_priv *priv, int *health);
};
enum chip_id {
ID_MAX1720X,
ID_MAX1730X,
};
enum register_ids {
STATUS_REG = 0,
VALRTTH_REG,
TALRTTH_REG,
SALRTTH_REG,
ATRATE_REG,
REPCAP_REG,
REPSOC_REG,
TEMP_REG,
VCELL_REG,
CURRENT_REG,
AVGCURRENT_REG,
TTE_REG ,
CYCLES_REG,
DESIGNCAP_REG,
AVGVCELL_REG,
MAXMINVOLT_REG,
CONFIG_REG,
TTF_REG ,
VERSION_REG,
FULLCAPREP_REG,
VEMPTY_REG,
QH_REG ,
IALRTTH_REG,
PROTSTATUS_REG,
ATTTE_REG,
VFOCV_REG,
};
static int max1720x_get_battery_health(struct max1720x_priv *priv, int *health);
static int max1730x_get_battery_health(struct max1720x_priv *priv, int *health);
static int (*get_battery_health_handlers[])
(struct max1720x_priv *priv, int *health) = {
[ID_MAX1720X] = max1720x_get_battery_health,
[ID_MAX1730X] = max1730x_get_battery_health,
};
/* Register addresses */
static const u8 max1720x_regs[] = {
[STATUS_REG] = 0x00,
[VALRTTH_REG] = 0x01,
[TALRTTH_REG] = 0x02,
[SALRTTH_REG] = 0x03,
[ATRATE_REG] = 0x04,
[REPCAP_REG] = 0x05,
[REPSOC_REG] = 0x06,
[TEMP_REG] = 0x08,
[VCELL_REG] = 0x09,
[CURRENT_REG] = 0x0A,
[AVGCURRENT_REG] = 0x0B,
[TTE_REG] = 0x11,
[CYCLES_REG] = 0x17,
[DESIGNCAP_REG] = 0x18,
[AVGVCELL_REG] = 0x19,
[MAXMINVOLT_REG] = 0x1B,
[CONFIG_REG] = 0x1D,
[TTF_REG] = 0x20,
[VERSION_REG] = 0x21,
[FULLCAPREP_REG] = 0x35,
[VEMPTY_REG] = 0x3A,
[QH_REG] = 0x4D,
[IALRTTH_REG] = 0xB4,
[ATTTE_REG] = 0xDD,
[VFOCV_REG] = 0xFB,
};
static const u8 max1730x_regs[] = {
[STATUS_REG] = 0x00,
[VALRTTH_REG] = 0x01,
[TALRTTH_REG] = 0x02,
[SALRTTH_REG] = 0x03,
[ATRATE_REG] = 0x04,
[REPCAP_REG] = 0x05,
[REPSOC_REG] = 0x06,
[TEMP_REG] = 0x1B,
[VCELL_REG] = 0x1A,
[CURRENT_REG] = 0x1C,
[AVGCURRENT_REG] = 0x1D,
[TTE_REG] = 0x11,
[CYCLES_REG] = 0x17,
[DESIGNCAP_REG] = 0x18,
[AVGVCELL_REG] = 0x19,
[MAXMINVOLT_REG] = 0x08,
[CONFIG_REG] = 0x1D,
[TTF_REG] = 0x20,
[VERSION_REG] = 0x21,
[FULLCAPREP_REG] = 0x10,
[VEMPTY_REG] = 0x3A,
[QH_REG] = 0x4D,
[IALRTTH_REG] = 0xAC,
[PROTSTATUS_REG] = 0xD9,
[ATTTE_REG] = 0xDD,
[VFOCV_REG] = 0xFB,
};
static const u8* chip_regs[] = {
[ID_MAX1720X] = max1720x_regs,
[ID_MAX1730X] = max1730x_regs,
};
static const u8 nvmem_high_addrs[] = {
[ID_MAX1720X] = 0xDF,
[ID_MAX1730X] = 0xEF,
};
static const int cycles_reg_lsb_percents[] = {
[ID_MAX1720X] = 25,
[ID_MAX1730X] = 16,
};
static enum power_supply_property max1720x_battery_props[] = {
POWER_SUPPLY_PROP_PRESENT,
POWER_SUPPLY_PROP_CYCLE_COUNT,
POWER_SUPPLY_PROP_VOLTAGE_MAX,
POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN,
POWER_SUPPLY_PROP_VOLTAGE_NOW,
POWER_SUPPLY_PROP_VOLTAGE_AVG,
POWER_SUPPLY_PROP_VOLTAGE_OCV,
POWER_SUPPLY_PROP_CAPACITY,
POWER_SUPPLY_PROP_CAPACITY_ALERT_MIN,
POWER_SUPPLY_PROP_CAPACITY_ALERT_MAX,
POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN,
POWER_SUPPLY_PROP_CHARGE_FULL,
POWER_SUPPLY_PROP_CHARGE_NOW,
POWER_SUPPLY_PROP_CHARGE_COUNTER,
POWER_SUPPLY_PROP_TEMP,
POWER_SUPPLY_PROP_TEMP_ALERT_MIN,
POWER_SUPPLY_PROP_TEMP_ALERT_MAX,
POWER_SUPPLY_PROP_HEALTH,
POWER_SUPPLY_PROP_CURRENT_NOW,
POWER_SUPPLY_PROP_CURRENT_AVG,
POWER_SUPPLY_PROP_STATUS,
POWER_SUPPLY_PROP_TIME_TO_EMPTY_AVG,
POWER_SUPPLY_PROP_TIME_TO_FULL_AVG,
};
static inline int max1720x_raw_voltage_to_uvolts(struct max1720x_priv *priv,
int lsb)
{
return lsb * 10000 / 65536; /* 78.125uV per bit */
}
static inline int max1720x_raw_current_to_uamps(struct max1720x_priv *priv,
int curr)
{
return curr * 15625 / ((int)priv->pdata->rsense * 10);
}
static inline int max1720x_raw_capacity_to_uamph(struct max1720x_priv *priv,
int cap)
{
return cap * 5000 / (int)priv->pdata->rsense;
}
static ssize_t max1720x_log_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct max1720x_priv *priv = dev_get_drvdata(dev);
int rc = 0, reg = 0;
u32 val = 0;
for (reg = 0; reg < 0xE0; reg++) {
regmap_read(priv->regmap, reg, &val);
rc += (int)snprintf(buf+rc, PAGE_SIZE-rc, "0x%04X,", val);
if (reg == 0x4F)
reg += 0x60;
if (reg == 0xBF)
reg += 0x10;
}
rc += (int)snprintf(buf+rc, PAGE_SIZE-rc, "\n");
return rc;
}
static ssize_t max1720x_nvmem_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct max1720x_priv *priv = dev_get_drvdata(dev);
int rc = 0, reg = 0;
u32 val = 0;
int ret;
int i;
/*
* Device has a separate slave address for accessing non-volatile memory
* region, so we are temporarily changing i2c client address.
*/
priv->client->addr = NONVOLATILE_DATA_I2C_ADDR;
for (reg = 0x80; reg < priv->nvmem_high_addr; reg += 16) {
rc += snprintf(buf+rc, PAGE_SIZE-rc, "Page %02Xh: ",
(reg + 0x100) >> 4);
for (i = 0; i < 16; i++) {
ret = regmap_read(priv->regmap, reg + i, &val);
if (ret) {
dev_err(dev, "NV memory reading failed (%d)\n",
ret);
return 0;
}
rc += snprintf(buf+rc, PAGE_SIZE-rc, "0x%04X ", val);
}
rc += snprintf(buf+rc, PAGE_SIZE-rc, "\n");
}
priv->client->addr = MODELGAUGE_DATA_I2C_ADDR;
return rc;
}
static ssize_t max1720x_atrate_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct max1720x_priv *priv = dev_get_drvdata(dev);
u32 val = 0;
int ret;
ret = regmap_read(priv->regmap, priv->regs[ATRATE_REG], &val);
if (ret) {
return 0;
}
return sprintf(buf, "%d", (short)val);
}
static ssize_t max1720x_atrate_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct max1720x_priv *priv = dev_get_drvdata(dev);
s32 val = 0;
int ret;
if (kstrtos32(buf, 0, &val))
return -EINVAL;
ret = regmap_write(priv->regmap, priv->regs[ATRATE_REG], val);
if (ret < 0)
return ret;
return count;
}
static ssize_t max1720x_attte_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct max1720x_priv *priv = dev_get_drvdata(dev);
u32 val = 0;
int ret;
ret = regmap_read(priv->regmap, priv->regs[ATTTE_REG], &val);
if (ret) {
return 0;
}
return sprintf(buf, "%d", (short)val);
}
static DEVICE_ATTR(log, S_IRUGO, max1720x_log_show, NULL);
static DEVICE_ATTR(nvmem, S_IRUGO, max1720x_nvmem_show, NULL);
static DEVICE_ATTR(atrate, S_IRUGO | S_IWUSR, max1720x_atrate_show,
max1720x_atrate_store);
static DEVICE_ATTR(attte, S_IRUGO, max1720x_attte_show, NULL);
static struct attribute *max1720x_attr[] = {
&dev_attr_log.attr,
&dev_attr_nvmem.attr,
&dev_attr_atrate.attr,
&dev_attr_attte.attr,
NULL
};
static struct attribute_group max1720x_attr_group = {
.attrs = max1720x_attr,
};
static int max1720x_get_temperature(struct max1720x_priv *priv, int *temp)
{
int ret;
u32 data;
struct regmap *map = priv->regmap;
ret = regmap_read(map, priv->regs[TEMP_REG], &data);
if (ret < 0)
return ret;
*temp = sign_extend32(data, 15);
/* The value is converted into centigrade scale */
/* Units of LSB = 1 / 256 degree Celsius */
*temp = (*temp * 10) >> 8;
return 0;
}
static int max1720x_set_temp_lower_limit(struct max1720x_priv *priv,
int temp)
{
int ret;
u32 data;
struct regmap *map = priv->regmap;
ret = regmap_read(map, priv->regs[TALRTTH_REG], &data);
if (ret < 0)
return ret;
/* Input in deci-centigrade, convert to centigrade */
temp /= 10;
data &= 0xFF00;
data |= (temp & 0xFF);
ret = regmap_write(map, priv->regs[TALRTTH_REG], data);
if (ret < 0)
return ret;
return 0;
}
static int max1720x_get_temperature_alert_min(struct max1720x_priv *priv,
int *temp)
{
int ret;
u32 data;
struct regmap *map = priv->regmap;
ret = regmap_read(map, priv->regs[TALRTTH_REG], &data);
if (ret < 0)
return ret;
/* Convert 1DegreeC LSB to 0.1DegreeC LSB */
*temp = sign_extend32(data & 0xff, 7) * 10;
return 0;
}
static int max1720x_set_temp_upper_limit(struct max1720x_priv *priv,
int temp)
{
int ret;
u32 data;
struct regmap *map = priv->regmap;
ret = regmap_read(map, priv->regs[TALRTTH_REG], &data);
if (ret < 0)
return ret;
/* Input in deci-centigrade, convert to centigrade */
temp /= 10;
data &= 0xFF;
data |= ((temp << 8) & 0xFF00);
ret = regmap_write(map, priv->regs[TALRTTH_REG], data);
if (ret < 0)
return ret;
return 0;
}
static int max1720x_get_temperature_alert_max(struct max1720x_priv *priv,
int *temp)
{
int ret;
u32 data;
struct regmap *map = priv->regmap;
ret = regmap_read(map, priv->regs[TALRTTH_REG], &data);
if (ret < 0)
return ret;
/* Convert 1DegreeC LSB to 0.1DegreeC LSB */
*temp = sign_extend32(data >> 8, 7) * 10;
return 0;
}
static int max1720x_get_battery_health(struct max1720x_priv *priv, int *health)
{
int temp, vavg, vbatt, ret;
u32 val;
ret = regmap_read(priv->regmap, priv->regs[AVGVCELL_REG], &val);
if (ret < 0)
goto health_error;
/* bits [0-3] unused */
vavg = max1720x_raw_voltage_to_uvolts(priv, val);
/* Convert to millivolts */
vavg /= 1000;
ret = regmap_read(priv->regmap, priv->regs[VCELL_REG], &val);
if (ret < 0)
goto health_error;
/* bits [0-3] unused */
vbatt = max1720x_raw_voltage_to_uvolts(priv, val);
/* Convert to millivolts */
vbatt /= 1000;
if (vavg < priv->pdata->volt_min) {
*health = POWER_SUPPLY_HEALTH_DEAD;
goto out;
}
if (vbatt > priv->pdata->volt_max + MAX1720X_VMAX_TOLERANCE) {
*health = POWER_SUPPLY_HEALTH_OVERVOLTAGE;
goto out;
}
ret = max1720x_get_temperature(priv, &temp);
if (ret < 0)
goto health_error;
if (temp <= priv->pdata->temp_min) {
*health = POWER_SUPPLY_HEALTH_COLD;
goto out;
}
if (temp >= priv->pdata->temp_max) {
*health = POWER_SUPPLY_HEALTH_OVERHEAT;
goto out;
}
*health = POWER_SUPPLY_HEALTH_GOOD;
out:
return 0;
health_error:
return ret;
}
static int max1730x_get_battery_health(struct max1720x_priv *priv, int *health)
{
int ret;
u32 val;
ret = regmap_read(priv->regmap, priv->regs[PROTSTATUS_REG], &val);
if (ret < 0)
return ret;
if ((val & MAX1730X_PROTSTATUS_RESCFAULT) ||
(val & MAX1730X_PROTSTATUS_RESDFAULT)) {
*health = POWER_SUPPLY_HEALTH_UNKNOWN;
} else if ((val & MAX1730X_PROTSTATUS_TOOHOTC) ||
(val & MAX1730X_PROTSTATUS_TOOHOTD) ||
(val & MAX1730X_PROTSTATUS_DIEHOT)) {
*health = POWER_SUPPLY_HEALTH_OVERHEAT;
} else if ((val & MAX1730X_PROTSTATUS_UVP) ||
(val & MAX1730X_PROTSTATUS_PERMFAIL) ||
(val & MAX1730X_PROTSTATUS_SHDN)) {
*health = POWER_SUPPLY_HEALTH_DEAD;
} else if (val & MAX1730X_PROTSTATUS_TOOCOLDC) {
*health = POWER_SUPPLY_HEALTH_COLD;
} else if (val & MAX1730X_PROTSTATUS_OVP) {
*health = POWER_SUPPLY_HEALTH_OVERVOLTAGE;
} else if ((val & MAX1730X_PROTSTATUS_QOVFLW) ||
(val & MAX1730X_PROTSTATUS_OCCP) ||
(val & MAX1730X_PROTSTATUS_ODCP)) {
*health = POWER_SUPPLY_HEALTH_UNSPEC_FAILURE;
} else if (val & MAX1730X_PROTSTATUS_CHGWDT) {
*health = POWER_SUPPLY_HEALTH_WATCHDOG_TIMER_EXPIRE;
} else {
*health = POWER_SUPPLY_HEALTH_GOOD;
}
return 0;
}
static int max1720x_get_min_capacity_alert_th(struct max1720x_priv *priv,
unsigned int *th)
{
int ret;
struct regmap *map = priv->regmap;
ret = regmap_read(map, priv->regs[SALRTTH_REG], th);
if (ret < 0)
return ret;
*th &= 0xFF;
return 0;
}
static int max1720x_set_min_capacity_alert_th(struct max1720x_priv *priv,
unsigned int th)
{
int ret;
unsigned int data;
struct regmap *map = priv->regmap;
ret = regmap_read(map, priv->regs[SALRTTH_REG], &data);
if (ret < 0)
return ret;
data &= 0xFF00;
data |= (th & 0xFF);
ret = regmap_write(map, priv->regs[SALRTTH_REG], data);
if (ret < 0)
return ret;
return 0;
}
static int max1720x_get_max_capacity_alert_th(struct max1720x_priv *priv,
unsigned int *th)
{
int ret;
struct regmap *map = priv->regmap;
ret = regmap_read(map, priv->regs[SALRTTH_REG], th);
if (ret < 0)
return ret;
*th >>= 8;
return 0;
}
static int max1720x_set_max_capacity_alert_th(struct max1720x_priv *priv,
unsigned int th)
{
int ret;
unsigned int data;
struct regmap *map = priv->regmap;
ret = regmap_read(map, priv->regs[SALRTTH_REG], &data);
if (ret < 0)
return ret;
data &= 0xFF;
data |= ((th & 0xFF) << 8);
ret = regmap_write(map, priv->regs[SALRTTH_REG], data);
if (ret < 0)
return ret;
return 0;
}
static int max1720x_get_property(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
struct max1720x_priv *priv = power_supply_get_drvdata(psy);
struct regmap *regmap = priv->regmap;
struct max1720x_platform_data *pdata = priv->pdata;
unsigned int reg;
int ret;
switch (psp) {
case POWER_SUPPLY_PROP_PRESENT:
ret = regmap_read(regmap, priv->regs[STATUS_REG], ®);
if (ret < 0)
return ret;
if (reg & MAX1720X_STATUS_BST)
val->intval = 0;
else
val->intval = 1;
break;
case POWER_SUPPLY_PROP_CYCLE_COUNT:
ret = regmap_read(regmap, priv->regs[CYCLES_REG], ®);
if (ret < 0)
return ret;
val->intval = reg * 100 / priv->cycles_reg_lsb_percent;
break;
case POWER_SUPPLY_PROP_VOLTAGE_MAX:
ret = regmap_read(regmap, priv->regs[MAXMINVOLT_REG], ®);
if (ret < 0)
return ret;
val->intval = reg >> 8;
val->intval *= 20000; /* Units of LSB = 20mV */
break;
case POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN:
ret = regmap_read(regmap, priv->regs[VEMPTY_REG], ®);
if (ret < 0)
return ret;
val->intval = reg >> 7;
val->intval *= 10000; /* Units of LSB = 10mV */
break;
case POWER_SUPPLY_PROP_STATUS:
if (pdata && priv->get_charging_status)
val->intval = priv->get_charging_status();
else
val->intval = POWER_SUPPLY_STATUS_UNKNOWN;
break;
case POWER_SUPPLY_PROP_VOLTAGE_NOW:
ret = regmap_read(regmap, priv->regs[VCELL_REG], ®);
if (ret < 0)
return ret;
val->intval = max1720x_raw_voltage_to_uvolts(priv, reg);
break;
case POWER_SUPPLY_PROP_VOLTAGE_AVG:
ret = regmap_read(regmap, priv->regs[AVGVCELL_REG], ®);
if (ret < 0)
return ret;
val->intval = max1720x_raw_voltage_to_uvolts(priv, reg);
break;
case POWER_SUPPLY_PROP_VOLTAGE_OCV:
ret = regmap_read(regmap, priv->regs[VFOCV_REG], ®);
if (ret < 0)
return ret;
val->intval = max1720x_raw_voltage_to_uvolts(priv, reg);
break;
case POWER_SUPPLY_PROP_CAPACITY:
ret = regmap_read(regmap, priv->regs[REPSOC_REG], ®);
if (ret < 0)
return ret;
val->intval = reg >> 8; /* RepSOC LSB: 1/256 % */
break;
case POWER_SUPPLY_PROP_CAPACITY_ALERT_MIN:
ret = max1720x_get_min_capacity_alert_th(priv, &val->intval);
if (ret < 0)
return ret;
break;
case POWER_SUPPLY_PROP_CAPACITY_ALERT_MAX:
ret = max1720x_get_max_capacity_alert_th(priv, &val->intval);
if (ret < 0)
return ret;
break;
case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
ret = regmap_read(regmap, priv->regs[DESIGNCAP_REG], ®);
if (ret < 0)
return ret;
val->intval = max1720x_raw_capacity_to_uamph(priv, reg);
break;
case POWER_SUPPLY_PROP_CHARGE_FULL:
ret = regmap_read(regmap, priv->regs[FULLCAPREP_REG], ®);
if (ret < 0)
return ret;
val->intval = max1720x_raw_capacity_to_uamph(priv, reg);
break;
case POWER_SUPPLY_PROP_CHARGE_COUNTER:
ret = regmap_read(regmap, priv->regs[QH_REG], ®);
if (ret < 0)
return ret;
/* This register is signed as oppose to other capacity type
* registers.
*/
val->intval = max1720x_raw_capacity_to_uamph(priv,
sign_extend32(reg, 15));
break;
case POWER_SUPPLY_PROP_CHARGE_NOW:
ret = regmap_read(regmap, priv->regs[REPCAP_REG], ®);
if (ret < 0)
return ret;
val->intval = max1720x_raw_capacity_to_uamph(priv, reg);
break;
case POWER_SUPPLY_PROP_TEMP:
ret = max1720x_get_temperature(priv, &val->intval);
if (ret < 0)
return ret;
break;
case POWER_SUPPLY_PROP_TEMP_ALERT_MIN:
ret = max1720x_get_temperature_alert_min(priv, &val->intval);
if (ret < 0)
return ret;
break;
case POWER_SUPPLY_PROP_TEMP_ALERT_MAX:
ret = max1720x_get_temperature_alert_max(priv, &val->intval);
if (ret < 0)
return ret;
break;
case POWER_SUPPLY_PROP_HEALTH:
if (priv->get_battery_health != 0) {
ret = priv->get_battery_health(priv, &val->intval);
if (ret < 0)
return ret;
} else {
val->intval = POWER_SUPPLY_HEALTH_UNKNOWN;
}
break;
case POWER_SUPPLY_PROP_CURRENT_NOW:
ret = regmap_read(regmap, priv->regs[CURRENT_REG], ®);
if (ret < 0)
return ret;
val->intval = max1720x_raw_current_to_uamps(priv, sign_extend32(reg, 15));
break;
case POWER_SUPPLY_PROP_CURRENT_AVG:
ret = regmap_read(regmap, priv->regs[AVGCURRENT_REG], ®);
if (ret < 0)
return ret;
val->intval = max1720x_raw_current_to_uamps(priv, sign_extend32(reg, 15));
break;
case POWER_SUPPLY_PROP_TIME_TO_EMPTY_AVG:
ret = regmap_read(regmap, priv->regs[TTE_REG], ®);
if (ret < 0)
return ret;
val->intval = (reg * 45) >> 3; /* TTE LSB: 5.625 sec */
break;
case POWER_SUPPLY_PROP_TIME_TO_FULL_AVG:
ret = regmap_read(regmap, priv->regs[TTF_REG], ®);
if (ret < 0)
return ret;
val->intval = (reg * 45) >> 3; /* TTF LSB: 5.625 sec */
break;
default:
return -EINVAL;
}
return 0;
}
static int max1720x_set_property(struct power_supply *psy,
enum power_supply_property psp,
const union power_supply_propval *val)
{
struct max1720x_priv *priv = power_supply_get_drvdata(psy);
int ret = 0;
switch (psp) {
case POWER_SUPPLY_PROP_TEMP_ALERT_MIN:
ret = max1720x_set_temp_lower_limit(priv, val->intval);
if (ret < 0)
dev_err(priv->dev, "temp alert min set fail:%d\n",
ret);
break;
case POWER_SUPPLY_PROP_TEMP_ALERT_MAX:
ret = max1720x_set_temp_upper_limit(priv, val->intval);
if (ret < 0)
dev_err(priv->dev, "temp alert max set fail:%d\n",
ret);
break;
case POWER_SUPPLY_PROP_CAPACITY_ALERT_MIN:
ret = max1720x_set_min_capacity_alert_th(priv, val->intval);
if (ret < 0)
dev_err(priv->dev, "capacity alert min set fail:%d\n",
ret);
break;
case POWER_SUPPLY_PROP_CAPACITY_ALERT_MAX:
ret = max1720x_set_max_capacity_alert_th(priv, val->intval);
if (ret < 0)
dev_err(priv->dev, "capacity alert max set fail:%d\n",
ret);
break;
default:
return -EINVAL;
}
return ret;
}
static int max1720x_property_is_writeable(struct power_supply *psy,
enum power_supply_property psp)
{
int ret;
switch (psp) {
case POWER_SUPPLY_PROP_TEMP_ALERT_MIN:
case POWER_SUPPLY_PROP_TEMP_ALERT_MAX:
case POWER_SUPPLY_PROP_CAPACITY_ALERT_MIN:
case POWER_SUPPLY_PROP_CAPACITY_ALERT_MAX:
ret = 1;
break;
default:
ret = 0;
}
return ret;
}
static irqreturn_t max1720x_irq_handler(int id, void *dev)
{
struct max1720x_priv *priv = dev;
u32 val;
/* Check alert type */
regmap_read(priv->regmap, priv->regs[STATUS_REG], &val);
if (val & MAX1720X_STATUS_SOC_MAX_ALRT)
dev_info(priv->dev, "Alert: SOC MAX!\n");
if (val & MAX1720X_STATUS_SOC_MIN_ALRT)
dev_info(priv->dev, "Alert: SOC MIN!\n");
if (val & MAX1720X_STATUS_TEMP_MAX_ALRT)
dev_info(priv->dev, "Alert: TEMP MAX!\n");
if (val & MAX1720X_STATUS_TEMP_MIN_ALRT)
dev_info(priv->dev, "Alert: TEMP MIN!\n");
if (val & MAX1720X_STATUS_VOLT_MAX_ALRT)
dev_info(priv->dev, "Alert: VOLT MAX!\n");
if (val & MAX1720X_STATUS_VOLT_MIN_ALRT)
dev_info(priv->dev, "Alert: VOLT MIN!\n");
if (val & MAX1720X_STATUS_CURR_MAX_ALRT)
dev_info(priv->dev, "Alert: CURR MAX!\n");
if (val & MAX1720X_STATUS_CURR_MIN_ALRT)
dev_info(priv->dev, "Alert: CURR MIN!\n");
/* Clear alerts */
regmap_write(priv->regmap, priv->regs[STATUS_REG],
val & MAX1720X_STATUS_ALRT_CLR_MASK);
power_supply_changed(priv->battery);
return IRQ_HANDLED;
}
static void max1720x_set_alert_thresholds(struct max1720x_priv *priv)
{
struct max1720x_platform_data *pdata = priv->pdata;
struct regmap *regmap = priv->regmap;
u32 val;
/* Set VAlrtTh */
val = (pdata->volt_min / 20);
val |= ((pdata->volt_max / 20) << 8);
regmap_write(regmap, priv->regs[VALRTTH_REG], val);
/* Set TAlrtTh */
val = pdata->temp_min & 0xFF;
val |= ((pdata->temp_max & 0xFF) << 8);
regmap_write(regmap, priv->regs[TALRTTH_REG], val);
/* Set SAlrtTh */
val = pdata->soc_min;
val |= (pdata->soc_max << 8);
regmap_write(regmap, priv->regs[SALRTTH_REG], val);
/* Set IAlrtTh */
val = (pdata->curr_min * pdata->rsense / 400) & 0xFF;
val |= (((pdata->curr_max * pdata->rsense / 400) & 0xFF) << 8);
regmap_write(regmap, priv->regs[IALRTTH_REG], val);
}
static int max1720x_init(struct max1720x_priv *priv)
{
struct regmap *regmap = priv->regmap;
int ret;
unsigned int reg;
u32 fgrev;
ret = regmap_read(regmap, priv->regs[VERSION_REG], &fgrev);
if (ret < 0)
return ret;
dev_info(priv->dev, "IC Version: 0x%04x\n", fgrev);
/* Optional step - alert threshold initialization */
max1720x_set_alert_thresholds(priv);
/* Clear Status.POR */
ret = regmap_read(regmap, priv->regs[STATUS_REG], ®);
if (ret < 0)
return ret;
ret = regmap_write(regmap, priv->regs[STATUS_REG],
reg & ~MAX1720X_STATUS_POR);
if (ret < 0)
return ret;
return 0;
}
static void max1720x_init_worker(struct work_struct *work)
{
struct max1720x_priv *priv = container_of(work,
struct max1720x_priv,
init_worker);
max1720x_init(priv);
}
static struct max1720x_platform_data *max1720x_parse_dt(struct device *dev)
{
struct device_node *np = dev->of_node;
struct max1720x_platform_data *pdata;
int ret;
pdata = devm_kzalloc(dev, sizeof(*pdata), GFP_KERNEL);
if (!pdata)
return NULL;
ret = of_property_read_u32(np, "talrt-min", &pdata->temp_min);
if (ret)
pdata->temp_min = -128; /* DegreeC */ /* Disable alert */
ret = of_property_read_u32(np, "talrt-max", &pdata->temp_max);
if (ret)
pdata->temp_max = 127; /* DegreeC */ /* Disable alert */
ret = of_property_read_u32(np, "valrt-min", &pdata->volt_min);
if (ret)
pdata->volt_min = 0; /* mV */ /* Disable alert */
ret = of_property_read_u32(np, "valrt-max", &pdata->volt_max);
if (ret)
pdata->volt_max = 5100; /* mV */ /* Disable alert */
ret = of_property_read_u32(np, "ialrt-min", &pdata->curr_min);
if (ret)
pdata->curr_min = -5120; /* mA */ /* Disable alert */
ret = of_property_read_u32(np, "ialrt-max", &pdata->curr_max);
if (ret)
pdata->curr_max = 5080; /* mA */ /* Disable alert */
ret = of_property_read_u32(np, "salrt-min", &pdata->soc_min);
if (ret)
pdata->soc_min = 0; /* Percent */ /* Disable alert */
ret = of_property_read_u32(np, "salrt-max", &pdata->soc_max);
if (ret)
pdata->soc_max = 255; /* Percent */ /* Disable alert */
ret = of_property_read_u32(np, "rsense", &pdata->rsense);
if (ret)
pdata->rsense = 10;
return pdata;
}
static const struct regmap_config max1720x_regmap = {
.reg_bits = 8,
.val_bits = 16,
.val_format_endian = REGMAP_ENDIAN_NATIVE,
};
static const struct power_supply_desc max1720x_fg_desc = {
.name = "max1720x_battery",
.type = POWER_SUPPLY_TYPE_BATTERY,
.properties = max1720x_battery_props,
.num_properties = ARRAY_SIZE(max1720x_battery_props),
.get_property = max1720x_get_property,
.set_property = max1720x_set_property,
.property_is_writeable = max1720x_property_is_writeable,
};
static int max1720x_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct i2c_adapter *adapter = to_i2c_adapter(client->dev.parent);
struct max1720x_priv *priv;
struct power_supply_config psy_cfg = {};
int ret;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_WORD_DATA))
return -EIO;
priv = devm_kzalloc(&client->dev, sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
priv->regs = chip_regs[id->driver_data];
priv->nvmem_high_addr = nvmem_high_addrs[id->driver_data];
priv->cycles_reg_lsb_percent = cycles_reg_lsb_percents[id->driver_data];
priv->get_battery_health = get_battery_health_handlers[id->driver_data];
if (client->dev.of_node)
priv->pdata = max1720x_parse_dt(&client->dev);
else
priv->pdata = client->dev.platform_data;
priv->dev = &client->dev;
i2c_set_clientdata(client, priv);
priv->client = client;
priv->regmap = devm_regmap_init_i2c(client, &max1720x_regmap);
if (IS_ERR(priv->regmap))
return PTR_ERR(priv->regmap);
INIT_WORK(&priv->init_worker, max1720x_init_worker);
schedule_work(&priv->init_worker);
psy_cfg.drv_data = priv;
priv->battery = power_supply_register(&client->dev,
&max1720x_fg_desc, &psy_cfg);
if (IS_ERR(priv->battery)) {
ret = PTR_ERR(priv->battery);
dev_err(&client->dev, "failed to register battery: %d\n", ret);
goto err_supply;
}
if (client->irq) {
ret = devm_request_threaded_irq(priv->dev, client->irq,
NULL,
max1720x_irq_handler,
IRQF_TRIGGER_FALLING |
IRQF_ONESHOT,
priv->battery->desc->name,
priv);
if (ret) {
dev_err(priv->dev, "Failed to request irq %d\n",
client->irq);
goto err_irq;
} else {
regmap_update_bits(priv->regmap, priv->regs[CONFIG_REG],
MAX1720X_CONFIG_ALRT_EN,
MAX1720X_CONFIG_ALRT_EN);
}
}
/* Create max1720x sysfs attributes */
priv->attr_grp = &max1720x_attr_group;
ret = sysfs_create_group(&priv->dev->kobj, priv->attr_grp);
if (ret) {
dev_err(priv->dev, "Failed to create attribute group [%d]\n",
ret);
priv->attr_grp = NULL;
goto err_attr;
}
return 0;
err_irq:
power_supply_unregister(priv->battery);
err_supply:
cancel_work_sync(&priv->init_worker);
err_attr:
sysfs_remove_group(&priv->dev->kobj, priv->attr_grp);
return ret;
}
static int max1720x_remove(struct i2c_client *client)
{
struct max1720x_priv *priv = i2c_get_clientdata(client);
cancel_work_sync(&priv->init_worker);
sysfs_remove_group(&priv->dev->kobj, priv->attr_grp);
power_supply_unregister(priv->battery);
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int max1720x_suspend(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
if (client->irq) {
disable_irq(client->irq);
enable_irq_wake(client->irq);
}
return 0;
}
static int max1720x_resume(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
if (client->irq) {
disable_irq_wake(client->irq);
enable_irq(client->irq);
}
return 0;
}
static SIMPLE_DEV_PM_OPS(max1720x_pm_ops, max1720x_suspend, max1720x_resume);
#define MAX1720X_PM_OPS (&max1720x_pm_ops)
#else
#define MAX1720X_PM_OPS NULL
#endif /* CONFIG_PM_SLEEP */
#ifdef CONFIG_OF
static const struct of_device_id max1720x_match[] = {
{ .compatible = "maxim,max17201", },
{ .compatible = "maxim,max17205", },
{ .compatible = "maxim,max17301", },
{ .compatible = "maxim,max17302", },
{ .compatible = "maxim,max17303", },
{ },
};
MODULE_DEVICE_TABLE(of, max1720x_match);
#endif
static const struct i2c_device_id max1720x_id[] = {
{ "max17201", ID_MAX1720X },
{ "max17205", ID_MAX1720X },
{ "max17301", ID_MAX1730X },
{ "max17302", ID_MAX1730X },
{ "max17303", ID_MAX1730X },
{ },
};
MODULE_DEVICE_TABLE(i2c, max1720x_id);
static struct i2c_driver max1720x_i2c_driver = {
.driver = {
.name = DRV_NAME,
.of_match_table = of_match_ptr(max1720x_match),
.pm = MAX1720X_PM_OPS,
},
.probe = max1720x_probe,
.remove = max1720x_remove,
.id_table = max1720x_id,
};
module_i2c_driver(max1720x_i2c_driver);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mahir Ozturk <mahir.ozturk@maximintegrated.com>");
MODULE_DESCRIPTION("Maxim MAX17201/5 and MAX17301/2/3 Fuel Gauge driver");
| 30,367 | C | 23.912223 | 80 | 0.662331 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Mangdang/LCD/ST7789.py | # ST7789 IPS LCD (320x240) driver
import numbers
import time
import numpy as np
import sys
import os
from PIL import Image
from PIL import ImageDraw
sys.path.append("/home/ubuntu/Robotics/QuadrupedRobot")
sys.path.extend([os.path.join(root, name) for root, dirs, _ in os.walk("/home/ubuntu/Robotics/QuadrupedRobot") for name in dirs])
import Mangdang.Adafruit_GPIO as GPIO
import Mangdang.Adafruit_GPIO.SPI as SPI
from Mangdang.LCD.gif import AnimatedGif
SPI_CLOCK_HZ = 31200000 # 31.2 MHz
# Constants for interacting with display registers.
ST7789_TFTWIDTH = 320
ST7789_TFTHEIGHT = 240
ST7789_NOP = 0x00
ST7789_SWRESET = 0x01
ST7789_RDDID = 0x04
ST7789_RDDST = 0x09
ST7789_RDDPM = 0x0A
ST7789_RDDMADCTL = 0x0B
ST7789_RDDCOLMOD = 0x0C
ST7789_RDDIM = 0x0D
ST7789_RDDSM = 0x0E
ST7789_RDDSDR = 0x0F
ST7789_SLPIN = 0x10
ST7789_SLPOUT = 0x11
ST7789_PTLON = 0x12
ST7789_NORON = 0x13
ST7789_INVOFF = 0x20
ST7789_INVON = 0x21
ST7789_GAMSET = 0x26
ST7789_DISPOFF = 0x28
ST7789_DISPON = 0x29
ST7789_CASET = 0x2A
ST7789_RASET = 0x2B
ST7789_RAMWR = 0x2C
ST7789_RAMRD = 0x2E
ST7789_PTLAR = 0x30
ST7789_VSCRDEF = 0x33
ST7789_TEOFF = 0x34
ST7789_TEON = 0x35
ST7789_MADCTL = 0x36
ST7789_VSCRSADD = 0x37
ST7789_IDMOFF = 0x38
ST7789_IDMON = 0x39
ST7789_COLMOD = 0x3A
ST7789_RAMWRC = 0x3C
ST7789_RAMRDC = 0x3E
ST7789_TESCAN = 0x44
ST7789_RDTESCAN = 0x45
ST7789_WRDISBV = 0x51
ST7789_RDDISBV = 0x52
ST7789_WRCTRLD = 0x53
ST7789_RDCTRLD = 0x54
ST7789_WRCACE = 0x55
ST7789_RDCABC = 0x56
ST7789_WRCABCMB = 0x5E
ST7789_RDCABCMB = 0x5F
ST7789_RDABCSDR = 0x68
ST7789_RDID1 = 0xDA
ST7789_RDID2 = 0xDB
ST7789_RDID3 = 0xDC
ST7789_RAMCTRL = 0xB0
ST7789_RGBCTRL = 0xB1
ST7789_PORCTRL = 0xB2
ST7789_FRCTRL1 = 0xB3
ST7789_GCTRL = 0xB7
ST7789_DGMEN = 0xBA
ST7789_VCOMS = 0xBB
ST7789_LCMCTRL = 0xC0
ST7789_IDSET = 0xC1
ST7789_VDVVRHEN = 0xC2
ST7789_VRHS = 0xC3
ST7789_VDVSET = 0xC4
ST7789_VCMOFSET = 0xC5
ST7789_FRCTR2 = 0xC6
ST7789_CABCCTRL = 0xC7
ST7789_REGSEL1 = 0xC8
ST7789_REGSEL2 = 0xCA
ST7789_PWMFRSEL = 0xCC
ST7789_PWCTRL1 = 0xD0
ST7789_VAPVANEN = 0xD2
ST7789_CMD2EN = 0xDF5A6902
ST7789_PVGAMCTRL = 0xE0
ST7789_NVGAMCTRL = 0xE1
ST7789_DGMLUTR = 0xE2
ST7789_DGMLUTB = 0xE3
ST7789_GATECTRL = 0xE4
ST7789_PWCTRL2 = 0xE8
ST7789_EQCTRL = 0xE9
ST7789_PROMCTRL = 0xEC
ST7789_PROMEN = 0xFA
ST7789_NVMSET = 0xFC
ST7789_PROMACT = 0xFE
# Colours for convenience
ST7789_BLACK = 0x0000 # 0b 00000 000000 00000
ST7789_BLUE = 0x001F # 0b 00000 000000 11111
ST7789_GREEN = 0x07E0 # 0b 00000 111111 00000
ST7789_RED = 0xF800 # 0b 11111 000000 00000
ST7789_CYAN = 0x07FF # 0b 00000 111111 11111
ST7789_MAGENTA = 0xF81F # 0b 11111 000000 11111
ST7789_YELLOW = 0xFFE0 # 0b 11111 111111 00000
ST7789_WHITE = 0xFFFF # 0b 11111 111111 11111
def color565(r, g, b):
"""Convert red, green, blue components to a 16-bit 565 RGB value. Components
should be values 0 to 255.
"""
return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3)
def image_to_data(image):
"""Generator function to convert a PIL image to 16-bit 565 RGB bytes."""
# NumPy is much faster at doing this. NumPy code provided by:
# Keith (https://www.blogger.com/profile/02555547344016007163)
pb = np.array(image.convert('RGB')).astype('uint16')
color = ((pb[:,:,0] & 0xF8) << 8) | ((pb[:,:,1] & 0xFC) << 3) | (pb[:,:,2] >> 3)
return np.dstack(((color >> 8) & 0xFF, color & 0xFF)).flatten().tolist()
class ST7789(object):
"""Representation of an ST7789 IPS LCD."""
def __init__(self, rst, dc, led):
"""Create an instance of the display using SPI communication. Must
provide the GPIO pin number for the D/C pin and the SPI driver. Can
optionally provide the GPIO pin number for the reset pin as the rst
parameter.
"""
SPI_PORT = 0
SPI_DEVICE = 0
SPI_MODE = 0b11
SPI_SPEED_HZ = 40000000
self._spi = SPI.SpiDev(SPI_PORT, SPI_DEVICE, max_speed_hz=SPI_SPEED_HZ)
self._rst = rst
self._dc = dc
self._led = led
self._gpio = None
self.width = ST7789_TFTWIDTH
self.height = ST7789_TFTHEIGHT
if self._gpio is None:
self._gpio = GPIO.get_platform_gpio()
# Set DC as output.
self._gpio.setup(self._dc, GPIO.OUT)
# Setup reset as output (if provided).
if self._rst is not None:
self._gpio.setup(self._rst, GPIO.OUT)
# Turn on the backlight LED
self._gpio.setup(self._led, GPIO.OUT)
# Set SPI to mode 0, MSB first.
self._spi.set_mode(SPI_MODE)
self._spi.set_bit_order(SPI.MSBFIRST)
self._spi.set_clock_hz(SPI_CLOCK_HZ)
# Create an image buffer.
self.buffer = Image.new('RGB', (self.width, self.height))
def send(self, data, is_data=True, chunk_size=4096):
"""Write a byte or array of bytes to the display. Is_data parameter
controls if byte should be interpreted as display data (True) or command
data (False). Chunk_size is an optional size of bytes to write in a
single SPI transaction, with a default of 4096.
"""
# Set DC low for command, high for data.
self._gpio.output(self._dc, is_data)
# Convert scalar argument to list so either can be passed as parameter.
if isinstance(data, numbers.Number):
data = [data & 0xFF]
# Write data a chunk at a time.
for start in range(0, len(data), chunk_size):
end = min(start+chunk_size, len(data))
self._spi.write(data[start:end])
def command(self, data):
"""Write a byte or array of bytes to the display as command data."""
self.send(data, False)
def data(self, data):
"""Write a byte or array of bytes to the display as display data."""
self.send(data, True)
def reset(self):
"""Reset the display, if reset pin is connected."""
if self._rst is not None:
self._gpio.set_high(self._rst)
time.sleep(0.100)
self._gpio.set_low(self._rst)
time.sleep(0.100)
self._gpio.set_high(self._rst)
time.sleep(0.100)
def _init(self):
# Initialize the display. Broken out as a separate function so it can
# be overridden by other displays in the future.
time.sleep(0.012)
self.command(0x11)
time.sleep(0.150)
self.command(0x36)
self.data(0xA0)
self.data(0x00)
self.command(0x3A)
self.data(0x05)
self.command(0xB2)
self.data(0x0C)
self.data(0x0C)
self.data(0x00)
self.data(0x33)
self.data(0x33)
self.command(0xB7)
self.data(0x35)
## ---------------------------------ST7789S Power setting - ----------------------------
self.command(0xBB)
self.data(0x29)
# self.command(0xC0)
# self.data(0x2C)
self.command(0xC2)
self.data(0x01)
self.command(0xC3)
self.data(0x19)
self.command(0xC4)
self.data(0x20)
self.command(0xC5)
self.data(0x1A)
self.command(0xC6)
self.data(0x1F) ## 0x0F:60Hz
# self.command(0xCA)
# self.data(0x0F)
#
# self.command(0xC8)
# self.data(0x08)
#
# self.command(0x55)
# self.data(0x90)
self.command(0xD0)
self.data(0xA4)
self.data(0xA1)
## --------------------------------ST7789S gamma setting - -----------------------------
self.command(0xE0)
self.data(0xD0)
self.data(0x08)
self.data(0x0E)
self.data(0x09)
self.data(0x09)
self.data(0x05)
self.data(0x31)
self.data(0x33)
self.data(0x48)
self.data(0x17)
self.data(0x14)
self.data(0x15)
self.data(0x31)
self.data(0x34)
self.command(0xE1)
self.data(0xD0)
self.data(0x08)
self.data(0x0E)
self.data(0x09)
self.data(0x09)
self.data(0x15)
self.data(0x31)
self.data(0x33)
self.data(0x48)
self.data(0x17)
self.data(0x14)
self.data(0x15)
self.data(0x31)
self.data(0x34)
self.command(0x21)
self.command(0x29)
time.sleep(0.100) # 100 ms
self._gpio.set_high(self._led)
def begin(self):
"""Initialize the display. Should be called once before other calls that
interact with the display are called.
"""
self.reset()
self._init()
def set_window(self, x0=0, y0=0, x1=None, y1=None):
"""Set the pixel address window for proceeding drawing commands. x0 and
x1 should define the minimum and maximum x pixel bounds. y0 and y1
should define the minimum and maximum y pixel bound. If no parameters
are specified the default will be to update the entire display from 0,0
to width-1,height-1.
"""
if x1 is None:
x1 = self.width-1
if y1 is None:
y1 = self.height-1
self.command(ST7789_CASET) # Column addr set
self.data(x0 >> 8)
self.data(x0) # XSTART
self.data(x1 >> 8)
self.data(x1) # XEND
self.command(ST7789_RASET) # Row addr set
self.data(y0 >> 8)
self.data(y0) # YSTART
self.data(y1 >> 8)
self.data(y1) # YEND
self.command(ST7789_RAMWR) # write to RAM
#def display(self, image=None):
def display(self, image=None, x0=0, y0=0, x1=None, y1=None):
"""Write the display buffer or provided image to the hardware. If no
image parameter is provided the display buffer will be written to the
hardware. If an image is provided, it should be RGB format and the
same dimensions as the display hardware.
"""
# By default write the internal buffer to the display.
if image is None:
image = self.buffer
# Set address bounds to entire display.
#self.set_window()
if x1 is None:
x1 = self.width-1
if y1 is None:
y1 = self.height-1
self.set_window(x0, y0, x1, y1)
#image.thumbnail((x1-x0+1, y1-y0+1), Image.ANTIALIAS)
# Convert image to array of 16bit 565 RGB data bytes.
# Unfortunate that this copy has to occur, but the SPI byte writing
# function needs to take an array of bytes and PIL doesn't natively
# store images in 16-bit 565 RGB format.
pixelbytes = list(image_to_data(image))
# Write data to hardware.
self.data(pixelbytes)
def clear(self, color=(0,0,0)):
"""Clear the image buffer to the specified RGB color (default black)."""
width, height = self.buffer.size
self.buffer.putdata([color]*(width*height))
def draw(self):
"""Return a PIL ImageDraw instance for 2D drawing on the image buffer."""
return ImageDraw.Draw(self.buffer)
| 11,573 | Python | 29.781915 | 129 | 0.584723 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Mangdang/LCD/gif.py | import os
import time
from PIL import Image
from PIL import ImageOps
class Frame:
def __init__(self, duration=0):
self.duration = duration
self.image = None
class AnimatedGif:
def __init__(self, display, width=None, height=None, folder=None):
self._frame_count = 0
self._loop = 0
self._index = 0
self._duration = 0
self._gif_files = []
self._frames = []
self._gif_folder = folder
if width is not None:
self._width = width
else:
self._width = display.width
if height is not None:
self._height = height
else:
self._height = display.height
self.display = display
if folder is not None:
self.load_files(folder)
self.preload()
def advance(self):
self._index = (self._index + 1) % len(self._gif_files)
def back(self):
self._index = (self._index - 1 + len(self._gif_files)) % len(self._gif_files)
def load_files(self, folder):
gif_files = [f for f in os.listdir(folder) if f.endswith(".gif")]
for gif_file in gif_files:
image = Image.open(folder + gif_file)
# Only add animated Gifs
if image.is_animated:
self._gif_files.append(gif_file)
#print("Found", self._gif_files)
if not self._gif_files:
print("No Gif files found in current folder")
exit() # pylint: disable=consider-using-sys-exit
def preload(self):
image = Image.open(self._gif_folder + self._gif_files[self._index])
#print("Loading {}...".format(self._gif_files[self._index]))
if "duration" in image.info:
self._duration = image.info["duration"]
else:
self._duration = 0
if "loop" in image.info:
self._loop = image.info["loop"]
else:
self._loop = 1
self._frame_count = image.n_frames
del self._frames[:]
for frame in range(self._frame_count):
image.seek(frame)
# Create blank image for drawing.
# Make sure to create image with mode 'RGB' for full color.
frame_object = Frame(duration=self._duration)
if "duration" in image.info:
frame_object.duration = image.info["duration"]
frame_object.image = ImageOps.pad( # pylint: disable=no-member
image.convert("RGB"),
(self._width, self._height),
method=Image.NEAREST,
color=(0, 0, 0),
centering=(0.5, 0.5),
)
self._frames.append(frame_object)
def play(self):
# Check if we have loaded any files first
if not self._gif_files:
print("There are no Gif Images loaded to Play")
return False
#while True:
for frame_object in self._frames:
start_time = time.time()
self.display.display(frame_object.image)
while time.time() < (start_time + frame_object.duration / 1000):
pass
if self._loop == 1:
return True
if self._loop > 0:
self._loop -= 1
def run(self):
while True:
auto_advance = self.play()
if auto_advance:
self.advance()
| 3,404 | Python | 31.740384 | 85 | 0.529083 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/PupperCommand/joystick.py | from UDPComms import Publisher, Subscriber, timeout
from PS4Joystick import Joystick
import time
## you need to git clone the PS4Joystick repo and run `sudo bash install.sh`
## Configurable ##
MESSAGE_RATE = 20
PUPPER_COLOR = {"red":0, "blue":0, "green":255}
joystick_pub = Publisher(8830,65530)
joystick_subcriber = Subscriber(8840, timeout=0.01)
joystick = Joystick()
joystick.led_color(**PUPPER_COLOR)
while True:
values = joystick.get_input()
left_y = -values["left_analog_y"]
right_y = -values["right_analog_y"]
right_x = values["right_analog_x"]
left_x = values["left_analog_x"]
L2 = values["l2_analog"]
R2 = values["r2_analog"]
R1 = values["button_r1"]
L1 = values["button_l1"]
square = values["button_square"]
x = values["button_cross"]
circle = values["button_circle"]
triangle = values["button_triangle"]
dpadx = values["dpad_right"] - values["dpad_left"]
dpady = values["dpad_up"] - values["dpad_down"]
msg = {
"ly": left_y,
"lx": left_x,
"rx": right_x,
"ry": right_y,
"L2": L2,
"R2": R2,
"R1": R1,
"L1": L1,
"dpady": dpady,
"dpadx": dpadx,
"x": x,
"square": square,
"circle": circle,
"triangle": triangle,
"message_rate": MESSAGE_RATE,
}
joystick_pub.send(msg)
try:
msg = joystick_subcriber.get()
joystick.led_color(**msg["ps4_color"])
except timeout:
pass
time.sleep(1 / MESSAGE_RATE)
| 1,539 | Python | 22.692307 | 76 | 0.581546 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/PupperCommand/README.md | # PupperCommand
## Installation
```shell
git clone https://github.com/stanfordroboticsclub/PupperCommand.git
cd PupperCommand
sudo bash install.sh
```
Then clone https://github.com/stanfordroboticsclub/PS4Joystick/ and follow the installation instructions in the README.
## Starting the joystick publisher
1. The ```install.sh``` script makes the Raspberry Pi automatically look to pair and connect to PS4 joysticks on boot.
2. So once the Raspberry Pi turns on, put the PS4 controller into pairing mode by holding the share and PS button at the same time. The light should start blinking in bursts of two.
3. By around 10 seconds, the joystick should have paired with the Raspberry Pi and the front light on the joystick will change to whatever color you specify in the ```joystick.py``` script.
## Debugging
To see if the controller is publishing to the Rover topic use:
```shell
rover peek 8830
```
You can also check the status of the system daemon (systemd) running the ```joystick.py``` script by doing
```shell
sudo systemctl status joystick
```
If it shows that the service failed, you can try
```shell
sudo systemctl stop joystick
sudo systemctl start joystick
```
## Notes
If a packet is lost over the joystick connection, the PS4Joystick code will raise an exception and cause the program to exit. Systemd will then restart the ```joystick.py``` script, which means you will have to re-pair the joystick (hold share + ps4 button until double blinking).
| 1,473 | Markdown | 42.35294 | 281 | 0.773931 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/Legacy/ImageOps.py | #
# The Python Imaging Library.
# $Id$
#
# standard image operations
#
# History:
# 2001-10-20 fl Created
# 2001-10-23 fl Added autocontrast operator
# 2001-12-18 fl Added Kevin's fit operator
# 2004-03-14 fl Fixed potential division by zero in equalize
# 2005-05-05 fl Fixed equalize for low number of values
#
# Copyright (c) 2001-2004 by Secret Labs AB
# Copyright (c) 2001-2004 by Fredrik Lundh
#
# See the README file for information on usage and redistribution.
#
from . import Image
import operator
import functools
import warnings
#
# helpers
def _border(border):
if isinstance(border, tuple):
if len(border) == 2:
left, top = right, bottom = border
elif len(border) == 4:
left, top, right, bottom = border
else:
left = top = right = bottom = border
return left, top, right, bottom
def _color(color, mode):
if isStringType(color):
from . import ImageColor
color = ImageColor.getcolor(color, mode)
return color
def _lut(image, lut):
if image.mode == "P":
# FIXME: apply to lookup table, not image data
raise NotImplementedError("mode P support coming soon")
elif image.mode in ("L", "RGB"):
if image.mode == "RGB" and len(lut) == 256:
lut = lut + lut + lut
return image.point(lut)
else:
raise IOError("not supported for this image mode")
#
# actions
def autocontrast(image, cutoff=0, ignore=None):
"""
Maximize (normalize) image contrast. This function calculates a
histogram of the input image, removes **cutoff** percent of the
lightest and darkest pixels from the histogram, and remaps the image
so that the darkest pixel becomes black (0), and the lightest
becomes white (255).
:param image: The image to process.
:param cutoff: How many percent to cut off from the histogram.
:param ignore: The background pixel value (use None for no background).
:return: An image.
"""
histogram = image.histogram()
lut = []
for layer in range(0, len(histogram), 256):
h = histogram[layer:layer+256]
if ignore is not None:
# get rid of outliers
try:
h[ignore] = 0
except TypeError:
# assume sequence
for ix in ignore:
h[ix] = 0
if cutoff:
# cut off pixels from both ends of the histogram
# get number of pixels
n = 0
for ix in range(256):
n = n + h[ix]
# remove cutoff% pixels from the low end
cut = n * cutoff // 100
for lo in range(256):
if cut > h[lo]:
cut = cut - h[lo]
h[lo] = 0
else:
h[lo] -= cut
cut = 0
if cut <= 0:
break
# remove cutoff% samples from the hi end
cut = n * cutoff // 100
for hi in range(255, -1, -1):
if cut > h[hi]:
cut = cut - h[hi]
h[hi] = 0
else:
h[hi] -= cut
cut = 0
if cut <= 0:
break
# find lowest/highest samples after preprocessing
for lo in range(256):
if h[lo]:
break
for hi in range(255, -1, -1):
if h[hi]:
break
if hi <= lo:
# don't bother
lut.extend(list(range(256)))
else:
scale = 255.0 / (hi - lo)
offset = -lo * scale
for ix in range(256):
ix = int(ix * scale + offset)
if ix < 0:
ix = 0
elif ix > 255:
ix = 255
lut.append(ix)
return _lut(image, lut)
def colorize(image, black, white, mid=None, blackpoint=0,
whitepoint=255, midpoint=127):
"""
Colorize grayscale image.
This function calculates a color wedge which maps all black pixels in
the source image to the first color and all white pixels to the
second color. If **mid** is specified, it uses three-color mapping.
The **black** and **white** arguments should be RGB tuples or color names;
optionally you can use three-color mapping by also specifying **mid**.
Mapping positions for any of the colors can be specified
(e.g. **blackpoint**), where these parameters are the integer
value corresponding to where the corresponding color should be mapped.
These parameters must have logical order, such that
**blackpoint** <= **midpoint** <= **whitepoint** (if **mid** is specified).
:param image: The image to colorize.
:param black: The color to use for black input pixels.
:param white: The color to use for white input pixels.
:param mid: The color to use for midtone input pixels.
:param blackpoint: an int value [0, 255] for the black mapping.
:param whitepoint: an int value [0, 255] for the white mapping.
:param midpoint: an int value [0, 255] for the midtone mapping.
:return: An image.
"""
# Initial asserts
assert image.mode == "L"
if mid is None:
assert 0 <= blackpoint <= whitepoint <= 255
else:
assert 0 <= blackpoint <= midpoint <= whitepoint <= 255
# Define colors from arguments
black = _color(black, "RGB")
white = _color(white, "RGB")
if mid is not None:
mid = _color(mid, "RGB")
# Empty lists for the mapping
red = []
green = []
blue = []
# Create the low-end values
for i in range(0, blackpoint):
red.append(black[0])
green.append(black[1])
blue.append(black[2])
# Create the mapping (2-color)
if mid is None:
range_map = range(0, whitepoint - blackpoint)
for i in range_map:
red.append(black[0] + i * (white[0] - black[0]) // len(range_map))
green.append(black[1] + i * (white[1] - black[1]) // len(range_map))
blue.append(black[2] + i * (white[2] - black[2]) // len(range_map))
# Create the mapping (3-color)
else:
range_map1 = range(0, midpoint - blackpoint)
range_map2 = range(0, whitepoint - midpoint)
for i in range_map1:
red.append(black[0] + i * (mid[0] - black[0]) // len(range_map1))
green.append(black[1] + i * (mid[1] - black[1]) // len(range_map1))
blue.append(black[2] + i * (mid[2] - black[2]) // len(range_map1))
for i in range_map2:
red.append(mid[0] + i * (white[0] - mid[0]) // len(range_map2))
green.append(mid[1] + i * (white[1] - mid[1]) // len(range_map2))
blue.append(mid[2] + i * (white[2] - mid[2]) // len(range_map2))
# Create the high-end values
for i in range(0, 256 - whitepoint):
red.append(white[0])
green.append(white[1])
blue.append(white[2])
# Return converted image
image = image.convert("RGB")
return _lut(image, red + green + blue)
def pad(image, size, method=Image.NEAREST, color=None, centering=(0.5, 0.5)):
"""
Returns a sized and padded version of the image, expanded to fill the
requested aspect ratio and size.
:param image: The image to size and crop.
:param size: The requested output size in pixels, given as a
(width, height) tuple.
:param method: What resampling method to use. Default is
:py:attr:`PIL.Image.NEAREST`.
:param color: The background color of the padded image.
:param centering: Control the position of the original image within the
padded version.
(0.5, 0.5) will keep the image centered
(0, 0) will keep the image aligned to the top left
(1, 1) will keep the image aligned to the bottom
right
:return: An image.
"""
im_ratio = image.width / image.height
dest_ratio = float(size[0]) / size[1]
if im_ratio == dest_ratio:
out = image.resize(size, resample=method)
else:
out = Image.new(image.mode, size, color)
if im_ratio > dest_ratio:
new_height = int(image.height / image.width * size[0])
if new_height != size[1]:
image = image.resize((size[0], new_height), resample=method)
y = int((size[1] - new_height) * max(0, min(centering[1], 1)))
out.paste(image, (0, y))
else:
new_width = int(image.width / image.height * size[1])
if new_width != size[0]:
image = image.resize((new_width, size[1]), resample=method)
x = int((size[0] - new_width) * max(0, min(centering[0], 1)))
out.paste(image, (x, 0))
return out
def crop(image, border=0):
"""
Remove border from image. The same amount of pixels are removed
from all four sides. This function works on all image modes.
.. seealso:: :py:meth:`~PIL.Image.Image.crop`
:param image: The image to crop.
:param border: The number of pixels to remove.
:return: An image.
"""
left, top, right, bottom = _border(border)
return image.crop(
(left, top, image.size[0]-right, image.size[1]-bottom)
)
def scale(image, factor, resample=Image.NEAREST):
"""
Returns a rescaled image by a specific factor given in parameter.
A factor greater than 1 expands the image, between 0 and 1 contracts the
image.
:param image: The image to rescale.
:param factor: The expansion factor, as a float.
:param resample: An optional resampling filter. Same values possible as
in the PIL.Image.resize function.
:returns: An :py:class:`~PIL.Image.Image` object.
"""
if factor == 1:
return image.copy()
elif factor <= 0:
raise ValueError("the factor must be greater than 0")
else:
size = (int(round(factor * image.width)),
int(round(factor * image.height)))
return image.resize(size, resample)
def deform(image, deformer, resample=Image.BILINEAR):
"""
Deform the image.
:param image: The image to deform.
:param deformer: A deformer object. Any object that implements a
**getmesh** method can be used.
:param resample: An optional resampling filter. Same values possible as
in the PIL.Image.transform function.
:return: An image.
"""
return image.transform(
image.size, Image.MESH, deformer.getmesh(image), resample
)
def equalize(image, mask=None):
"""
Equalize the image histogram. This function applies a non-linear
mapping to the input image, in order to create a uniform
distribution of grayscale values in the output image.
:param image: The image to equalize.
:param mask: An optional mask. If given, only the pixels selected by
the mask are included in the analysis.
:return: An image.
"""
if image.mode == "P":
image = image.convert("RGB")
h = image.histogram(mask)
lut = []
for b in range(0, len(h), 256):
histo = [_f for _f in h[b:b+256] if _f]
if len(histo) <= 1:
lut.extend(list(range(256)))
else:
step = (functools.reduce(operator.add, histo) - histo[-1]) // 255
if not step:
lut.extend(list(range(256)))
else:
n = step // 2
for i in range(256):
lut.append(n // step)
n = n + h[i+b]
return _lut(image, lut)
def expand(image, border=0, fill=0):
"""
Add border to the image
:param image: The image to expand.
:param border: Border width, in pixels.
:param fill: Pixel fill value (a color value). Default is 0 (black).
:return: An image.
"""
left, top, right, bottom = _border(border)
width = left + image.size[0] + right
height = top + image.size[1] + bottom
out = Image.new(image.mode, (width, height), _color(fill, image.mode))
out.paste(image, (left, top))
return out
def fit(image, size, method=Image.NEAREST, bleed=0.0, centering=(0.5, 0.5)):
"""
Returns a sized and cropped version of the image, cropped to the
requested aspect ratio and size.
This function was contributed by Kevin Cazabon.
:param image: The image to size and crop.
:param size: The requested output size in pixels, given as a
(width, height) tuple.
:param method: What resampling method to use. Default is
:py:attr:`PIL.Image.NEAREST`.
:param bleed: Remove a border around the outside of the image from all
four edges. The value is a decimal percentage (use 0.01 for
one percent). The default value is 0 (no border).
Cannot be greater than or equal to 0.5.
:param centering: Control the cropping position. Use (0.5, 0.5) for
center cropping (e.g. if cropping the width, take 50% off
of the left side, and therefore 50% off the right side).
(0.0, 0.0) will crop from the top left corner (i.e. if
cropping the width, take all of the crop off of the right
side, and if cropping the height, take all of it off the
bottom). (1.0, 0.0) will crop from the bottom left
corner, etc. (i.e. if cropping the width, take all of the
crop off the left side, and if cropping the height take
none from the top, and therefore all off the bottom).
:return: An image.
"""
# by Kevin Cazabon, Feb 17/2000
# kevin@cazabon.com
# http://www.cazabon.com
# ensure centering is mutable
centering = list(centering)
if not 0.0 <= centering[0] <= 1.0:
centering[0] = 0.5
if not 0.0 <= centering[1] <= 1.0:
centering[1] = 0.5
if not 0.0 <= bleed < 0.5:
bleed = 0.0
# calculate the area to use for resizing and cropping, subtracting
# the 'bleed' around the edges
# number of pixels to trim off on Top and Bottom, Left and Right
bleed_pixels = (bleed * image.size[0], bleed * image.size[1])
live_size = (image.size[0] - bleed_pixels[0] * 2,
image.size[1] - bleed_pixels[1] * 2)
# calculate the aspect ratio of the live_size
live_size_ratio = float(live_size[0]) / live_size[1]
# calculate the aspect ratio of the output image
output_ratio = float(size[0]) / size[1]
# figure out if the sides or top/bottom will be cropped off
if live_size_ratio >= output_ratio:
# live_size is wider than what's needed, crop the sides
crop_width = output_ratio * live_size[1]
crop_height = live_size[1]
else:
# live_size is taller than what's needed, crop the top and bottom
crop_width = live_size[0]
crop_height = live_size[0] / output_ratio
# make the crop
crop_left = bleed_pixels[0] + (live_size[0]-crop_width) * centering[0]
crop_top = bleed_pixels[1] + (live_size[1]-crop_height) * centering[1]
crop = (
crop_left, crop_top,
crop_left + crop_width, crop_top + crop_height
)
# resize the image and return it
return image.resize(size, method, box=crop)
def flip(image):
"""
Flip the image vertically (top to bottom).
:param image: The image to flip.
:return: An image.
"""
return image.transpose(Image.FLIP_TOP_BOTTOM)
def grayscale(image):
"""
Convert the image to grayscale.
:param image: The image to convert.
:return: An image.
"""
return image.convert("L")
def invert(image):
"""
Invert (negate) the image.
:param image: The image to invert.
:return: An image.
"""
lut = []
for i in range(256):
lut.append(255-i)
return _lut(image, lut)
def mirror(image):
"""
Flip image horizontally (left to right).
:param image: The image to mirror.
:return: An image.
"""
return image.transpose(Image.FLIP_LEFT_RIGHT)
def posterize(image, bits):
"""
Reduce the number of bits for each color channel.
:param image: The image to posterize.
:param bits: The number of bits to keep for each channel (1-8).
:return: An image.
"""
lut = []
mask = ~(2**(8-bits)-1)
for i in range(256):
lut.append(i & mask)
return _lut(image, lut)
def solarize(image, threshold=128):
"""
Invert all pixel values above a threshold.
:param image: The image to solarize.
:param threshold: All pixels above this greyscale level are inverted.
:return: An image.
"""
lut = []
for i in range(256):
if i < threshold:
lut.append(i)
else:
lut.append(255-i)
return _lut(image, lut)
# --------------------------------------------------------------------
# PIL USM components, from Kevin Cazabon.
def gaussian_blur(im, radius=None):
""" PIL_usm.gblur(im, [radius])"""
warnings.warn(
'PIL.ImageOps.gaussian_blur is deprecated. '
'Use PIL.ImageFilter.GaussianBlur instead. '
'This function will be removed in a future version.',
DeprecationWarning
)
if radius is None:
radius = 5.0
im.load()
return im.im.gaussian_blur(radius)
def gblur(im, radius=None):
""" PIL_usm.gblur(im, [radius])"""
warnings.warn(
'PIL.ImageOps.gblur is deprecated. '
'Use PIL.ImageFilter.GaussianBlur instead. '
'This function will be removed in a future version.',
DeprecationWarning
)
return gaussian_blur(im, radius)
def unsharp_mask(im, radius=None, percent=None, threshold=None):
""" PIL_usm.usm(im, [radius, percent, threshold])"""
warnings.warn(
'PIL.ImageOps.unsharp_mask is deprecated. '
'Use PIL.ImageFilter.UnsharpMask instead. '
'This function will be removed in a future version.',
DeprecationWarning
)
if radius is None:
radius = 5.0
if percent is None:
percent = 150
if threshold is None:
threshold = 3
im.load()
return im.im.unsharp_mask(radius, percent, threshold)
def usm(im, radius=None, percent=None, threshold=None):
""" PIL_usm.usm(im, [radius, percent, threshold])"""
warnings.warn(
'PIL.ImageOps.usm is deprecated. '
'Use PIL.ImageFilter.UnsharpMask instead. '
'This function will be removed in a future version.',
DeprecationWarning
)
return unsharp_mask(im, radius, percent, threshold)
def box_blur(image, radius):
"""
Blur the image by setting each pixel to the average value of the pixels
in a square box extending radius pixels in each direction.
Supports float radius of arbitrary size. Uses an optimized implementation
which runs in linear time relative to the size of the image
for any radius value.
:param image: The image to blur.
:param radius: Size of the box in one direction. Radius 0 does not blur,
returns an identical image. Radius 1 takes 1 pixel
in each direction, i.e. 9 pixels in total.
:return: An image.
"""
warnings.warn(
'PIL.ImageOps.box_blur is deprecated. '
'Use PIL.ImageFilter.BoxBlur instead. '
'This function will be removed in a future version.',
DeprecationWarning
)
image.load()
return image._new(image.im.box_blur(radius))
| 19,772 | Python | 30.891935 | 80 | 0.581732 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/calibrate_tool.py | import re
import tkinter as tk
import tkinter.messagebox
from tkinter import *
import _thread
import time
import os
import sys
import numpy as np
from pupper.HardwareInterface import HardwareInterface
###################################################################
OverLoadCurrentMax = 1500000
OverLoadHoldCounterMax = 100 # almost 3s
ServoCalibrationFilePath = '/sys/bus/i2c/devices/3-0050/eeprom'
servo1_en = 25
servo2_en = 21
hw_version=""
###################################################################
class LegPositionScale:
def __init__(self,root,location_x,location_y,leg_name):
self.LocationX = location_x
self.LocationY = location_y
delt_x = 40
delt_y = 45
self.Value1 = DoubleVar()
self.Value2 = DoubleVar()
self.Value3 = DoubleVar()
self.title = Label(root,text = leg_name,font = ('bold',16))
self.label1 = Label(root,text = 'Hip')
self.slider1 = Scale(root,from_=-100,to=100,variable = self.Value1,length = 120,orient = HORIZONTAL)
self.label2 = Label(root,text = 'Thigh')
self.slider2 = Scale(root,from_=-55,to=145,variable = self.Value2,length = 120,orient = HORIZONTAL)
self.label3 = Label(root,text = 'Calf')
self.slider3 = Scale(root,from_=-145,to=55,variable = self.Value3,length = 120,orient = HORIZONTAL)
self.label1.place(x=location_x, y=location_y + 20)
self.label2.place(x=location_x, y=location_y + delt_y*1+ 20)
self.label3.place(x=location_x, y=location_y + delt_y*2+ 20)
self.slider1.place(x=location_x + delt_x, y=location_y )
self.slider2.place(x=location_x + delt_x, y=location_y + delt_y*1)
self.slider3.place(x=location_x + delt_x, y=location_y + delt_y*2)
self.title.place(x=location_x + 70, y=location_y + delt_y*3)
def setValue(self,value):
self.slider1.set(value[0])
self.slider2.set(value[1])
self.slider3.set(value[2])
return True
def getValue(self):
value = []
value.append(self.Value1.get())
value.append(self.Value2.get())
value.append(self.Value3.get())
return value
class CalibrationTool:
def __init__(self,title, width, height):
self.Run = True
self.FileAllLines = []
#leg slider value
self.Leg1SlidersValue = [0,0,0]
self.Leg2SlidersValue = [0,0,0]
self.Leg3SlidersValue = [0,0,0]
self.Leg4SlidersValue = [0,0,0]
# calibration data
self.Matrix_EEPROM = np.array([[0, 0, 0, 0], [45, 45, 45, 45], [-45, -45, -45, -45]])
self.ServoStandardLAngle = [[0,0,0,0],[45,45,45,45],[-45,-45,-45,-45]]
self.ServoNeutralLAngle = [[0,0,0,0],[45,45,45,45],[-45,-45,-45,-45]]
self.NocalibrationServoAngle = [[0,0,0,0],[45,45,45,45],[-45,-45,-45,-45]]
self.CalibrationServoAngle = [[0,0,0,0],[45,45,45,45],[-45,-45,-45,-45]]
#build main window
self.MainWindow = tk.Tk()
screenwidth = self.MainWindow.winfo_screenwidth()
screenheight = self.MainWindow.winfo_screenheight()
size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
self.MainWindow.geometry(size)
self.MainWindow.title('MiniPupper') #Mini Pupper Calibration Tool
self.MainWindow.update()
#init title
self.Title = Label(self.MainWindow,text = title,font = ('bold',30))
self.Title.place(x=140,y=15)
#init robot image
self.photo = tk.PhotoImage(file= '/home/ubuntu/Robotics/QuadrupedRobot/Doc/imgs/MiniPupper.Calibration.png')
self.MainImg = Label(self.MainWindow,image = self.photo)
self.MainImg.place(x=230,y=60)
#init read update button
self.ResetButton = Button(self.MainWindow,text = ' Reset ',font = ('bold',20),command=self.ResetButtonEvent)
self.UpdateButton = Button(self.MainWindow,text = 'Update',font = ('bold',20),command=self.updateButtonEvent)
self.RestoreButton = Button(self.MainWindow,text = 'Restore',font = ('bold',7),command=self.RestoreButtonEvent)
self.ResetButton.place(x=600,y=100)
self.UpdateButton.place(x=600,y=200)
self.RestoreButton.place(x=160,y=80)
#build 4 legs sliders
self.Leg1Calibration = LegPositionScale(self.MainWindow,20,300, 'Leg 1')
self.Leg2Calibration = LegPositionScale(self.MainWindow,220,300,'Leg 2')
self.Leg3Calibration = LegPositionScale(self.MainWindow,420,300,'Leg 3')
self.Leg4Calibration = LegPositionScale(self.MainWindow,620,300,'Leg 4')
self.Leg1Calibration.setValue([self.ServoNeutralLAngle[0][0],self.ServoNeutralLAngle[1][0],self.ServoNeutralLAngle[2][0]])
self.Leg2Calibration.setValue([self.ServoNeutralLAngle[0][1],self.ServoNeutralLAngle[1][1],self.ServoNeutralLAngle[2][1]])
self.Leg3Calibration.setValue([self.ServoNeutralLAngle[0][2],self.ServoNeutralLAngle[1][2],self.ServoNeutralLAngle[2][2]])
self.Leg4Calibration.setValue([self.ServoNeutralLAngle[0][3],self.ServoNeutralLAngle[1][3],self.ServoNeutralLAngle[2][3]])
def setLegSlidersValue(self,value):
self.Leg1Calibration.setValue(value[0])
self.Leg2Calibration.setValue(value[1])
self.Leg3Calibration.setValue(value[2])
self.Leg4Calibration.setValue(value[3])
return value
def readCalibrationFile(self):
#read all lines text from EEPROM
try:
with open(ServoCalibrationFilePath, "rb") as nv_f:
arr1 = np.array(eval(nv_f.readline()))
arr2 = np.array(eval(nv_f.readline()))
matrix = np.append(arr1, arr2)
arr3 = np.array(eval(nv_f.readline()))
matrix = np.append(matrix, arr3)
matrix.resize(3,4)
self.Matrix_EEPROM = matrix
print("Get nv calibration params: \n" , self.Matrix_EEPROM)
except:
matrix = np.array([[0, 0, 0, 0], [45, 45, 45, 45], [-45, -45, -45, -45]])
self.Matrix_EEPROM = matrix
#update
for i in range(3):
for j in range(4):
self.NocalibrationServoAngle[i][j] = self.Matrix_EEPROM[i,j]
self.CalibrationServoAngle[i][j] = self.Matrix_EEPROM[i,j]
return True
def updateCalibrationMatrix(self,angle):
for i in range(3):
for j in range(4):
self.Matrix_EEPROM[i,j] = angle[i][j]
return True
def writeCalibrationFile(self):
#write matrix to EEPROM
buf_matrix = np.zeros((3, 4))
for i in range(3):
for j in range(4):
buf_matrix[i,j]= self.Matrix_EEPROM[i,j]
# Format array object string for np.array
p1 = re.compile("([0-9]\.) ( *)") # pattern to replace the space that follows each number with a comma
partially_formatted_matrix = p1.sub(r"\1,\2", str(buf_matrix))
p2 = re.compile("(\]\n)") # pattern to add a comma at the end of the first two lines
formatted_matrix_with_required_commas = p2.sub("],\n", partially_formatted_matrix)
with open(ServoCalibrationFilePath, "w") as nv_f:
_tmp = str(buf_matrix)
_tmp = _tmp.replace('.' , ',')
_tmp = _tmp.replace('[' , '')
_tmp = _tmp.replace(']' , '')
print(_tmp, file = nv_f)
nv_f.close()
return True
def getLegSlidersValue(self):
value = [[0,0,0,0],[0,0,0,0],[0,0,0,0]]
self.Leg1SlidersValue = self.Leg1Calibration.getValue()
self.Leg2SlidersValue = self.Leg2Calibration.getValue()
self.Leg3SlidersValue = self.Leg3Calibration.getValue()
self.Leg4SlidersValue = self.Leg4Calibration.getValue()
value[0] = [self.Leg1SlidersValue[0],self.Leg2SlidersValue[0],self.Leg3SlidersValue[0],self.Leg4SlidersValue[0]]
value[1] = [self.Leg1SlidersValue[1],self.Leg2SlidersValue[1],self.Leg3SlidersValue[1],self.Leg4SlidersValue[1]]
value[2] = [self.Leg1SlidersValue[2],self.Leg2SlidersValue[2],self.Leg3SlidersValue[2],self.Leg4SlidersValue[2]]
self.ServoNeutralLAngle = value
return value
def ResetButtonEvent(self):
value = [[0,0,0],[0,0,0],[0,0,0],[0,0,0]]
for i in range(3):
for j in range(4):
value[j][i] = self.ServoStandardLAngle[i][j]
self.setLegSlidersValue(value)
return True
def updateButtonEvent(self):
# update angle matrix
value = self.getLegSlidersValue()
angle = [[0,0,0,0],[0,0,0,0],[0,0,0,0]]
for i in range(3):
for j in range(4):
angle[i][j] = self.ServoStandardLAngle[i][j] - value[i][j] +MainWindow.NocalibrationServoAngle[i][j]
# limit angle
for i in range(3):
for j in range(4):
if angle[i][j] > 90:
angle[i][j] = 90
elif angle[i][j] < -90:
angle[i][j] = -90
# popup message box
result = tk.messagebox.askquestion('Info:','****** Angle Matrix ******\n'
+str(angle[0])+'\n'
+str(angle[1])+'\n'
+str(angle[2])+'\n'
+'****************************\n'
+' Update Matrix?')
# update matrix
if result == 'yes':
self.updateCalibrationMatrix(angle)
self.writeCalibrationFile()
print('******** Angle Matrix ********')
print(angle[0])
print(angle[1])
print(angle[2])
print('******************************')
return True
def RestoreButtonEvent(self):
# update angle matrix
value = self.getLegSlidersValue()
angle = [[0,0,0,0],[45,45,45,45],[-45,-45,-45,-45]]
# popup message box
result = tk.messagebox.askquestion('Warning','Are you sure you want to Restore Factory Setting!?')
# update matrix
if result == 'yes':
self.updateCalibrationMatrix(angle)
self.writeCalibrationFile()
print('******** Angle Matrix ********')
print(angle[0])
print(angle[1])
print(angle[2])
print('******************************')
sys.exit()
for i in range(3):
for j in range(4):
self.NocalibrationServoAngle[i][j] = angle[i][j]
#self.CalibrationServoAngle[i][j] = angle[i][j]
value = [[0,0,0],[0,0,0],[0,0,0],[0,0,0]]
for i in range(3):
for j in range(4):
value[j][i] = self.ServoStandardLAngle[i][j]
self.setLegSlidersValue(value)
return True
def runMainWindow(self):
self.MainWindow.mainloop()
return True
def stopMainWindow(self):
self.Run = False
return True
OverLoadHoldCounter = 0
def OverLoadDetection():
overload = False
global OverLoadHoldCounter
r = os.popen("cat /sys/class/power_supply/max1720x_battery/current_now")
feedback = str(r.readlines())
current_now = int(feedback[3:len(feedback)-4])
if (current_now > OverLoadCurrentMax):
OverLoadHoldCounter = OverLoadHoldCounter + 1
if (OverLoadHoldCounter > OverLoadHoldCounterMax):
OverLoadHoldCounter = OverLoadHoldCounterMax
os.popen("echo 0 > /sys/class/gpio/gpio"+ str(servo1_en) + "/value")
os.popen("echo 0 > /sys/class/gpio/gpio"+ str(servo2_en) + "/value")
overload = True
else:
overload = False
else:
OverLoadHoldCounter = OverLoadHoldCounter - 10
if (OverLoadHoldCounter < 0):
OverLoadHoldCounter = 0
os.popen("echo 1 > /sys/class/gpio/gpio" + str(servo1_en) + "/value")
os.popen("echo 1 > /sys/class/gpio/gpio" + str(servo2_en) + "/value")
overload = False
return overload
def updateServoValue(MainWindow,servo):
while MainWindow.Run:
#update leg slider value
value = MainWindow.getLegSlidersValue()
# overload detection
overload = OverLoadDetection()
if overload == True:
tk.messagebox.showwarning('Warning','Servos overload, please check !!!')
else:
#control servo
joint_angles = np.zeros((3, 4))
joint_angles2 = np.zeros((3, 4))
for i in range(3):
for j in range(4):
joint_angles[i,j] = (value[i][j] - (MainWindow.NocalibrationServoAngle[i][j] - MainWindow.CalibrationServoAngle[i][j]))*0.01745
servo.set_actuator_postions(joint_angles)
time.sleep(0.01)
##############################################
with open("/home/ubuntu/.hw_version", "r") as hw_f:
hw_version = hw_f.readline()
if hw_version == 'P1\n':
ServoCalibrationFilePath = "/home/ubuntu/.nv_fle"
servo1_en = 19
servo2_en = 26
else:
servo1_en = 25
servo2_en = 21
os.system("sudo systemctl stop robot")
os.system("echo 1 > /sys/class/gpio/gpio" + str(servo1_en) + "/value")
os.system("echo 1 > /sys/class/gpio/gpio" + str(servo2_en) + "/value")
MainWindow = CalibrationTool('MiniPupper Calibration Tool',800,500)
MainWindow.readCalibrationFile()
hardware_interface = HardwareInterface()
try:
_thread.start_new_thread( updateServoValue, ( MainWindow, hardware_interface,) )
except:
print ('Thread Error')
MainWindow.runMainWindow()
MainWindow.stopMainWindow()
os.system("sudo systemctl start robot")
os.system("echo 1 > /sys/class/gpio/gpio"+ str(servo1_en) + "/value")
os.system("echo 1 > /sys/class/gpio/gpio"+ str(servo2_en) + "/value")
| 14,538 | Python | 34.987624 | 147 | 0.554684 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/run_robot.py | import os
import sys
import threading
import time
import numpy as np
from PIL import Image
from multiprocessing import Process
import multiprocessing
sys.path.append("/home/ubuntu/Robotics/QuadrupedRobot")
sys.path.extend([os.path.join(root, name) for root, dirs, _ in os.walk("/home/ubuntu/Robotics/QuadrupedRobot") for name in dirs])
from Mangdang.LCD.ST7789 import ST7789
from Mangdang.LCD.gif import AnimatedGif
from src.Controller import Controller
from src.JoystickInterface import JoystickInterface
from src.State import State
from pupper.MovementGroup import MovementLib
from src.MovementScheme import MovementScheme
from pupper.HardwareInterface import HardwareInterface
from pupper.Config import Configuration
from pupper.Kinematics import four_legs_inverse_kinematics
quat_orientation = np.array([1, 0, 0, 0])
cartoons_folder = "/home/ubuntu/Robotics/QuadrupedRobot/Mangdang/LCD/cartoons/"
current_show = ""
with open("/home/ubuntu/.hw_version", "r") as hw_f:
hw_version = hw_f.readline()
if hw_version == 'P1\n':
disp = ST7789(14, 15, 47)
else :
disp = ST7789(27, 24, 26)
def pic_show(disp, pic_name, _lock):
""" Show the specify picture
Parameter:
disp : display instance
pic_name : picture name to show
Return : None
"""
if pic_name == "":
return
global current_show
if pic_name == current_show:
return
image=Image.open(cartoons_folder + pic_name)
image.resize((320,240))
_lock.acquire()
disp.display(image)
_lock.release()
current_show = pic_name
def animated_thr_fun(_disp, duration, is_connect, current_leg, _lock):
"""
The thread funcation to show sleep animated gif
Parameter: None
Returen: None
"""
try:
gif_player = AnimatedGif(_disp, width=320, height=240, folder=cartoons_folder)
last_time = time.time()
last_joint_angles = np.zeros(3)
while True:
if is_connect.value == 1 :
#if ((current_leg[0]==last_joint_angles[0]) and (current_leg[1]==last_joint_angles[1]) and (current_leg[2]==last_joint_angles[2])) == False :
if ((current_leg[0]==last_joint_angles[0]) and (current_leg[1]==last_joint_angles[1])) == False :
last_time = time.time()
last_joint_angles[0] = current_leg[0]
last_joint_angles[1] = current_leg[1]
#last_joint_angles[2] = current_leg[2]
if (time.time() - last_time) > duration :
_lock.acquire()
gif_player.play()
_lock.release()
time.sleep(0.5)
else :
last_time = time.time()
time.sleep(1.5)
except KeyboardInterrupt:
_lock.release()
pass
def cmd_dump(cmd):
"""
debug interface to show all info about PS4 command
Parameter: None
return : None
"""
print("\nGet PS4 command :")
print("horizontal_velocity: ", cmd.horizontal_velocity)
print("yaw_rate ", cmd.yaw_rate)
print("height", cmd.height)
print("pitch ", cmd.pitch)
print("roll ", cmd.roll)
print("activation ", cmd.activation)
print("hop_event ", cmd.hop_event)
print("trot_event ", cmd.trot_event)
print("activate_event ", cmd.activate_event)
def main():
"""Main program
"""
# Create config
config = Configuration()
hardware_interface = HardwareInterface()
# show logo
global disp
disp.begin()
disp.clear()
image=Image.open(cartoons_folder + "logo.png")
image.resize((320,240))
disp.display(image)
shutdown_counter = 0 # counter for shuudown cmd
# Start animated process
duration = 10
is_connect = multiprocessing.Value('l', 0)
current_leg = multiprocessing.Array('d', [0, 0, 0])
lock = multiprocessing.Lock()
animated_process = Process(target=animated_thr_fun, args=(disp, duration, is_connect, current_leg, lock))
#animated_process.start()
#Create movement group scheme
movement_ctl = MovementScheme(MovementLib)
# Create controller and user input handles
controller = Controller(
config,
four_legs_inverse_kinematics,
)
state = State()
print("Creating joystick listener...")
joystick_interface = JoystickInterface(config)
print("Done.")
last_loop = time.time()
print("Summary of gait parameters:")
print("overlap time: ", config.overlap_time)
print("swing time: ", config.swing_time)
print("z clearance: ", config.z_clearance)
print("x shift: ", config.x_shift)
# Wait until the activate button has been pressed
while True:
print("Waiting for L1 to activate robot.")
while True:
command = joystick_interface.get_command(state)
joystick_interface.set_color(config.ps4_deactivated_color)
if command.activate_event == 1:
break
time.sleep(0.1)
print("Robot activated.")
is_connect.value = 1
joystick_interface.set_color(config.ps4_color)
pic_show(disp, "walk.png", lock)
while True:
now = time.time()
if now - last_loop < config.dt:
continue
last_loop = time.time()
# Parse the udp joystick commands and then update the robot controller's parameters
command = joystick_interface.get_command(state)
#cmd_dump(command)
_pic = "walk.png" if command.yaw_rate ==0 else "turnaround.png"
if command.trot_event == True:
_pic = "walk_r1.png"
pic_show(disp, _pic, lock)
if command.activate_event == 1:
is_connect.value = 0
pic_show(disp, "notconnect.png", lock)
print("Deactivating Robot")
break
state.quat_orientation = quat_orientation
# movement scheme
movement_switch = command.dance_switch_event
gait_state = command.trot_event
dance_state = command.dance_activate_event
shutdown_signal = command.shutdown_signal
#shutdown counter
if shutdown_signal == True:
shutdown_counter = shutdown_counter + 1
# press shut dow button more 3s(0.015*200), shut down system
if shutdown_counter >= 200:
print('shutdown system now')
os.system('systemctl stop robot')
os.system('shutdown -h now')
# gait and movement control
if gait_state == True or dance_state == True: # if triger tort event, reset the movement number to 0
movement_ctl.resetMovementNumber()
movement_ctl.runMovementScheme(movement_switch)
food_location = movement_ctl.getMovemenLegsLocation()
attitude_location = movement_ctl.getMovemenAttitude()
robot_speed = movement_ctl.getMovemenSpeed()
controller.run(state,command,food_location,attitude_location,robot_speed)
# Update the pwm widths going to the servos
hardware_interface.set_actuator_postions(state.joint_angles)
current_leg[0]= state.joint_angles[0][0]
current_leg[1]= state.joint_angles[1][0]
#current_leg[2]= state.joint_angles[2][0]
try:
main()
except KeyboardInterrupt:
pass
| 7,553 | Python | 33.81106 | 158 | 0.60572 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/src/Gaits.py | class GaitController:
def __init__(self, config):
self.config = config
def phase_index(self, ticks):
"""Calculates which part of the gait cycle the robot should be in given the time in ticks.
Parameters
----------
ticks : int
Number of timesteps since the program started
gaitparams : GaitParams
GaitParams object
Returns
-------
Int
The index of the gait phase that the robot should be in.
"""
phase_time = ticks % self.config.phase_length
phase_sum = 0
for i in range(self.config.num_phases):
phase_sum += self.config.phase_ticks[i]
if phase_time < phase_sum:
return i
assert False
def subphase_ticks(self, ticks):
"""Calculates the number of ticks (timesteps) since the start of the current phase.
Parameters
----------
ticks : Int
Number of timesteps since the program started
gaitparams : GaitParams
GaitParams object
Returns
-------
Int
Number of ticks since the start of the current phase.
"""
phase_time = ticks % self.config.phase_length
phase_sum = 0
subphase_ticks = 0
for i in range(self.config.num_phases):
phase_sum += self.config.phase_ticks[i]
if phase_time < phase_sum:
subphase_ticks = phase_time - phase_sum + self.config.phase_ticks[i]
return subphase_ticks
assert False
def contacts(self, ticks):
"""Calculates which feet should be in contact at the given number of ticks
Parameters
----------
ticks : Int
Number of timesteps since the program started.
gaitparams : GaitParams
GaitParams object
Returns
-------
numpy array (4,)
Numpy vector with 0 indicating flight and 1 indicating stance.
"""
return self.config.contact_phases[:, self.phase_index(ticks)]
| 2,154 | Python | 28.930555 | 98 | 0.545032 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/src/Command.py | import numpy as np
class Command:
"""Stores movement command
"""
def __init__(self):
self.horizontal_velocity = np.array([0, 0])
self.yaw_rate = 0.0
self.height = -0.07
self.pitch = 0.0
self.roll = 0.0
self.activation = 0
self.hop_event = False
self.trot_event = False
self.activate_event = False
self.dance_activate_event = False
self.dance_switch_event = False
self.gait_switch_event = False
self.shutdown_signal = False
| 554 | Python | 20.346153 | 51 | 0.555957 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/src/SwingLegController.py | import numpy as np
from transforms3d.euler import euler2mat
class SwingController:
def __init__(self, config):
self.config = config
def raibert_touchdown_location(
self, leg_index, command
):
delta_p_2d = (
self.config.alpha
* self.config.stance_ticks
* self.config.dt
* command.horizontal_velocity
)
delta_p = np.array([delta_p_2d[0], delta_p_2d[1], 0])
theta = (
self.config.beta
* self.config.stance_ticks
* self.config.dt
* command.yaw_rate
)
R = euler2mat(0, 0, theta)
return R @ self.config.default_stance[:, leg_index] + delta_p
def swing_height(self, swing_phase, triangular=True):
if triangular:
if swing_phase < 0.5:
swing_height_ = swing_phase / 0.5 * self.config.z_clearance
else:
swing_height_ = self.config.z_clearance * (1 - (swing_phase - 0.5) / 0.5)
return swing_height_
def next_foot_location(
self,
swing_prop,
leg_index,
state,
command,
):
assert swing_prop >= 0 and swing_prop <= 1
foot_location = state.foot_locations[:, leg_index]
swing_height_ = self.swing_height(swing_prop)
touchdown_location = self.raibert_touchdown_location(leg_index, command)
time_left = self.config.dt * self.config.swing_ticks * (1.0 - swing_prop)
v = (touchdown_location - foot_location) / time_left * np.array([1, 1, 0])
delta_foot_location = v * self.config.dt
z_vector = np.array([0, 0, swing_height_ + command.height])
return foot_location * np.array([1, 1, 0]) + z_vector + delta_foot_location
| 1,781 | Python | 32.622641 | 89 | 0.563167 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/src/MovementScheme.py | from ActuatorControl import ActuatorControl
LocationStanding = [[ 0.06,0.06,-0.06,-0.06],[-0.05, 0.05,-0.05,0.05],[ -0.07,-0.07,-0.07,-0.07]]
DeltLocationMax = 0.001
AttitudeMinMax = [[-20,20],[-20,20],[-100,100]]
class SequenceInterpolation:
def __init__(self,name,dimension):
self.Name = name
self.Dimension = dimension
self.InterpolationNumber = 1
self.ExecuteTick = 0
self.SequenceExecuteCounter = 0
self.PhaseNumberMax = 1
self.SequencePoint = [[0,0,0]]
# interpolation point data
self.PointPhaseStart = 0
self.PointPhaseStop = 1
self.TnterpolationDelt = [0,0,0]
self.PointNow = [0,0,0]
self.PointPrevious = [0,0,0]
def setCycleType(self,cycle_type,cycle_index):
if cycle_type == 'Forever':
self.SequenceExecuteCounter = 9999
elif cycle_type == 'Multiple':
self.SequenceExecuteCounter = cycle_index
else:
self.SequenceExecuteCounter = 1
return True
def setInterpolationNumber(self,interpolation_number):
self.InterpolationNumber = interpolation_number
return True
def setSequencePoint(self,sequence):
self.SequencePoint = sequence
self.PhaseNumberMax = len(sequence)
# init now and pre point phase
for xyz in range(self.Dimension):
self.PointNow[xyz] = sequence[0][xyz]
self.PointPrevious[xyz] = sequence[0][xyz]
# init start point phase
self.PointPhaseStart = 0
# init stop point phase
self.PointPhaseStop = self.PointPhaseStart + 1
if self.PointPhaseStop >= len(sequence):
self.PointPhaseStop = self.PointPhaseStart
return True
def updatePointPhase(self):
# update start point phase
self.PointPhaseStart = self.PointPhaseStart + 1
if self.PointPhaseStart >= self.PhaseNumberMax:
if self.SequenceExecuteCounter >0:
self.PointPhaseStart = 0
else:
self.SequenceExecuteCounter = 0
self.PointPhaseStart = self.PointPhaseStart - 1
# update stop point phase
self.PointPhaseStop = self.PointPhaseStart + 1
if self.PointPhaseStop >= self.PhaseNumberMax:
self.SequenceExecuteCounter = self.SequenceExecuteCounter - 1
if self.SequenceExecuteCounter >0:
self.PointPhaseStop = 0
else:
self.SequenceExecuteCounter = 0
self.PointPhaseStop = self.PointPhaseStop - 1
self.PointPhaseStop = 0
return True
def updateInterpolationDelt(self):
#get start and stop point
point_start = self.SequencePoint[self.PointPhaseStart]
point_stop = self.SequencePoint[self.PointPhaseStop]
for xyz in range(self.Dimension):
diff = point_stop[xyz] - point_start[xyz]
self.TnterpolationDelt[xyz] = - diff/self.InterpolationNumber
return True
def getNewPoint(self):
#update movement tick
self.ExecuteTick = self.ExecuteTick + 1
if self.ExecuteTick >= self.InterpolationNumber:
self.ExecuteTick = 0
self.updatePointPhase()
self.updateInterpolationDelt()
self.PointNow[0] = self.PointPrevious[0] + self.TnterpolationDelt[0]
self.PointNow[1] = self.PointPrevious[1] + self.TnterpolationDelt[1]
self.PointNow[2] = self.PointPrevious[2] + self.TnterpolationDelt[2]
self.PointPrevious = self.PointNow
return self.PointNow
class Movements:
def __init__(self,name,speed_enable,attitude_enable,legs_enable,actuator_enable):
self.MovementName = name
self.SpeedEnable = speed_enable
self.AttitudeEnable = attitude_enable
self.LegsEnable = legs_enable
self.ActuatorEnable = actuator_enable
self.ExitToStand = True
self.SpeedMovements = SequenceInterpolation('speed',2)
self.AttitudeMovements = SequenceInterpolation('attitude',3)
self.LegsMovements = []
self.LegsMovements.append(SequenceInterpolation('leg1',3))
self.LegsMovements.append(SequenceInterpolation('leg2',3))
self.LegsMovements.append(SequenceInterpolation('leg3',3))
self.LegsMovements.append(SequenceInterpolation('leg4',3))
self.ActuatorsMovements = SequenceInterpolation('actuators',1)
# init state value
self.SpeedInit = [0,0,0] # x, y speed
self.AttitudeInit = [0,0,0] # roll pitch yaw rate
self.LegsLocationInit = [[0,0,0,0],[0,0,0,0],[0,0,0,0]] # x,y,z for 4 legs
self.ActuatorsAngleInit = [0,0,0] # angle for 3 actuators
# output
self.SpeedOutput = [0,0,0] # x, y speed
self.AttitudeOutput = [0,0,0] # roll pitch yaw rate
self.LegsLocationOutput = [[0,0,0,0],[0,0,0,0],[0,0,0,0]] # x,y,z for 4 legs
self.ActuatorsAngleOutput = [0,0,0] # angle for 3 actuators
def setInterpolationNumber(self,number):
self.ActuatorsMovements.setInterpolationNumber(number)
for leg in range(4):
self.LegsMovements[leg].setInterpolationNumber(number)
self.AttitudeMovements.setInterpolationNumber(number)
self.SpeedMovements.setInterpolationNumber(number)
return True
def setExitstate(self,state):
if state != 'Stand':
self.ExitToStand = False
return True
def setSpeedSequence(self,sequence,cycle_type,cycle_index):
self.SpeedMovements.setSequencePoint(sequence)
self.SpeedMovements.setCycleType(cycle_type,cycle_index)
self.SpeedInit = sequence[0]
def setAttitudeSequence(self,sequence,cycle_type,cycle_index):
self.AttitudeMovements.setSequencePoint(sequence)
self.AttitudeMovements.setCycleType(cycle_type,cycle_index)
self.AttitudeInit = sequence[0]
def setLegsSequence(self,sequence,cycle_type,cycle_index):
for leg in range(4):
self.LegsMovements[leg].setSequencePoint(sequence[leg])
self.LegsMovements[leg].setCycleType(cycle_type,cycle_index)
# init location
self.LegsLocationInit[0][leg] = sequence[leg][0][0]
self.LegsLocationInit[1][leg] = sequence[leg][0][1]
self.LegsLocationInit[2][leg] = sequence[leg][0][2]
def setActuatorsSequence(self,sequence,cycle_type,cycle_index):
self.ActuatorsMovements.setSequencePoint(sequence)
self.ActuatorsMovements.setCycleType(cycle_type,cycle_index)
self.ActuatorsAngleInit = sequence[0]
def runMovementSequence(self):
if self.SpeedEnable == 'SpeedEnable':
self.SpeedOutput = self.SpeedMovements.getNewPoint()
if self.AttitudeEnable == 'AttitudeEnable':
self.AttitudeOutput = self.AttitudeMovements.getNewPoint()
if self.LegsEnable == 'LegsEnable':
for leg in range(4):
leg_loaction = self.LegsMovements[leg].getNewPoint()
for xyz in range(3):
self.LegsLocationOutput[xyz][leg] = leg_loaction[xyz]
if self.ActuatorEnable == 'ActuatorEnable':
self.ActuatorsAngleOutput = self.ActuatorsMovements.getNewPoint()
def getSpeedOutput(self, state = 'Normal'):
if state == 'Init':
return self.SpeedInit
else:
return self.SpeedOutput
def getAttitudeOutput(self, state = 'Normal'):
if state == 'Init':
return self.AttitudeInit
else:
return self.AttitudeOutput
def getLegsLocationOutput(self, state = 'Normal'):
if state == 'Init':
return self.LegsLocationInit
else:
return self.LegsLocationOutput
def getActuatorsAngleOutput(self, state = 'Normal'):
if state == 'Init':
return self.ActuatorsAngleInit
else:
return self.ActuatorsAngleOutput
def getMovementName(self):
return self.MovementName
class MovementScheme:
def __init__(self,movements_lib):
self.movements_lib = movements_lib
self.movements_now = movements_lib[0]
self.movements_pre = movements_lib[0]
self.movement_now_name = movements_lib[0].getMovementName()
self.movement_now_number = 0
self.ststus = 'Movement' # 'Entry' 'Movement' 'Exit'
self.entry_down = False
self.exit_down = False
self.tick = 0
self.legs_location_pre = LocationStanding
self.legs_location_now = LocationStanding
self.attitude_pre = [0,0,0]
self.attitude_now = [0,0,0]
self.speed_pre = [0,0,0]
self.speed_now = [0,0,0]
self.actuators_pre = [0,0,0]
self.actuators_now = [0,0,0]
self.actuator = []
self.actuator.append(ActuatorControl(1))
self.actuator.append(ActuatorControl(2))
self.actuator.append(ActuatorControl(3))
def updateMovementType(self):
self.movements_pre = self.movements_lib[self.movement_now_number]
self.movement_now_number = self.movement_now_number + 1
if self.movement_now_number>= len(self.movements_lib):
self.movement_now_number = 0
self.entry_down = False
self.exit_down = False
self.movements_now = self.movements_lib[self.movement_now_number]
return self.movements_now.getMovementName()
def resetMovementNumber(self):
self.movements_pre = self.movements_lib[self.movement_now_number]
self.movement_now_number = 0
self.entry_down = False
self.exit_down = False
self.movements_now = self.movements_lib[0]
return True
def updateMovement(self,movement_type):
# movement state transition
if movement_type != self.movement_now_name:
self.ststus = 'Exit'
elif(self.entry_down):
self.ststus = 'Movement'
elif(self.exit_down):
self.ststus = 'Entry'
self.movement_now_name = movement_type
# update system tick
self.tick = self.tick+ 1
# movement execute
if self.ststus == 'Entry':
location_ready = self.movements_now.getLegsLocationOutput('Init')
self.legs_location_now,self.entry_down = self.updateMovementGradient(self.legs_location_pre,location_ready)
self.legs_location_pre = self.legs_location_now
if self.ststus == 'Exit':
if self.movements_pre.ExitToStand == False:
self.legs_location_now,self.exit_down = self.updateMovementGradient(self.location_pre,LocationStanding)
self.legs_location_pre = self.legs_location_now
else:
self.legs_location_now = self.legs_location_pre
self.exit_down = True
elif self.ststus == 'Movement':
self.updateMovemenScheme(self.tick)
self.legs_location_pre = self.legs_location_now
self.attitude_pre = self.attitude_now
return self.legs_location_now
def updateMovementGradient(self,location_now,location_target):
loaction_gradient = location_now
gradient_done = False
gradient_done_counter = 0
#legs gradient
for xyz_index in range(3):
for leg_index in range(4):
diff = location_now[xyz_index][leg_index] - location_target[xyz_index][leg_index]
if diff > DeltLocationMax:
loaction_gradient[xyz_index][leg_index] = location_now[xyz_index][leg_index] - DeltLocationMax
elif diff < -DeltLocationMax:
loaction_gradient[xyz_index][leg_index] = location_now[xyz_index][leg_index] + DeltLocationMax
else :
loaction_gradient[xyz_index][leg_index] = location_target[xyz_index][leg_index]
gradient_done_counter = gradient_done_counter + 1
# movement gradient is down
if gradient_done_counter == 12:
gradient_done = True
return loaction_gradient, gradient_done
def updateMovemenScheme(self,tick):
# run movement
self.movements_now.runMovementSequence()
# legs movement
self.legs_location_now = self.movements_now.getLegsLocationOutput('normal')
# speed movement
self.speed_now = self.movements_now.getSpeedOutput('normal')
# attitude movement
self.attitude_now = self.movements_now.getAttitudeOutput('normal')
# attitude movement
self.actuators_now = self.movements_now.getActuatorsAngleOutput('normal')
# attitude process
'''
for rpy in range(3):
#limite attitude angle
if attitude_now[rpy] < AttitudeMinMax[rpy][0]:
attitude_now[rpy] = AttitudeMinMax[rpy][0]
elif attitude_now[rpy] > AttitudeMinMax[rpy][1]:
attitude_now[rpy] = AttitudeMinMax[rpy][1]
'''
# speed process
return True
def runMovementScheme(self,transition):
# update movement
movement_name = ''
if transition == True:
movement_name = self.updateMovementType()
self.updateMovement(movement_name)
return True
def getMovemenSpeed(self):
speed_now = [0,0,0]
for xyz in range(3):
speed_now[xyz] = -self.speed_now[xyz]
return speed_now
def getMovemenLegsLocation(self):
return self.legs_location_now
def getMovemenAttitude(self):
attitude_now_rad = [0,0,0]
for rpy in range(3):
#angle to radin
attitude_now_rad[rpy] = -self.attitude_now[rpy] / 57.3
return attitude_now_rad
def getMovemenActuators(self):
return self.actuators_now
| 14,291 | Python | 31.930876 | 130 | 0.607865 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/src/State.py | import numpy as np
from enum import Enum
class State:
def __init__(self):
self.horizontal_velocity = np.array([0.0, 0.0])
self.yaw_rate = 0.0
self.height = -0.07
self.pitch = 0.0
self.roll = 0.0
self.activation = 0
self.behavior_state = BehaviorState.REST
self.ticks = 0
self.foot_locations = np.zeros((3, 4))
self.joint_angles = np.zeros((3, 4))
self.behavior_state = BehaviorState.REST
class BehaviorState(Enum):
DEACTIVATED = -1
REST = 0
TROT = 1
HOP = 2
FINISHHOP = 3 | 589 | Python | 20.851851 | 55 | 0.568761 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/src/StanceController.py | import numpy as np
from transforms3d.euler import euler2mat
class StanceController:
def __init__(self, config):
self.config = config
def position_delta(self, leg_index, state, command):
"""Calculate the difference between the next desired body location and the current body location
Parameters
----------
z_measured : float
Z coordinate of the feet relative to the body.
stance_params : StanceParams
Stance parameters object.
movement_reference : MovementReference
Movement reference object.
gait_params : GaitParams
Gait parameters object.
Returns
-------
(Numpy array (3), Numpy array (3, 3))
(Position increment, rotation matrix increment)
"""
z = state.foot_locations[2, leg_index]
v_xy = np.array(
[
-command.horizontal_velocity[0],
-command.horizontal_velocity[1],
1.0
/ self.config.z_time_constant
* (state.height - z),
]
)
delta_p = v_xy * self.config.dt
delta_R = euler2mat(0, 0, -command.yaw_rate * self.config.dt)
return (delta_p, delta_R)
# TODO: put current foot location into state
def next_foot_location(self, leg_index, state, command):
foot_location = state.foot_locations[:, leg_index]
(delta_p, delta_R) = self.position_delta(leg_index, state, command)
incremented_location = delta_R @ foot_location + delta_p
return incremented_location
| 1,628 | Python | 32.244897 | 104 | 0.57801 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/src/JoystickInterface.py | import UDPComms
import numpy as np
import time
from src.State import BehaviorState, State
from src.Command import Command
from src.Utilities import deadband, clipped_first_order_filter
class JoystickInterface:
def __init__(
self, config, udp_port=8830, udp_publisher_port = 8840,
):
self.config = config
self.previous_gait_toggle = 0
self.previous_state = BehaviorState.REST
self.previous_hop_toggle = 0
self.previous_activate_toggle = 0
self.previous_dance_activate_toggle = 0
self.previous_dance_switch_toggle = 0
self.previous_gait_switch_toggle = 0
self.message_rate = 50
self.udp_handle = UDPComms.Subscriber(udp_port, timeout=0.3)
self.udp_publisher = UDPComms.Publisher(udp_publisher_port,65532)
def get_command(self, state, do_print=False):
try:
msg = self.udp_handle.get()
command = Command()
####### Handle discrete commands ########
# Check if requesting a state transition to trotting, or from trotting to resting
gait_toggle = msg["R1"]
command.trot_event = (gait_toggle == 1 and self.previous_gait_toggle == 0)
# Check if requesting a state transition to hopping, from trotting or resting
hop_toggle = msg["x"]
command.hop_event = (hop_toggle == 1 and self.previous_hop_toggle == 0)
dance_activate_toggle = msg["circle"]
command.dance_activate_event = (dance_activate_toggle == 1 and self.previous_dance_activate_toggle == 0)
shutdown_toggle = msg["triangle"]
command.shutdown_signal = shutdown_toggle
activate_toggle = msg["L1"]
command.activate_event = (activate_toggle == 1 and self.previous_activate_toggle == 0)
dance_toggle = msg["L2"]
command.dance_switch_event = (dance_toggle == 1 and self.previous_dance_switch_toggle != 1)
gait_switch_toggle = msg["R2"]
command.gait_switch_event = (gait_switch_toggle == 1 and self.previous_gait_switch_toggle != 1)
# Update previous values for toggles and state
self.previous_gait_toggle = gait_toggle
self.previous_hop_toggle = hop_toggle
self.previous_activate_toggle = activate_toggle
self.previous_dance_activate_toggle = dance_activate_toggle
self.previous_dance_switch_toggle = dance_toggle
self.previous_gait_switch_toggle = gait_switch_toggle
####### Handle continuous commands ########
x_vel = msg["ly"] * self.config.max_x_velocity
y_vel = msg["lx"] * -self.config.max_y_velocity
command.horizontal_velocity = np.array([x_vel, y_vel])
command.yaw_rate = msg["rx"] * -self.config.max_yaw_rate
message_rate = msg["message_rate"]
message_dt = 1.0 / message_rate
pitch = msg["ry"] * self.config.max_pitch
deadbanded_pitch = deadband(
pitch, self.config.pitch_deadband
)
pitch_rate = clipped_first_order_filter(
state.pitch,
deadbanded_pitch,
self.config.max_pitch_rate,
self.config.pitch_time_constant,
)
command.pitch = state.pitch + message_dt * pitch_rate
height_movement = msg["dpady"]
command.height = state.height - message_dt * self.config.z_speed * height_movement
roll_movement = - msg["dpadx"]
command.roll = state.roll + message_dt * self.config.roll_speed * roll_movement
return command
except UDPComms.timeout:
if do_print:
print("UDP Timed out")
return Command()
def set_color(self, color):
joystick_msg = {"ps4_color": color}
self.udp_publisher.send(joystick_msg)
| 3,985 | Python | 37.326923 | 116 | 0.59197 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/src/ActuatorControl.py | import os
import sys
import time
class ActuatorControl:
def __init__(self,pwm_number):
self.pwm_number = pwm_number
def updateDutyCycle(self,angle):
duty_cycle = int((1.11*angle+50)*10000)
return duty_cycle
def updateActuatorAngle(self,angle):
if self.pwm_number == 1:
actuator_name = 'pwm1'
elif self.pwm_number == 2:
actuator_name = 'pwm2'
elif self.pwm_number == 3:
actuator_name = 'pwm3'
duty_cycle = self.updateDutyCycle(angle)
file_node = '/sys/class/pwm/pwmchip0/' + actuator_name+ '/duty_cycle'
f = open(file_node, "w")
f.write(str(duty_cycle))
#test = ActuatorControl(3)
#time.sleep(10)
#for index in range(30):
# test.updateActuatorAngle(index*3)
# time.sleep(0.1)
# test.updateActuatorAngle(0)
| 856 | Python | 22.162162 | 77 | 0.600467 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/src/Utilities.py | import numpy as np
def deadband(value, band_radius):
return max(value - band_radius, 0) + min(value + band_radius, 0)
def clipped_first_order_filter(input, target, max_rate, tau):
rate = (target - input) / tau
return np.clip(rate, -max_rate, max_rate)
| 268 | Python | 23.454543 | 68 | 0.671642 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/src/Controller.py | from src.Gaits import GaitController
#from src.GaitScheme import GaitScheme
from src.StanceController import StanceController
from src.SwingLegController import SwingController
from src.Utilities import clipped_first_order_filter
from src.State import BehaviorState, State
import numpy as np
from transforms3d.euler import euler2mat, quat2euler
from transforms3d.quaternions import qconjugate, quat2axangle
from transforms3d.axangles import axangle2mat
class Controller:
"""Controller and planner object
"""
def __init__(
self,
config,
inverse_kinematics,
):
self.config = config
self.smoothed_yaw = 0.0 # for REST mode only
self.inverse_kinematics = inverse_kinematics
self.dance_active_state = False
self.contact_modes = np.zeros(4)
self.gait_controller = GaitController(self.config)
#self.gait_controller = GaitScheme(1)
#self.gait_controller.setCurrentGait('Trotting')
self.swing_controller = SwingController(self.config)
self.stance_controller = StanceController(self.config)
self.hop_transition_mapping = {BehaviorState.REST: BehaviorState.HOP, BehaviorState.HOP: BehaviorState.FINISHHOP, BehaviorState.FINISHHOP: BehaviorState.REST, BehaviorState.TROT: BehaviorState.HOP}
self.trot_transition_mapping = {BehaviorState.REST: BehaviorState.TROT, BehaviorState.TROT: BehaviorState.REST, BehaviorState.HOP: BehaviorState.TROT, BehaviorState.FINISHHOP: BehaviorState.TROT}
self.activate_transition_mapping = {BehaviorState.DEACTIVATED: BehaviorState.REST, BehaviorState.REST: BehaviorState.DEACTIVATED}
def dance_active(self,command):
if command.dance_activate_event == True:
if self.dance_active_state == False:
self.dance_active_state = True
elif self.dance_active_state == True:
self.dance_active_state = False
return True
def step_gait(self, state, command):
"""Calculate the desired foot locations for the next timestep
Returns
-------
Numpy array (3, 4)
Matrix of new foot locations.
"""
contact_modes = self.gait_controller.contacts(state.ticks)
#if command.gait_switch_event == 1:
# self.gait_controller.switchGait()
#self.gait_controller.updateGaitScheme()
#contact_modes = self.gait_controller.current_leg_state
new_foot_locations = np.zeros((3, 4))
for leg_index in range(4):
contact_mode = contact_modes[leg_index]
foot_location = state.foot_locations[:, leg_index]
if contact_mode == 1:
new_location = self.stance_controller.next_foot_location(leg_index, state, command)
else:
swing_proportion = (
self.gait_controller.subphase_ticks(state.ticks) / self.config.swing_ticks
)
#leg_progress = self.gait_controller.current_leg_progress
#swing_proportion = leg_progress[leg_index]
new_location = self.swing_controller.next_foot_location(
swing_proportion,
leg_index,
state,
command
)
new_foot_locations[:, leg_index] = new_location
return new_foot_locations, contact_modes
def run(self, state, command,location,attitude,robot_speed):
"""Steps the controller forward one timestep
Parameters
----------
controller : Controller
Robot controller object.
"""
########## Update operating state based on command ######
if command.activate_event:
state.behavior_state = self.activate_transition_mapping[state.behavior_state]
elif command.trot_event:
state.behavior_state = self.trot_transition_mapping[state.behavior_state]
elif command.hop_event:
state.behavior_state = self.hop_transition_mapping[state.behavior_state]
# check dance active event
self.dance_active(command)
if state.behavior_state == BehaviorState.TROT:
state.foot_locations, contact_modes = self.step_gait(
state,
command,
)
# Apply the desired body rotation
rotated_foot_locations = (
euler2mat(
command.roll, command.pitch, 0.0
)
@ state.foot_locations
)
# Construct foot rotation matrix to compensate for body tilt
(roll, pitch, yaw) = quat2euler(state.quat_orientation)
correction_factor = 0.8
max_tilt = 0.4
roll_compensation = correction_factor * np.clip(-roll, -max_tilt, max_tilt)
pitch_compensation = correction_factor * np.clip(-pitch, -max_tilt, max_tilt)
rmat = euler2mat(roll_compensation, pitch_compensation, 0)
rotated_foot_locations = rmat.T @ rotated_foot_locations
state.joint_angles = self.inverse_kinematics(
rotated_foot_locations, self.config
)
elif state.behavior_state == BehaviorState.HOP:
state.foot_locations = (
self.config.default_stance
+ np.array([0, 0, -0.03])[:, np.newaxis]
)
state.joint_angles = self.inverse_kinematics(
state.foot_locations, self.config
)
elif state.behavior_state == BehaviorState.FINISHHOP:
state.foot_locations = (
self.config.default_stance
+ np.array([0, 0, -0.105])[:, np.newaxis]
)
state.joint_angles = self.inverse_kinematics(
state.foot_locations, self.config
)
elif state.behavior_state == BehaviorState.REST:
yaw_proportion = command.yaw_rate / self.config.max_yaw_rate
self.smoothed_yaw += (
self.config.dt
* clipped_first_order_filter(
self.smoothed_yaw,
yaw_proportion * -self.config.max_stance_yaw,
self.config.max_stance_yaw_rate,
self.config.yaw_time_constant,
)
)
# Set the foot locations to the default stance plus the standard height
print('act:',self.dance_active_state)
#self.dance_active_state = True
if self.dance_active_state == False:
state.foot_locations = (self.config.default_stance + np.array([0, 0, command.height])[:, np.newaxis])
# Apply the desired body rotation
rotated_foot_locations = (
euler2mat(
command.roll,
command.pitch,
self.smoothed_yaw,
)
@ state.foot_locations
)
else:
location_buf = np.zeros((3, 4))
for index_i in range(3):
for index_j in range(4):
location_buf[index_i,index_j] = location[index_i][index_j]
if (abs(robot_speed[0])<0.01) and (abs(robot_speed[1])<0.01):
state.foot_locations = location_buf
else:
command.horizontal_velocity[0] = robot_speed[0]
command.horizontal_velocity[1] = robot_speed[1]
state.foot_locations, contact_modes = self.step_gait(state,command)
# Apply the desired body rotation
rotated_foot_locations = (
euler2mat(
attitude[0],
attitude[1],
self.smoothed_yaw,
)
@ state.foot_locations
)
state.joint_angles = self.inverse_kinematics(
rotated_foot_locations, self.config
)
# Construct foot rotation matrix to compensate for body tilt
(roll, pitch, yaw) = quat2euler(state.quat_orientation)
correction_factor = 0.8
max_tilt = 0.4
roll_compensation = correction_factor * np.clip(-roll, -max_tilt, max_tilt)
pitch_compensation = correction_factor * np.clip(-pitch, -max_tilt, max_tilt)
rmat = euler2mat(roll_compensation, pitch_compensation, 0)
rotated_foot_locations = rmat.T @ rotated_foot_locations
state.joint_angles = self.inverse_kinematics(
rotated_foot_locations, self.config
)
state.ticks += 1
state.pitch = command.pitch
state.roll = command.roll
state.height = command.height
def set_pose_to_default(self):
state.foot_locations = (
self.config.default_stance
+ np.array([0, 0, self.config.default_z_ref])[:, np.newaxis]
)
state.joint_angles = controller.inverse_kinematics(
state.foot_locations, self.config
)
| 9,316 | Python | 38.478813 | 205 | 0.566445 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/pupper/ServoCalibration.py | # WARNING: This file is machine generated. Edit at your own risk.
import numpy as np
MICROS_PER_RAD = 11.111 * 180.0 / np.pi
| 128 | Python | 17.428569 | 65 | 0.703125 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/pupper/MovementGroup.py |
from src.MovementScheme import Movements
def appendDanceMovement():
'''
#demo 1
dance_scheme = Movements('stand','SpeedDisable','AttitudeDisable','LegsEnable','ActuatorDisable')
dance_scheme.setExitstate('Stand')
dance_all_legs = []
dance_all_legs.append([[ 0.06,-0.05,-0.065]]) # leg1
dance_all_legs.append([[ 0.06, 0.05,-0.065]]) # leg2
dance_all_legs.append([[-0.06,-0.05,-0.065]]) # leg3
dance_all_legs.append([[-0.06, 0.05,-0.065]]) # leg4
dance_scheme.setInterpolationNumber(50)
dance_scheme.setLegsSequence(dance_all_legs,'Forever',5)
MovementLib.append(dance_scheme) # append dance
'''
#demo 2
dance_scheme = Movements('push-up','SpeedEnable','AttitudeDisable','LegsEnable','ActuatorDisable')
dance_scheme.setExitstate('Stand')
dance_all_legs = []
dance_all_legs.append([[ 0.06,-0.05,-0.04],[ 0.06,-0.05,-0.07],[ 0.06,-0.05,-0.04],[ 0.06,-0.05,-0.04],[ 0.06,-0.05,-0.04]]) # leg1
dance_all_legs.append([[ 0.06, 0.05,-0.04],[ 0.06, 0.05,-0.07],[ 0.06, 0.05,-0.04],[ 0.06, 0.05,-0.04],[ 0.06, 0.05,-0.04]]) # leg2
dance_all_legs.append([[-0.06,-0.05,-0.04],[-0.06,-0.05,-0.07],[-0.06,-0.05,-0.04],[-0.06,-0.05,-0.04],[-0.06,-0.05,-0.04]]) # leg3
dance_all_legs.append([[-0.06, 0.05,-0.04],[-0.06, 0.05,-0.07],[-0.06, 0.05,-0.04],[-0.06, 0.05,-0.04],[-0.06, 0.05,-0.04]]) # leg4
dance_speed = [[0,0,0],[0,0,0],[0,0,0],[0.25,0,0,0],[0.25,0,0,0]] # speed_, speed_y, no_use
dance_attitude = [[0,0,0],[10,0,0],[0,0,0]] # roll, pitch, yaw rate
dance_scheme.setInterpolationNumber(70)
dance_scheme.setLegsSequence(dance_all_legs,'Forever',1)
dance_scheme.setSpeedSequence(dance_speed,'Forever',1)
dance_scheme.setAttitudeSequence(dance_attitude,'Forever',1)
MovementLib.append(dance_scheme) # append dance
MovementLib = []
appendDanceMovement()
| 1,955 | Python | 38.918367 | 137 | 0.588235 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/pupper/HardwareInterface.py | import os
import sys
sys.path.append("/home/ubuntu/Robotics/QuadrupedRobot/")
sys.path.extend([os.path.join(root, name) for root, dirs, _ in os.walk("/home/ubuntu/Robotics/QuadrupedRobot") for name in dirs])
from Mangdang import PWMController
from pupper.Config import ServoParams, PWMParams
#from __future__ import division
import numpy as np
class HardwareInterface:
def __init__(self):
self.pwm_params = PWMParams()
self.servo_params = ServoParams()
def set_actuator_postions(self, joint_angles):
send_servo_commands(self.pwm_params, self.servo_params, joint_angles)
def set_actuator_position(self, joint_angle, axis, leg):
send_servo_command(self.pwm_params, self.servo_params, joint_angle, axis, leg)
def pwm_to_duty_cycle(pulsewidth_micros, pwm_params):
"""Converts a pwm signal (measured in microseconds) to a corresponding duty cycle on the gpio pwm pin
Parameters
----------
pulsewidth_micros : float
Width of the pwm signal in microseconds
pwm_params : PWMParams
PWMParams object
Returns
-------
float
PWM duty cycle corresponding to the pulse width
"""
pulsewidth_micros = int(pulsewidth_micros / 1e6 * pwm_params.freq * pwm_params.range)
if np.isnan(pulsewidth_micros):
return 0
return int(np.clip(pulsewidth_micros, 0, 4096))
def angle_to_pwm(angle, servo_params, axis_index, leg_index):
"""Converts a desired servo angle into the corresponding PWM command
Parameters
----------
angle : float
Desired servo angle, relative to the vertical (z) axis
servo_params : ServoParams
ServoParams object
axis_index : int
Specifies which joint of leg to control. 0 is abduction servo, 1 is inner hip servo, 2 is outer hip servo.
leg_index : int
Specifies which leg to control. 0 is front-right, 1 is front-left, 2 is back-right, 3 is back-left.
Returns
-------
float
PWM width in microseconds
"""
angle_deviation = (
angle - servo_params.neutral_angles[axis_index, leg_index]
) * servo_params.servo_multipliers[axis_index, leg_index]
pulse_width_micros = (
servo_params.neutral_position_pwm
+ servo_params.micros_per_rad * angle_deviation
)
return pulse_width_micros
def angle_to_duty_cycle(angle, pwm_params, servo_params, axis_index, leg_index):
duty_cycle_f = angle_to_pwm(angle, servo_params, axis_index, leg_index) * 1e3
if np.isnan(duty_cycle_f):
return 0
return int(duty_cycle_f)
def initialize_pwm(pi, pwm_params):
pi.set_pwm_freq(pwm_params.freq)
def send_servo_commands(pwm_params, servo_params, joint_angles):
for leg_index in range(4):
for axis_index in range(3):
duty_cycle = angle_to_duty_cycle(
joint_angles[axis_index, leg_index],
pwm_params,
servo_params,
axis_index,
leg_index,
)
# write duty_cycle to pwm linux kernel node
file_node = "/sys/class/pwm/pwmchip0/pwm" + str(pwm_params.pins[axis_index, leg_index]) + "/duty_cycle"
f = open(file_node, "w")
f.write(str(duty_cycle))
def send_servo_command(pwm_params, servo_params, joint_angle, axis, leg):
duty_cycle = angle_to_duty_cycle(joint_angle, pwm_params, servo_params, axis, leg)
file_node = "/sys/class/pwm/pwmchip0/pwm" + str(pwm_params.pins[axis, leg]) + "/duty_cycle"
f = open(file_node, "w")
f.write(str(duty_cycle))
def deactivate_servos(pi, pwm_params):
for leg_index in range(4):
for axis_index in range(3):
pi.set_pwm(pwm_params.pins[axis_index, leg_index], 0, 0)
| 3,798 | Python | 33.225225 | 129 | 0.639547 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/pupper/Kinematics.py | import numpy as np
from transforms3d.euler import euler2mat
def leg_explicit_inverse_kinematics(r_body_foot, leg_index, config):
"""Find the joint angles corresponding to the given body-relative foot position for a given leg and configuration
Parameters
----------
r_body_foot : [type]
[description]
leg_index : [type]
[description]
config : [type]
[description]
Returns
-------
numpy array (3)
Array of corresponding joint angles.
"""
(x, y, z) = r_body_foot
# Distance from the leg origin to the foot, projected into the y-z plane
R_body_foot_yz = (y ** 2 + z ** 2) ** 0.5
# Distance from the leg's forward/back point of rotation to the foot
R_hip_foot_yz = (R_body_foot_yz ** 2 - config.ABDUCTION_OFFSET ** 2) ** 0.5
# Interior angle of the right triangle formed in the y-z plane by the leg that is coincident to the ab/adduction axis
# For feet 2 (front left) and 4 (back left), the abduction offset is positive, for the right feet, the abduction offset is negative.
arccos_argument = config.ABDUCTION_OFFSETS[leg_index] / R_body_foot_yz
arccos_argument = np.clip(arccos_argument, -0.99, 0.99)
phi = np.arccos(arccos_argument)
# Angle of the y-z projection of the hip-to-foot vector, relative to the positive y-axis
hip_foot_angle = np.arctan2(z, y)
# Ab/adduction angle, relative to the positive y-axis
abduction_angle = phi + hip_foot_angle
# theta: Angle between the tilted negative z-axis and the hip-to-foot vector
theta = np.arctan2(-x, R_hip_foot_yz)
# Distance between the hip and foot
R_hip_foot = (R_hip_foot_yz ** 2 + x ** 2) ** 0.5
# Angle between the line going from hip to foot and the link L1
arccos_argument = (config.LEG_L1 ** 2 + R_hip_foot ** 2 - config.LEG_L2 ** 2) / (
2 * config.LEG_L1 * R_hip_foot
)
arccos_argument = np.clip(arccos_argument, -0.99, 0.99)
trident = np.arccos(arccos_argument)
# Angle of the first link relative to the tilted negative z axis
hip_angle = theta + trident
# Angle between the leg links L1 and L2
arccos_argument = (config.LEG_L1 ** 2 + config.LEG_L2 ** 2 - R_hip_foot ** 2) / (
2 * config.LEG_L1 * config.LEG_L2
)
arccos_argument = np.clip(arccos_argument, -0.99, 0.99)
beta = np.arccos(arccos_argument)
# Angle of the second link relative to the tilted negative z axis
knee_angle = hip_angle - (np.pi - beta)
return np.array([abduction_angle, hip_angle, knee_angle])
def four_legs_inverse_kinematics(r_body_foot, config):
"""Find the joint angles for all twelve DOF correspoinding to the given matrix of body-relative foot positions.
Parameters
----------
r_body_foot : numpy array (3,4)
Matrix of the body-frame foot positions. Each column corresponds to a separate foot.
config : Config object
Object of robot configuration parameters.
Returns
-------
numpy array (3,4)
Matrix of corresponding joint angles.
"""
alpha = np.zeros((3, 4))
for i in range(4):
body_offset = config.LEG_ORIGINS[:, i]
alpha[:, i] = leg_explicit_inverse_kinematics(
r_body_foot[:, i] - body_offset, i, config
)
return alpha
| 3,324 | Python | 34.752688 | 136 | 0.639892 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/pupper/HardwareConfig.py | """
Per-robot configuration file that is particular to each individual robot, not just the type of robot.
"""
PS4_COLOR = {"red": 0, "blue": 0, "green": 255}
PS4_DEACTIVATED_COLOR = {"red": 0, "blue": 0, "green": 50}
| 218 | Python | 30.28571 | 101 | 0.655963 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/StanfordQuadruped/pupper/Config.py | import numpy as np
from pupper.ServoCalibration import MICROS_PER_RAD
from pupper.HardwareConfig import PS4_COLOR, PS4_DEACTIVATED_COLOR
from enum import Enum
# TODO: put these somewhere else
class PWMParams:
def __init__(self):
self.pins = np.array([[15, 12, 9, 6], [14, 11, 8, 5], [13, 10, 7, 4]])
self.range = 4096 ## ADC 12 bits
self.freq = 250 ## PWM freq
class ServoParams:
def __init__(self):
self.neutral_position_pwm = 1500 # Middle position
self.micros_per_rad = MICROS_PER_RAD # Must be calibrated
with open("/home/ubuntu/.hw_version", "r") as hw_f:
hw_version = hw_f.readline()
if hw_version == 'P1\n':
nv_file = "/home/ubuntu/.nv_fle"
else:
nv_file = "/sys/bus/i2c/devices/3-0050/eeprom"
# The neutral angle of the joint relative to the modeled zero-angle in degrees, for each joint
try:
with open(nv_file, "rb") as nv_f:
arr1 = np.array(eval(nv_f.readline()))
arr2 = np.array(eval(nv_f.readline()))
matrix = np.append(arr1, arr2)
arr3 = np.array(eval(nv_f.readline()))
matrix = np.append(matrix, arr3)
matrix.resize(3,4)
print("Get nv calibration params: \n" , matrix)
except:
print("Error, get nv calibration params failed, use default value. Please calibrate your pupper !")
matrix = np.array(
[[0, 0, 0, 0], [45, 45, 45, 45], [-45, -45, -45, -45]]
)
self.neutral_angle_degrees = matrix
self.servo_multipliers = np.array(
[[1, 1, -1, -1], [-1, 1, -1, 1], [-1, 1, -1, 1]]
)
@property
def neutral_angles(self):
return self.neutral_angle_degrees * np.pi / 180.0 # Convert to radians
class Configuration:
def __init__(self):
################# CONTROLLER BASE COLOR ##############
self.ps4_color = PS4_COLOR
self.ps4_deactivated_color = PS4_DEACTIVATED_COLOR
#################### COMMANDS ####################
self.max_x_velocity = 0.20
self.max_y_velocity = 0.20
self.max_yaw_rate = 2
self.max_pitch = 20.0 * np.pi / 180.0
#################### MOVEMENT PARAMS ####################
self.z_time_constant = 0.02
self.z_speed = 0.01 # maximum speed [m/s]
self.pitch_deadband = 0.02
self.pitch_time_constant = 0.25
self.max_pitch_rate = 0.15
self.roll_speed = 0.16 # maximum roll rate [rad/s] 0.16
self.yaw_time_constant = 0.3
self.max_stance_yaw = 1.2
self.max_stance_yaw_rate = 1.5
#################### STANCE ####################
self.delta_x = 0.059
self.delta_y = 0.050
self.x_shift = 0.00
self.default_z_ref = -0.08
#################### SWING ######################
self.z_coeffs = None
self.z_clearance = 0.03
self.alpha = (
0.5 # Ratio between touchdown distance and total horizontal stance movement
)
self.beta = (
0.5 # Ratio between touchdown distance and total horizontal stance movement
)
#################### GAIT #######################
self.dt = 0.015
self.num_phases = 4
self.contact_phases = np.array(
[[1, 1, 1, 0], [1, 0, 1, 1], [1, 0, 1, 1], [1, 1, 1, 0]]
)
self.overlap_time = (
0.09 # duration of the phase where all four feet are on the ground
)
self.swing_time = (
0.1 # duration of the phase when only two feet are on the ground
)
######################## GEOMETRY ######################
self.LEG_FB = 0.059 # front-back distance from center line to leg axis
self.LEG_LR = 0.0235 # left-right distance from center line to leg plane
self.LEG_L2 = 0.060
self.LEG_L1 = 0.050
self.ABDUCTION_OFFSET = 0.026 # distance from abduction axis to leg
self.FOOT_RADIUS = 0.00
self.HIP_L = 0.0394
self.HIP_W = 0.0744
self.HIP_T = 0.0214
self.HIP_OFFSET = 0.0132
self.L = 0.176
self.W = 0.060
self.T = 0.045
self.LEG_ORIGINS = np.array(
[
[self.LEG_FB, self.LEG_FB, -self.LEG_FB, -self.LEG_FB],
[-self.LEG_LR, self.LEG_LR, -self.LEG_LR, self.LEG_LR],
[0, 0, 0, 0],
]
)
self.ABDUCTION_OFFSETS = np.array(
[
-self.ABDUCTION_OFFSET,
self.ABDUCTION_OFFSET,
-self.ABDUCTION_OFFSET,
self.ABDUCTION_OFFSET,
]
)
################### INERTIAL ####################
self.FRAME_MASS = 0.200 # kg
self.MODULE_MASS = 0.020 # kg
self.LEG_MASS = 0.010 # kg
self.MASS = self.FRAME_MASS + (self.MODULE_MASS + self.LEG_MASS) * 4
# Compensation factor of 3 because the inertia measurement was just
# of the carbon fiber and plastic parts of the frame and did not
# include the hip servos and electronics
self.FRAME_INERTIA = tuple(
map(lambda x: 3.0 * x, (1.844e-4, 1.254e-3, 1.337e-3))
)
self.MODULE_INERTIA = (3.698e-5, 7.127e-6, 4.075e-5)
leg_z = 1e-6
leg_mass = 0.010
leg_x = 1 / 12 * self.LEG_L1 ** 2 * leg_mass
leg_y = leg_x
self.LEG_INERTIA = (leg_x, leg_y, leg_z)
@property
def default_stance(self):
return np.array(
[
[
self.delta_x + self.x_shift,
self.delta_x + self.x_shift,
-self.delta_x + self.x_shift,
-self.delta_x + self.x_shift,
],
[-self.delta_y, self.delta_y, -self.delta_y, self.delta_y],
[0, 0, 0, 0],
]
)
################## SWING ###########################
@property
def z_clearance(self):
return self.__z_clearance
@z_clearance.setter
def z_clearance(self, z):
self.__z_clearance = z
# b_z = np.array([0, 0, 0, 0, self.__z_clearance])
# A_z = np.array(
# [
# [0, 0, 0, 0, 1],
# [1, 1, 1, 1, 1],
# [0, 0, 0, 1, 0],
# [4, 3, 2, 1, 0],
# [0.5 ** 4, 0.5 ** 3, 0.5 ** 2, 0.5 ** 1, 0.5 ** 0],
# ]
# )
# self.z_coeffs = solve(A_z, b_z)
########################### GAIT ####################
@property
def overlap_ticks(self):
return int(self.overlap_time / self.dt)
@property
def swing_ticks(self):
return int(self.swing_time / self.dt)
@property
def stance_ticks(self):
return 2 * self.overlap_ticks + self.swing_ticks
@property
def phase_ticks(self):
return np.array(
[self.overlap_ticks, self.swing_ticks, self.overlap_ticks, self.swing_ticks]
)
@property
def phase_length(self):
return 2 * self.overlap_ticks + 2 * self.swing_ticks
class SimulationConfig:
def __init__(self):
self.XML_IN = "pupper.xml"
self.XML_OUT = "pupper_out.xml"
self.START_HEIGHT = 0.3
self.MU = 1.5 # coeff friction
self.DT = 0.001 # seconds between simulation steps
self.JOINT_SOLREF = "0.001 1" # time constant and damping ratio for joints
self.JOINT_SOLIMP = "0.9 0.95 0.001" # joint constraint parameters
self.GEOM_SOLREF = "0.01 1" # time constant and damping ratio for geom contacts
self.GEOM_SOLIMP = "0.9 0.95 0.001" # geometry contact parameters
# Joint params
G = 220 # Servo gear ratio
m_rotor = 0.016 # Servo rotor mass
r_rotor = 0.005 # Rotor radius
self.ARMATURE = G ** 2 * m_rotor * r_rotor ** 2 # Inertia of rotational joints
# print("Servo armature", self.ARMATURE)
NATURAL_DAMPING = 1.0 # Damping resulting from friction
ELECTRICAL_DAMPING = 0.049 # Damping resulting from back-EMF
self.REV_DAMPING = (
NATURAL_DAMPING + ELECTRICAL_DAMPING
) # Damping torque on the revolute joints
# Servo params
self.SERVO_REV_KP = 300 # Position gain [Nm/rad]
# Force limits
self.MAX_JOINT_TORQUE = 3.0
self.REVOLUTE_RANGE = 1.57
| 8,547 | Python | 33.329317 | 111 | 0.500058 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/PS4Joystick/PS4Joystick.py |
import sys
import time
import subprocess
import math
from threading import Thread
from collections import OrderedDict, deque
from ds4drv.actions import ActionRegistry
from ds4drv.backends import BluetoothBackend, HidrawBackend
from ds4drv.config import load_options
from ds4drv.daemon import Daemon
from ds4drv.eventloop import EventLoop
from ds4drv.exceptions import BackendError
from ds4drv.action import ReportAction
from ds4drv.__main__ import create_controller_thread
class ActionShim(ReportAction):
""" intercepts the joystick report"""
def __init__(self, *args, **kwargs):
super(ActionShim, self).__init__(*args, **kwargs)
self.timer = self.create_timer(0.02, self.intercept)
self.values = None
self.timestamps = deque(range(10), maxlen=10)
def enable(self):
self.timer.start()
def disable(self):
self.timer.stop()
self.values = None
def load_options(self, options):
pass
def deadzones(self,values):
deadzone = 0.14
if math.sqrt( values['left_analog_x'] ** 2 + values['left_analog_y'] ** 2) < deadzone:
values['left_analog_y'] = 0.0
values['left_analog_x'] = 0.0
if math.sqrt( values['right_analog_x'] ** 2 + values['right_analog_y'] ** 2) < deadzone:
values['right_analog_y'] = 0.0
values['right_analog_x'] = 0.0
return values
def intercept(self, report):
new_out = OrderedDict()
for key in report.__slots__:
value = getattr(report, key)
new_out[key] = value
for key in ["left_analog_x", "left_analog_y",
"right_analog_x", "right_analog_y",
"l2_analog", "r2_analog"]:
new_out[key] = 2*( new_out[key]/255 ) - 1
new_out = self.deadzones(new_out)
self.timestamps.append(new_out['timestamp'])
if len(set(self.timestamps)) <= 1:
self.values = None
else:
self.values = new_out
return True
class Joystick:
def __init__(self):
self.thread = None
options = load_options()
if options.hidraw:
raise ValueError("HID mode not supported")
backend = HidrawBackend(Daemon.logger)
else:
subprocess.run(["hciconfig", "hciX", "up"])
backend = BluetoothBackend(Daemon.logger)
backend.setup()
self.thread = create_controller_thread(1, options.controllers[0])
self.thread.controller.setup_device(next(backend.devices))
self.shim = ActionShim(self.thread.controller)
self.thread.controller.actions.append(self.shim)
self.shim.enable()
self._color = (None, None, None)
self._rumble = (None, None)
self._flash = (None, None)
# ensure we get a value before returning
while self.shim.values is None:
pass
def close(self):
if self.thread is None:
return
self.thread.controller.exit("Cleaning up...")
self.thread.controller.loop.stop()
def __del__(self):
self.close()
@staticmethod
def map(val, in_min, in_max, out_min, out_max):
""" helper static method that helps with rescaling """
in_span = in_max - in_min
out_span = out_max - out_min
value_scaled = float(val - in_min) / float(in_span)
value_mapped = (value_scaled * out_span) + out_min
if value_mapped < out_min:
value_mapped = out_min
if value_mapped > out_max:
value_mapped = out_max
return value_mapped
def get_input(self):
""" returns ordered dict with state of all inputs """
if self.thread.controller.error:
raise IOError("Encountered error with controller")
if self.shim.values is None:
raise TimeoutError("Joystick hasn't updated values in last 200ms")
return self.shim.values
def led_color(self, red=0, green=0, blue=0):
""" set RGB color in range 0-255"""
color = (int(red),int(green),int(blue))
if( self._color == color ):
return
self._color = color
self.thread.controller.device.set_led( *self._color )
def rumble(self, small=0, big=0):
""" rumble in range 0-255 """
rumble = (int(small),int(big))
if( self._rumble == rumble ):
return
self._rumble = rumble
self.thread.controller.device.rumble( *self._rumble )
def led_flash(self, on=0, off=0):
""" flash led: on and off times in range 0 - 255 """
flash = (int(on),int(off))
if( self._flash == flash ):
return
self._flash = flash
if( self._flash == (0,0) ):
self.thread.controller.device.stop_led_flash()
else:
self.thread.controller.device.start_led_flash( *self._flash )
if __name__ == "__main__":
j = Joystick()
while 1:
for key, value in j.get_input().items():
print(key,value)
print()
time.sleep(0.1)
| 5,123 | Python | 28.28 | 96 | 0.579934 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/PS4Joystick/mac_joystick.py | import os
import pygame
from UDPComms import Publisher
os.environ["SDL_VIDEODRIVER"] = "dummy"
drive_pub = Publisher(8830)
arm_pub = Publisher(8410)
pygame.display.init()
pygame.joystick.init()
# wait until joystick is connected
while 1:
try:
pygame.joystick.Joystick(0).init()
break
except pygame.error:
pygame.time.wait(500)
# Prints the joystick's name
JoyName = pygame.joystick.Joystick(0).get_name()
print("Name of the joystick:")
print(JoyName)
# Gets the number of axes
JoyAx = pygame.joystick.Joystick(0).get_numaxes()
print("Number of axis:")
print(JoyAx)
while True:
pygame.event.pump()
forward = (pygame.joystick.Joystick(0).get_axis(3))
twist = (pygame.joystick.Joystick(0).get_axis(2))
on = (pygame.joystick.Joystick(0).get_button(5))
if on:
print({'f':-150*forward,'t':-80*twist})
drive_pub.send({'f':-150*forward,'t':-80*twist})
else:
drive_pub.send({'f':0,'t':0})
pygame.time.wait(100)
| 994 | Python | 22.139534 | 56 | 0.662978 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/PS4Joystick/setup.py | #!/usr/bin/env python
from distutils.core import setup
setup(name='PS4Joystick',
version='2.0',
py_modules=['PS4Joystick'],
description='Interfaces with a PS4 joystick over Bluetooth',
author='Michal Adamkiewicz',
author_email='mikadam@stanford.edu',
url='https://github.com/stanfordroboticsclub/JoystickUDP',
)
| 356 | Python | 24.499998 | 66 | 0.679775 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/PS4Joystick/local_or_remote.py | import os
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM) # Broadcom pin-numbering scheme
GPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_UP)
while 1:
if not GPIO.input(21):
print("eanbling joystick")
os.system("sudo systemctl start ds4drv")
os.system("sudo systemctl start joystick")
#os.system("screen sudo python3 /home/pi/RoverCommand/joystick.py")
else:
os.system("sudo systemctl stop ds4drv")
os.system("sudo systemctl stop joystick")
print("not eanbling joystick")
time.sleep(5)
| 566 | Python | 27.349999 | 75 | 0.673145 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/PS4Joystick/README.md | # PS4Joystick
Code allowing the use of a DualShock (PS4 Joystick) over Bluetooth on Linux. Over USB comming soon. `mac_joystick.py` shows how to emulate something similar on macOS, but without the fancy features.
Note: We have updated from the previous version so make sure you disable ds4drv from running automatically at startup as they will conflict.
This method still requires [ds4drv](https://github.com/chrippa/ds4drv) however it doesn't run it as a separate service and then separately pull joystick data using Pygame. Instead it imports ds4drv directly which gives us much more control over the joystick behaviour. Specifically:
- It will only pair to one joystick allowing us to run multiple robots at a time
- Allows for launching joystick code via systemd at boot using `sudo systemctl enable joystick`
- Can change joystick colors and using rumble directly from Python (can also access the touchpad and IMU!)
- Is a much nicer interface than using Pygame, as the axes are actually named as opposed to arbitrarly numbered! The axis directions are consistant with Pygame.
- Doesn't need $DISPLAY hacks to run on headless devices
### Usage
Take a look at `rover_example.py` as it demonstrates most features.
To implement this functionality to a new repository (say [PupperCommand](https://github.com/stanfordroboticsclub/PupperCommand)) you can just call `from PS4Joystick import Joystick` anywhere once you've installed the module. Replicate `joystick.service` in that repository.
### Install
``` sudo bash install.sh ```
### macOS
Sadly ds4drv doesn't work on Macs. But you can get some of the functionality by installing Pygame with `sudo pip3 install Pygame`. Take a look in `mac_joystick.py` for an example. Note this only works over USB (plug the controller in using a micro usb cable) and the mapping is different than using Pygame with ds4drv | 1,873 | Markdown | 65.928569 | 317 | 0.789642 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/QuadrupedRobot-mini_pupper/PS4Joystick/rover_example.py | from UDPComms import Publisher
from PS4Joystick import Joystick
import time
from enum import Enum
drive_pub = Publisher(8830)
arm_pub = Publisher(8410)
j=Joystick()
MODES = Enum('MODES', 'SAFE DRIVE ARM')
mode = MODES.SAFE
while True:
values = j.get_input()
if( values['button_ps'] ):
if values['dpad_up']:
mode = MODES.DRIVE
j.led_color(red=255)
elif values['dpad_right']:
mode = MODES.ARM
j.led_color(blue=255)
elif values['dpad_down']:
mode = MODES.SAFE
j.led_color(green=255)
# overwrite when swiching modes to prevent phantom motions
values['dpad_down'] = 0
values['dpad_up'] = 0
values['dpad_right'] = 0
values['dpad_left'] = 0
if mode == MODES.DRIVE:
forward_left = - values['left_analog_y']
forward_right = - values['right_analog_y']
twist = values['right_analog_x']
on_right = values['button_r1']
on_left = values['button_l1']
l_trigger = values['l2_analog']
if on_left or on_right:
if on_right:
forward = forward_right
else:
forward = forward_left
slow = 150
fast = 500
max_speed = (fast+slow)/2 + l_trigger*(fast-slow)/2
out = {'f':(max_speed*forward),'t':-150*twist}
drive_pub.send(out)
print(out)
else:
drive_pub.send({'f':0,'t':0})
elif mode == MODES.ARM:
r_forward = - values['right_analog_y']
r_side = values['right_analog_x']
l_forward = - values['left_analog_y']
l_side = values['left_analog_x']
r_shoulder = values['button_r1']
l_shoulder = values['button_l1']
r_trigger = values['r2_analog']
l_trigger = values['l2_analog']
square = values['button_square']
cross = values['button_cross']
circle = values['button_circle']
triangle = values['button_triangle']
PS = values['button_ps']
# hat directions could be reversed from previous version
hat = [ values["dpad_up"] - values["dpad_down"],
values["dpad_right"] - values["dpad_left"] ]
reset = (PS == 1) and (triangle == 1)
reset_dock = (PS==1) and (square ==1)
target_vel = {"x": l_side,
"y": l_forward,
"z": (r_trigger - l_trigger)/2,
"yaw": r_side,
"pitch": r_forward,
"roll": (r_shoulder - l_shoulder),
"grip": cross - square,
"hat": hat,
"reset": reset,
"resetdock":reset_dock,
"trueXYZ": circle,
"dock": triangle}
print(target_vel)
arm_pub.send(target_vel)
elif mode == MODES.SAFE:
# random stuff to demo color features
triangle = values['button_triangle']
square = values['button_square']
j.rumble(small = 255*triangle, big = 255*square)
r2 = values['r2_analog']
r2 = j.map( r2, -1, 1, 0 ,255)
j.led_color( green = 255, blue = r2)
else:
pass
time.sleep(0.1)
| 3,285 | Python | 26.847457 | 66 | 0.506849 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/stanford_pupper_Chandykunju Alex/package.xml | <package format="2">
<name>standford_pupper_description</name>
<version>1.0.0</version>
<description>
<p>URDF Description package for standford_pupper</p>
<p>This package contains configuration data, 3D models and launch files
for standford_pupper robot</p>
</description>
<author>Chandy Alex</author>
<maintainer email="chandyalex92@gmail.com" />
<license>BSD</license>
<buildtool_depend>catkin</buildtool_depend>
<depend>roslaunch</depend>
<depend>robot_state_publisher</depend>
<depend>rviz</depend>
<depend>joint_state_publisher_gui</depend>
<depend>gazebo</depend>
<export>
<architecture_independent />
</export>
</package> | 670 | XML | 30.952379 | 75 | 0.722388 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/Mini_pupper/stanford_pupper_Chandykunju Alex/README.md |
# Stanford Pupper Robot Description (URDF)
## Overview
This package contains a simplified robot description (URDF) of the [Stanford Pupper](https://stanfordstudentrobotics.org/pupper) developed by [Stanford Robotics club](https://github.com/stanfordroboticsclub/StanfordQuadruped).
## License
This software is released under a [BSD 3-Clause license](LICENSE).
| 369 | Markdown | 23.666665 | 226 | 0.783198 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/CODE_OF_CONDUCT.md | # Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at mauricerahme2020@u.northwestern.edu. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
| 3,367 | Markdown | 42.740259 | 87 | 0.822097 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/CONTRIBUTING.md | # Contributing
When contributing to this repository, please first discuss the change you wish to make via issue,
[email](mauricerahme2020@u.northwestern.edu), or any other direct method with me. For those of you on the [Spot Micro Slack](https://spotmicroai-inviter.herokuapp.com/), contact me there (Maurice Rahme). Please be sure to follow the code of conduct.
## Examples of Contributions
1. New platform support (e.g. Gazebo, MuJoCo).
2. RL Agent addition (e.g. DDPG, PPO).
3. Simulation improvement (e.g. motor response in Pybullet)
4. Sensing capabilities in simulation (e.g. LIDAR, Camera)
If in doubt, please talk to me, and I'll let you know if your idea will be helpful to the project. Some things are better served as issues, such as:
## Examples of Issues
1. Bugs.
2. Feature Requests.
3. Clarifications.
4. Platform support (e.g. something is not working in your specific environment).
## Pull Request Process
1. Fork this repository.
2. Create a new branch titled `your-username`
3. Once your changes are ready, please send me a link to your branch so that I can try it out (there will be unit tests in the future).
4. If I approve your change, you may merge to `spot` and submit a PR.
| 1,207 | Markdown | 43.740739 | 249 | 0.755592 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/readthedocs.yml | # .readthedocs.yml
# Read the Docs configuration file
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
# Required
version: 2
# Build documentation in the docs/ directory with Sphinx
sphinx:
configuration: docs/conf.py
# Build documentation with MkDocs
#mkdocs:
# configuration: mkdocs.yml
# Optionally build your docs in additional formats such as PDF
formats:
- pdf
# Optionally set the version of Python and requirements required to build your docs
python:
version: 3.7
install:
- requirements: docs/requirements.txt | 563 | YAML | 22.499999 | 83 | 0.765542 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/toc.md |
Table of Contents
=================
* [Spot Mini Mini OpenAI Gym Environment](#spot-mini-mini-openai-gym-environment)
* [Motivation](#motivation)
* [Kinematics:](#kinematics)
* [Reinforcement Learning](#reinforcement-learning)
* [Stability on Difficult Terrain](#stability-on-difficult-terrain)
* [Drift Correction](#drift-correction)
* [Gait:](#gait)
* [How To Run](#how-to-run)
* [Dependencies](#dependencies)
* [Joystick Control with ROS](#joystick-control-with-ros)
* [Testing Environment (Non-Joystick)](#testing-environment-non-joystick)
* [Reinforcement Learning Agent Evaluation](#reinforcement-learning-agent-evaluation)
* [Using Different Terrain](#using-different-terrain)
Created by [gh-md-toc](https://github.com/ekalinin/github-markdown-toc)
| 834 | Markdown | 40.749998 | 91 | 0.676259 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/README.md | Note: development for this project was haulted in November 2020 to respect my NDA with my employer.
## Spot Mini Mini OpenAI Gym Environment
[![GitHub release](https://img.shields.io/github/release/moribots/spot_mini_mini.svg)](https://github.com/moribots/spot_mini_mini/releases)
[![Documentation Status](https://readthedocs.org/projects/spot-mini-mini/badge/?version=latest)](https://spot-mini-mini.readthedocs.io/en/latest/?badge=latest)
[![Maintenance](https://img.shields.io/badge/Maintained%3F-no-red.svg)](https://github.com/moribots/spot_mini_mini/graphs/commit-activity)
[![PR](https://camo.githubusercontent.com/f96261621753dacf526590825b84f87ccb1db0e6/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5052732d77656c636f6d652d627269676874677265656e2e7376673f7374796c653d666c6174)](https://github.com/moribots/spot_mini_mini/pulls)
[![Open Source Love png2](https://camo.githubusercontent.com/60dcf2177b53824e7912a6adfb3ff5e318d14ae4/68747470733a2f2f6261646765732e66726170736f66742e636f6d2f6f732f76312f6f70656e2d736f757263652e706e673f763d313033)](https://github.com/moribots)
[![MIT license](https://img.shields.io/badge/License-MIT-blue.svg)](https://github.com/moribots/spot_mini_mini/blob/spot/LICENSE)
<!-- ![SIK](spot_bullet/media/spot-mini-mini.gif) -->
<p float="left">
<img src="spot_real/media/spot_hello.gif" width="670" />
</p>
**Featured in [Robotics Weekly](https://weeklyrobotics.com/weekly-robotics-98) and [Mithi's Robotics Coursework](https://github.com/mithi/robotics-coursework/#hands-on-and-blogs)!**
## Motivation
As part of the [Spot Micro](https://spotmicroai.readthedocs.io/en/latest/) community, I saw the need for a reliable and versatile simulator for those who wanted to try things out without risking damage to their robots. To that end, I developed my own in Pybullet which can also be used as a Gym environment for Reinforcement Learning tasks.
<p float="left">
<img src="spot_bullet/media/spot_new_demo.gif" width="335" />
<img src="spot_real/media/full_control.gif" width="335" />
</p>
You'll notice that there are gifs of the original `SpotMicro` as well a new version designed for added real world fidelity. The default branch simulates the new version, but you can work with `SpotMicro` in the [spotmicroai](https://github.com/moribots/spot_mini_mini/tree/spotmicroai) branch of this repo. The new version also has a more reliable URDF, with more accurate inertial calculations.
If you don't need a Gym environment, that's okay too! `env_tester.py` works without RL or Gym, it is designed to accept any gait implementation, and provides a GUI for testing it out! In my case, I've implemented a 12-point Bezier gait.
<!--
<p float="left">
<img src="spot_real/media/spot_demo.gif" width="670" />
</p>
-->
**Read the [docs](https://spot-mini-mini.readthedocs.io/en/latest/index.html)!**
Table of Contents
-----------------
* [Motivation](#motivation)
* [Kinematics](#kinematics)
* [D^2 Gait Modulation with Bezier Curves](#d2-gait-modulation-with-bezier-curves)
* [Training](#Training)
* [Real World Validation](#real-world-validation)
* [Gait](#gait)
* [How To Run](#how-to-run)
* [Dependencies](#dependencies)
* [Joystick Control with ROS](#joystick-control-with-ros)
* [Testing Environment (Non-Joystick)](#testing-environment-non-joystick)
* [Reinforcement Learning Agent Training](#reinforcement-learning-agent-training)
* [Reinforcement Learning Agent Evaluation](#reinforcement-learning-agent-evaluation)
* [Using Different Terrain](#using-different-terrain)
* [Hardware](https://github.com/moribots/spot_mini_mini/tree/spot/spot_real)
* [Assembly & Calibration](https://github.com/moribots/spot_mini_mini/tree/spot/spot_real/Calibration.md)
* [Citing Spot Mini Mini](#citing-spot-mini-mini)
* [Credits](#credits)
### Kinematics
Body manipulation with [leg IK](https://www.researchgate.net/publication/320307716_Inverse_Kinematic_Analysis_Of_A_Quadruped_Robot) and [body IK](https://moribots.github.io/project/spot-mini-mini) descriptions.
<img src="spot_bullet/media/spot_rpy.gif" alt="SIK" width="500"/>
<img src="spot_real/media/rpy.gif" alt="SRIK" width="500"/>
### D^2 Gait Modulation with Bezier Curves
I'm using this platform to validate a novel Reinforcement Learning method for locomotion by myself and my co-authors Matthew L. Elwin, Ian Abraham, and Todd D. Murphey. Instead of learning a gait from scratch, we propose using an existing scheme as a baseline over which we optimize via training. The method is called `D^2 Gait Modulation with Bezier Curves`. To learn more, visit our [website](https://sites.google.com/view/drgmbc)
<p float="left">
<img src="spot_real/media/V_descent.gif" width="335" />
<img src="spot_real/media/A_descent.gif" width="335" />
</p>
#### Training
During training, simple Proportional controller was employed to deliver yaw correction as would be the case if the robot were teleoperated or able to localize itself. For increased policy robustness, the terrain, link masses and foot frictions are randomized on each environment reset.
Here, the action space is 14-dimensional, consisting of `Clearance Height` (1), `Body Height` (1), and `Foot XYZ Residual` modulations (12). `Clearance Height` is treated through an exponential filter (`alpha = 0.7`), but all other actions are processed directly. These results were trained with only 149 epochs.
Before training, the robot falls almost immediately:
![FALL](spot_bullet/media/spot_rough_falls.gif)
After training, the robot successfully navigates the terrain:
![NO_FALL](spot_bullet/media/spot_rough_ARS.gif)
What's even better, is that the same agent `#149` is able to adapt to unseen commands, making high-level system integration straightforward. Here it is being teleoperated using `Forward`, `Lateral`, and `Yaw` commands.
![UNIVERSAL](spot_bullet/media/spot_universal.gif)
Here's an example of the new URDF being teleoperated with a trained agent on 2x higher terrain:
![UNIVERSAL2](spot_bullet/media/spot_new_universal.gif)
#### Real World Validation
Here are some experimental results where the agent is on the right.
<p float="left">
<img src="spot_real/media/V2_3.gif" width="335" />
<img src="spot_real/media/T2_1.gif" width="335" />
</p>
### Gait
Open-Loop Gait using 12-Point Bezier Curves based on [MIT Cheetah Paper](https://dspace.mit.edu/handle/1721.1/98270) with [modifications](https://spot-mini-mini.readthedocs.io/en/latest/source/spotmicro.GaitGenerator.html#spotmicro.GaitGenerator.Bezier.BezierGait.GetPhase) for low step velocity discontinuity.
Forward and Lateral Motion:
![SLAT0](spot_bullet/media/spot_lat_logic.gif)
Yaw logic based on [4-wheel steering car](http://www.inase.org/library/2014/santorini/bypaper/ROBCIRC/ROBCIRC-54.pdf):
![SYAW0](spot_bullet/media/spot_yaw_logic.gif)
## How To Run
### Dependencies
* ROS Melodic
* Gazebo
* Pytorch
* Pybullet
* Gym
* OpenCV
* Scipy
* Numpy
### Joystick Control with ROS
First, you're going to need a joystick (okay, not really, but it's more fun if you have one).
**Setting Up The Joystick:**
* Get Number (you will see something like jsX): `ls /dev/input/`
* Make available to ROS: `sudo chmod a+rw /dev/input/jsX`
* Make sure `<param name="dev" type="string" value="/dev/input/jsX"/>` matches your setup in the launchfile
Then simply: `roslaunch mini_ros spot_move.launch`
You can ignore this msg: `[ERROR] [1591631380.406690714]: Couldn't open joystick force feedback!` It just means your controller is missing some functionality, but this package doesn't use it.
**Controls:**
Assuming you have a Logitech Gamepad F310:
`A`: switch between stepping and RPY
`X`: E-STOP (engage and disengage)
**Stepping Mode**:
* `Right Stick Up/Down`: Step Length
* `Right Stick Left/Right`: Lateral Fraction
* `Left Stick Up/Down`: Robot Height
* `Left Stick Left/Right`: Yaw Rate
* `Arrow Pad Up/Down` (DISCRETE): Step Height
* `Arrow Pad Left/Right` (DISCRETE): Step Depth
* `Bottom Right/Left Bumpers`: Step Velocity (modulate)
* `Top Right/Left Bumpers`: reset all to default
**Viewing Mode**:
* `Right Stick Up/Down`: Pitch
* `Right Stick Left/Right`: Roll
* `Left Stick Up/Down`: Robot Height
* `Left Stick Left/Right`: Yaw
Changing `Step Velocity` while moving forward:
![SVMOD](mini_ros/media/stepvel_mod.gif)
Changing `Step Length` while moving forward:
![SVMOD](mini_ros/media/steplen_mod.gif)
Yaw In Place: Slightly push the `Right Stick` forward while pushing the `Left Stick` maximally in either direction:
![SVMOD](mini_ros/media/yaw_in_place.gif)
### Testing Environment (Non-Joystick)
If you don't have a joystick, go to `spot_bullet/src` and do `./env_tester.py`. A Pybullet sim will open up for you with the same controls you would have on the joystick, except each is on its own scrollbar. You may also use the following optional arguments:
```
-h, --help show this help message and exit
-hf, --HeightField Use HeightField
-r, --DebugRack Put Spot on an Elevated Rack
-p, --DebugPath Draw Spot's Foot Path
-ay, --AutoYaw Automatically Adjust Spot's Yaw
-ar, --AutoReset Automatically Reset Environment When Spot Falls
```
### Reinforcement Learning Agent Training
Go to `spot_bullet/src` and do `./spot_ars.py`. Models will be saved every `9th` episode to `spot_bullet/models/`. I will add some more arguments in the future to give you finer control of the heightfield mesh from the command line.
### Reinforcement Learning Agent Evaluation
Go to `spot_bullet/src` and do `./spot_ars_eval.py`. You may also use the following optional arguments. Note that if you don't use the `-a` argument, no agent will be loaded, so you will be using the open-loop policy. For example, if you enter `149` after `-a`, you will see the first successful policy, but if you enter `2229`, you will see a much more aggressive policy.
```
-h, --help show this help message and exit
-hf, --HeightField Use HeightField
-r, --DebugRack Put Spot on an Elevated Rack
-p, --DebugPath Draw Spot's Foot Path
-gui, --GUI Control The Robot Yourself With a GUI
-a, --AgentNum Agent Number To Load (followed by number)
```
### Using Different Terrain
Navigate to `spotmicro/heightfield.py` and take a look at `useProgrammatic` and `useTerrainFromPNG` (you can play around with the mesh scales for each) to experiment with different terrains. Make sure that the `spotBezierEnv` instance has `height_field=True` in `env_tester.py` and `spot_pybullet_interface` depending on whether you're using the joystick/ROS version. The same goes for the RL environments. Note: these were adapted from the [pybullet](https://github.com/bulletphysics/bullet3/blob/master/examples/pybullet/examples/heightfield.py) source code.
`useTerrainFromPNG`
![PNGT](spot_bullet/media/spot_png_terrain.png)
`useProgrammatic`
![PROGT](spot_bullet/media/spot_prog_terrain.png)
With this terrain type, I programmed in a randomizer that triggers upon reset. This, along with the body randomizer from `Pybullet's Minitaur` increases your RL Policy's robustness.
![RANDENV](spot_bullet/media/spot_random_terrain.gif)
## Citing Spot Mini Mini
```
@software{spotminimini2020github,
author = {Maurice Rahme and Ian Abraham and Matthew Elwin and Todd Murphey},
title = {SpotMiniMini: Pybullet Gym Environment for Gait Modulation with Bezier Curves},
url = {https://github.com/moribots/spot_mini_mini},
version = {2.1.0},
year = {2020},
}
```
## Credits
* Original Spot Design and CAD files: [Spot Micro AI Community](https://spotmicroai.readthedocs.io/en/latest/)
* Collaborator on `OpenQuadruped` design, including mechanical parts, custom PCB, and Teensy interface: [Adham Elarabawy](https://github.com/adham-elarabawy/OpenQuadruped)
* OpenAI Gym and Heightfield Interface: [Minitaur Environment](https://github.com/bulletphysics/bullet3/blob/master/examples/pybullet/gym/pybullet_envs/bullet/minitaur.py)
* Deprecated URDF for earlier development: [Rex Gym](https://github.com/nicrusso7/rex-gym)
| 12,090 | Markdown | 47.558233 | 560 | 0.750538 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/spot_ars.py | #!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import sys
sys.path.append('../../')
from spotmicro.util.gui import GUI
from spotmicro.GymEnvs.spot_bezier_env import spotBezierEnv
from spotmicro.Kinematics.SpotKinematics import SpotModel
from spotmicro.GaitGenerator.Bezier import BezierGait
from spotmicro.OpenLoopSM.SpotOL import BezierStepper
from spotmicro.spot_env_randomizer import SpotEnvRandomizer
import time
from ars_lib.ars import ARSAgent, Normalizer, Policy, ParallelWorker
# Multiprocessing package for python
# Parallelization improvements based on:
# https://github.com/bulletphysics/bullet3/blob/master/examples/pybullet/gym/pybullet_envs/ARS/ars.py
import multiprocessing as mp
from multiprocessing import Pipe
import os
import argparse
# ARGUMENTS
descr = "Spot Mini Mini ARS Agent Trainer."
parser = argparse.ArgumentParser(description=descr)
parser.add_argument("-hf",
"--HeightField",
help="Use HeightField",
action='store_true')
parser.add_argument("-nc",
"--NoContactSensing",
help="Disable Contact Sensing",
action='store_true')
parser.add_argument("-dr",
"--DontRandomize",
help="Do NOT Randomize State and Environment.",
action='store_true')
parser.add_argument("-s", "--Seed", help="Seed (Default: 0).")
ARGS = parser.parse_args()
# Messages for Pipe
_RESET = 1
_CLOSE = 2
_EXPLORE = 3
def main():
""" The main() function. """
# Hold mp pipes
mp.freeze_support()
print("STARTING SPOT TRAINING ENV")
seed = 0
if ARGS.Seed:
seed = int(ARGS.Seed)
print("SEED: {}".format(seed))
max_timesteps = 4e6
eval_freq = 1e1
save_model = True
file_name = "spot_ars_"
if ARGS.HeightField:
height_field = True
else:
height_field = False
if ARGS.NoContactSensing:
contacts = False
else:
contacts = True
if ARGS.DontRandomize:
env_randomizer = None
rand_name = "norand_"
else:
env_randomizer = SpotEnvRandomizer()
rand_name = "rand_"
# Find abs path to this file
my_path = os.path.abspath(os.path.dirname(__file__))
results_path = os.path.join(my_path, "../results")
if contacts:
models_path = os.path.join(my_path, "../models/contact")
else:
models_path = os.path.join(my_path, "../models/no_contact")
if not os.path.exists(results_path):
os.makedirs(results_path)
if not os.path.exists(models_path):
os.makedirs(models_path)
env = spotBezierEnv(render=False,
on_rack=False,
height_field=height_field,
draw_foot_path=False,
contacts=contacts,
env_randomizer=env_randomizer)
# Set seeds
env.seed(seed)
np.random.seed(seed)
state_dim = env.observation_space.shape[0]
print("STATE DIM: {}".format(state_dim))
action_dim = env.action_space.shape[0]
print("ACTION DIM: {}".format(action_dim))
max_action = float(env.action_space.high[0])
env.reset()
g_u_i = GUI(env.spot.quadruped)
spot = SpotModel()
T_bf = spot.WorldToFoot
bz_step = BezierStepper(dt=env._time_step)
bzg = BezierGait(dt=env._time_step)
# Initialize Normalizer
normalizer = Normalizer(state_dim)
# Initialize Policy
policy = Policy(state_dim, action_dim, seed=seed)
# Initialize Agent with normalizer, policy and gym env
agent = ARSAgent(normalizer, policy, env, bz_step, bzg, spot)
agent_num = 0
if os.path.exists(models_path + "/" + file_name + str(agent_num) +
"_policy"):
print("Loading Existing agent")
agent.load(models_path + "/" + file_name + str(agent_num))
env.reset(agent.desired_velocity, agent.desired_rate)
episode_reward = 0
episode_timesteps = 0
episode_num = 0
# Create mp pipes
num_processes = policy.num_deltas
processes = []
childPipes = []
parentPipes = []
# Store mp pipes
for pr in range(num_processes):
parentPipe, childPipe = Pipe()
parentPipes.append(parentPipe)
childPipes.append(childPipe)
# Start multiprocessing
# Start multiprocessing
for proc_num in range(num_processes):
p = mp.Process(target=ParallelWorker,
args=(childPipes[proc_num], env, state_dim))
p.start()
processes.append(p)
print("STARTED SPOT TRAINING ENV")
t = 0
while t < (int(max_timesteps)):
# Maximum timesteps per rollout
episode_reward, episode_timesteps = agent.train_parallel(parentPipes)
t += episode_timesteps
# episode_reward = agent.train()
# +1 to account for 0 indexing.
# +0 on ep_timesteps since it will increment +1 even if done=True
print(
"Total T: {} Episode Num: {} Episode T: {} Reward: {:.2f} REWARD PER STEP: {:.2f}"
.format(t + 1, episode_num, episode_timesteps, episode_reward,
episode_reward / float(episode_timesteps)))
# Store Results (concat)
if episode_num == 0:
res = np.array(
[[episode_reward, episode_reward / float(episode_timesteps)]])
else:
new_res = np.array(
[[episode_reward, episode_reward / float(episode_timesteps)]])
res = np.concatenate((res, new_res))
# Also Save Results So Far (Overwrite)
# Results contain 2D numpy array of total reward for each ep
# and reward per timestep for each ep
np.save(
results_path + "/" + str(file_name) + rand_name + "seed" +
str(seed), res)
# Evaluate episode
if (episode_num + 1) % eval_freq == 0:
if save_model:
agent.save(models_path + "/" + str(file_name) +
str(episode_num))
episode_num += 1
# Close pipes and hence envs
for parentPipe in parentPipes:
parentPipe.send([_CLOSE, "pay2"])
for p in processes:
p.join()
if __name__ == '__main__':
main()
| 6,299 | Python | 28.166667 | 101 | 0.600572 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/env_tester.py | #!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import copy
import sys
sys.path.append('../../')
from spotmicro.GymEnvs.spot_bezier_env import spotBezierEnv
from spotmicro.util.gui import GUI
from spotmicro.Kinematics.SpotKinematics import SpotModel
from spotmicro.Kinematics.LieAlgebra import RPY
from spotmicro.GaitGenerator.Bezier import BezierGait
from spotmicro.spot_env_randomizer import SpotEnvRandomizer
# TESTING
from spotmicro.OpenLoopSM.SpotOL import BezierStepper
import time
import os
import argparse
# ARGUMENTS
descr = "Spot Mini Mini Environment Tester (No Joystick)."
parser = argparse.ArgumentParser(description=descr)
parser.add_argument("-hf",
"--HeightField",
help="Use HeightField",
action='store_true')
parser.add_argument("-r",
"--DebugRack",
help="Put Spot on an Elevated Rack",
action='store_true')
parser.add_argument("-p",
"--DebugPath",
help="Draw Spot's Foot Path",
action='store_true')
parser.add_argument("-ay",
"--AutoYaw",
help="Automatically Adjust Spot's Yaw",
action='store_true')
parser.add_argument("-ar",
"--AutoReset",
help="Automatically Reset Environment When Spot Falls",
action='store_true')
parser.add_argument("-dr",
"--DontRandomize",
help="Do NOT Randomize State and Environment.",
action='store_true')
ARGS = parser.parse_args()
def main():
""" The main() function. """
print("STARTING SPOT TEST ENV")
seed = 0
max_timesteps = 4e6
# Find abs path to this file
my_path = os.path.abspath(os.path.dirname(__file__))
results_path = os.path.join(my_path, "../results")
models_path = os.path.join(my_path, "../models")
if not os.path.exists(results_path):
os.makedirs(results_path)
if not os.path.exists(models_path):
os.makedirs(models_path)
if ARGS.DebugRack:
on_rack = True
else:
on_rack = False
if ARGS.DebugPath:
draw_foot_path = True
else:
draw_foot_path = False
if ARGS.HeightField:
height_field = True
else:
height_field = False
if ARGS.DontRandomize:
env_randomizer = None
else:
env_randomizer = SpotEnvRandomizer()
env = spotBezierEnv(render=True,
on_rack=on_rack,
height_field=height_field,
draw_foot_path=draw_foot_path,
env_randomizer=env_randomizer)
# Set seeds
env.seed(seed)
np.random.seed(seed)
state_dim = env.observation_space.shape[0]
print("STATE DIM: {}".format(state_dim))
action_dim = env.action_space.shape[0]
print("ACTION DIM: {}".format(action_dim))
max_action = float(env.action_space.high[0])
state = env.reset()
g_u_i = GUI(env.spot.quadruped)
spot = SpotModel()
T_bf0 = spot.WorldToFoot
T_bf = copy.deepcopy(T_bf0)
bzg = BezierGait(dt=env._time_step)
bz_step = BezierStepper(dt=env._time_step, mode=0)
action = env.action_space.sample()
FL_phases = []
FR_phases = []
BL_phases = []
BR_phases = []
FL_Elbow = []
yaw = 0.0
print("STARTED SPOT TEST ENV")
t = 0
while t < (int(max_timesteps)):
bz_step.ramp_up()
pos, orn, StepLength, LateralFraction, YawRate, StepVelocity, ClearanceHeight, PenetrationDepth = bz_step.StateMachine(
)
pos, orn, StepLength, LateralFraction, YawRate, StepVelocity, ClearanceHeight, PenetrationDepth, SwingPeriod = g_u_i.UserInput(
)
# Update Swing Period
bzg.Tswing = SwingPeriod
yaw = env.return_yaw()
P_yaw = 5.0
if ARGS.AutoYaw:
YawRate += -yaw * P_yaw
# print("YAW RATE: {}".format(YawRate))
# TEMP
bz_step.StepLength = StepLength
bz_step.LateralFraction = LateralFraction
bz_step.YawRate = YawRate
bz_step.StepVelocity = StepVelocity
contacts = state[-4:]
FL_phases.append(env.spot.LegPhases[0])
FR_phases.append(env.spot.LegPhases[1])
BL_phases.append(env.spot.LegPhases[2])
BR_phases.append(env.spot.LegPhases[3])
# Get Desired Foot Poses
T_bf = bzg.GenerateTrajectory(StepLength, LateralFraction, YawRate,
StepVelocity, T_bf0, T_bf,
ClearanceHeight, PenetrationDepth,
contacts)
joint_angles = spot.IK(orn, pos, T_bf)
FL_Elbow.append(np.degrees(joint_angles[0][-1]))
# for i, (key, Tbf_in) in enumerate(T_bf.items()):
# print("{}: \t Angle: {}".format(key, np.degrees(joint_angles[i])))
# print("-------------------------")
env.pass_joint_angles(joint_angles.reshape(-1))
# Get External Observations
env.spot.GetExternalObservations(bzg, bz_step)
# Step
state, reward, done, _ = env.step(action)
# print("IMU Roll: {}".format(state[0]))
# print("IMU Pitch: {}".format(state[1]))
# print("IMU GX: {}".format(state[2]))
# print("IMU GY: {}".format(state[3]))
# print("IMU GZ: {}".format(state[4]))
# print("IMU AX: {}".format(state[5]))
# print("IMU AY: {}".format(state[6]))
# print("IMU AZ: {}".format(state[7]))
# print("-------------------------")
if done:
print("DONE")
if ARGS.AutoReset:
env.reset()
# plt.plot()
# # plt.plot(FL_phases, label="FL")
# # plt.plot(FR_phases, label="FR")
# # plt.plot(BL_phases, label="BL")
# # plt.plot(BR_phases, label="BR")
# plt.plot(FL_Elbow, label="FL ELbow (Deg)")
# plt.xlabel("dt")
# plt.ylabel("value")
# plt.title("Leg Phases")
# plt.legend()
# plt.show()
# time.sleep(1.0)
t += 1
env.close()
print(joint_angles)
if __name__ == '__main__':
main()
| 6,407 | Python | 27.864865 | 135 | 0.547214 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/spot_ars_eval.py | #!/usr/bin/env python
import numpy as np
import sys
sys.path.append('../../')
from ars_lib.ars import ARSAgent, Normalizer, Policy
from spotmicro.util.gui import GUI
from spotmicro.Kinematics.SpotKinematics import SpotModel
from spotmicro.GaitGenerator.Bezier import BezierGait
from spotmicro.OpenLoopSM.SpotOL import BezierStepper
from spotmicro.GymEnvs.spot_bezier_env import spotBezierEnv
from spotmicro.spot_env_randomizer import SpotEnvRandomizer
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
import os
import argparse
# ARGUMENTS
descr = "Spot Mini Mini ARS Agent Evaluator."
parser = argparse.ArgumentParser(description=descr)
parser.add_argument("-hf",
"--HeightField",
help="Use HeightField",
action='store_true')
parser.add_argument("-nr",
"--DontRender",
help="Don't Render environment",
action='store_true')
parser.add_argument("-r",
"--DebugRack",
help="Put Spot on an Elevated Rack",
action='store_true')
parser.add_argument("-p",
"--DebugPath",
help="Draw Spot's Foot Path",
action='store_true')
parser.add_argument("-gui",
"--GUI",
help="Control The Robot Yourself With a GUI",
action='store_true')
parser.add_argument("-nc",
"--NoContactSensing",
help="Disable Contact Sensing",
action='store_true')
parser.add_argument("-a", "--AgentNum", help="Agent Number To Load")
parser.add_argument("-dr",
"--DontRandomize",
help="Do NOT Randomize State and Environment.",
action='store_true')
parser.add_argument("-pp",
"--PlotPolicy",
help="Plot Policy Output after each Episode.",
action='store_true')
parser.add_argument("-ta",
"--TrueAction",
help="Plot Action as seen by the Robot.",
action='store_true')
parser.add_argument(
"-save",
"--SaveData",
help="Save the Policy Output to a .npy file in the results folder.",
action='store_true')
parser.add_argument("-s", "--Seed", help="Seed (Default: 0).")
ARGS = parser.parse_args()
def main():
""" The main() function. """
print("STARTING MINITAUR ARS")
# TRAINING PARAMETERS
# env_name = "MinitaurBulletEnv-v0"
seed = 0
if ARGS.Seed:
seed = ARGS.Seed
max_timesteps = 4e6
file_name = "spot_ars_"
if ARGS.DebugRack:
on_rack = True
else:
on_rack = False
if ARGS.DebugPath:
draw_foot_path = True
else:
draw_foot_path = False
if ARGS.HeightField:
height_field = True
else:
height_field = False
if ARGS.NoContactSensing:
contacts = False
else:
contacts = True
if ARGS.DontRender:
render = False
else:
render = True
if ARGS.DontRandomize:
env_randomizer = None
else:
env_randomizer = SpotEnvRandomizer()
# Find abs path to this file
my_path = os.path.abspath(os.path.dirname(__file__))
results_path = os.path.join(my_path, "../results")
if contacts:
models_path = os.path.join(my_path, "../models/contact")
else:
models_path = os.path.join(my_path, "../models/no_contact")
if not os.path.exists(results_path):
os.makedirs(results_path)
if not os.path.exists(models_path):
os.makedirs(models_path)
env = spotBezierEnv(render=render,
on_rack=on_rack,
height_field=height_field,
draw_foot_path=draw_foot_path,
contacts=contacts,
env_randomizer=env_randomizer)
# Set seeds
env.seed(seed)
np.random.seed(seed)
state_dim = env.observation_space.shape[0]
print("STATE DIM: {}".format(state_dim))
action_dim = env.action_space.shape[0]
print("ACTION DIM: {}".format(action_dim))
max_action = float(env.action_space.high[0])
env.reset()
spot = SpotModel()
bz_step = BezierStepper(dt=env._time_step)
bzg = BezierGait(dt=env._time_step)
# Initialize Normalizer
normalizer = Normalizer(state_dim)
# Initialize Policy
policy = Policy(state_dim, action_dim)
# to GUI or not to GUI
if ARGS.GUI:
gui = True
else:
gui = False
# Initialize Agent with normalizer, policy and gym env
agent = ARSAgent(normalizer, policy, env, bz_step, bzg, spot, gui)
agent_num = 0
if ARGS.AgentNum:
agent_num = ARGS.AgentNum
if os.path.exists(models_path + "/" + file_name + str(agent_num) +
"_policy"):
print("Loading Existing agent")
agent.load(models_path + "/" + file_name + str(agent_num))
agent.policy.episode_steps = np.inf
policy = agent.policy
env.reset()
episode_reward = 0
episode_timesteps = 0
episode_num = 0
print("STARTED MINITAUR TEST SCRIPT")
t = 0
while t < (int(max_timesteps)):
episode_reward, episode_timesteps = agent.deployTG()
t += episode_timesteps
# episode_reward = agent.train()
# +1 to account for 0 indexing.
# +0 on ep_timesteps since it will increment +1 even if done=True
print("Total T: {} Episode Num: {} Episode T: {} Reward: {}".format(
t, episode_num, episode_timesteps, episode_reward))
episode_num += 1
# Plot Policy Output
if ARGS.PlotPolicy or ARGS.TrueAction or ARGS.SaveData:
if ARGS.TrueAction:
action_name = "robot_act"
action = np.array(agent.true_action_history)
else:
action_name = "agent_act"
action = np.array(agent.action_history)
if ARGS.SaveData:
if height_field:
terrain_name = "rough_"
else:
terrain_name = "flat_"
np.save(
results_path + "/" + "policy_out_" + terrain_name + action_name, action)
print("SAVED DATA")
ClearHeight_act = action[:, 0]
BodyHeight_act = action[:, 1]
Residuals_act = action[:, 2:]
plt.plot(ClearHeight_act,
label='Clearance Height Mod',
color='black')
plt.plot(BodyHeight_act,
label='Body Height Mod',
color='darkviolet')
# FL
plt.plot(Residuals_act[:, 0],
label='Residual: FL (x)',
color='limegreen')
plt.plot(Residuals_act[:, 1],
label='Residual: FL (y)',
color='lime')
plt.plot(Residuals_act[:, 2],
label='Residual: FL (z)',
color='green')
# FR
plt.plot(Residuals_act[:, 3],
label='Residual: FR (x)',
color='lightskyblue')
plt.plot(Residuals_act[:, 4],
label='Residual: FR (y)',
color='dodgerblue')
plt.plot(Residuals_act[:, 5],
label='Residual: FR (z)',
color='blue')
# BL
plt.plot(Residuals_act[:, 6],
label='Residual: BL (x)',
color='firebrick')
plt.plot(Residuals_act[:, 7],
label='Residual: BL (y)',
color='crimson')
plt.plot(Residuals_act[:, 8],
label='Residual: BL (z)',
color='red')
# BR
plt.plot(Residuals_act[:, 9],
label='Residual: BR (x)',
color='gold')
plt.plot(Residuals_act[:, 10],
label='Residual: BR (y)',
color='orange')
plt.plot(Residuals_act[:, 11],
label='Residual: BR (z)',
color='coral')
plt.xlabel("Epoch Iteration")
plt.ylabel("Action Value")
plt.title("Policy Output")
plt.legend()
plt.show()
env.close()
if __name__ == '__main__':
main()
| 8,583 | Python | 29.119298 | 96 | 0.518467 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/old_eval_scripts/sac_eval.py | #!/usr/bin/env python
import numpy as np
from sac_lib import SoftActorCritic, NormalizedActions, ReplayBuffer, PolicyNetwork
from mini_bullet.minitaur_gym_env import MinitaurBulletEnv
import gym
import torch
import os
import time
def main():
""" The main() function. """
print("STARTING MINITAUR TD3")
# TRAINING PARAMETERS
# env_name = "MinitaurBulletEnv-v0"
seed = 0
max_timesteps = 4e6
file_name = "mini_td3_"
# Find abs path to this file
my_path = os.path.abspath(os.path.dirname(__file__))
results_path = os.path.join(my_path, "../results")
models_path = os.path.join(my_path, "../models")
if not os.path.exists(results_path):
os.makedirs(results_path)
if not os.path.exists(models_path):
os.makedirs(models_path)
env = NormalizedActions(MinitaurBulletEnv(render=True))
# Set seeds
env.seed(seed)
torch.manual_seed(seed)
np.random.seed(seed)
state_dim = env.observation_space.shape[0]
print("STATE DIM: {}".format(state_dim))
action_dim = env.action_space.shape[0]
print("ACTION DIM: {}".format(action_dim))
max_action = float(env.action_space.high[0])
print("RECORDED MAX ACTION: {}".format(max_action))
hidden_dim = 256
policy = PolicyNetwork(state_dim, action_dim, hidden_dim)
replay_buffer_size = 1000000
replay_buffer = ReplayBuffer(replay_buffer_size)
sac = SoftActorCritic(policy=policy,
state_dim=state_dim,
action_dim=action_dim,
replay_buffer=replay_buffer)
policy_num = 2239999
if os.path.exists(models_path + "/" + file_name + str(policy_num) +
"_critic"):
print("Loading Existing Policy")
sac.load(models_path + "/" + file_name + str(policy_num))
policy = sac.policy_net
# Evaluate untrained policy and init list for storage
evaluations = []
state = env.reset()
done = False
episode_reward = 0
episode_timesteps = 0
episode_num = 0
print("STARTED MINITAUR TEST SCRIPT")
for t in range(int(max_timesteps)):
episode_timesteps += 1
# Deterministic Policy Action
action = np.clip(policy.get_action(np.array(state)),
-max_action, max_action)
# rospy.logdebug("Selected Acton: {}".format(action))
# Perform action
next_state, reward, done, _ = env.step(action)
state = next_state
episode_reward += reward
# print("DT REWARD: {}".format(reward))
if done:
# +1 to account for 0 indexing.
# +0 on ep_timesteps since it will increment +1 even if done=True
print(
"Total T: {} Episode Num: {} Episode T: {} Reward: {}".format(
t + 1, episode_num, episode_timesteps, episode_reward))
# Reset environment
state, done = env.reset(), False
evaluations.append(episode_reward)
episode_reward = 0
episode_timesteps = 0
episode_num += 1
if __name__ == '__main__':
main()
| 3,153 | Python | 26.911504 | 83 | 0.595623 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/old_eval_scripts/td3_eval.py | #!/usr/bin/env python
import numpy as np
from td3_lib.td3 import ReplayBuffer, TD3Agent, evaluate_policy
from mini_bullet.minitaur_gym_env import MinitaurBulletEnv
import gym
import torch
import os
import time
def main():
""" The main() function. """
print("STARTING MINITAUR TD3")
# TRAINING PARAMETERS
# env_name = "MinitaurBulletEnv-v0"
seed = 0
max_timesteps = 4e6
file_name = "mini_td3_"
# Find abs path to this file
my_path = os.path.abspath(os.path.dirname(__file__))
results_path = os.path.join(my_path, "../results")
models_path = os.path.join(my_path, "../models")
if not os.path.exists(results_path):
os.makedirs(results_path)
if not os.path.exists(models_path):
os.makedirs(models_path)
env = MinitaurBulletEnv(render=True)
# Set seeds
env.seed(seed)
torch.manual_seed(seed)
np.random.seed(seed)
state_dim = env.observation_space.shape[0]
print("STATE DIM: {}".format(state_dim))
action_dim = env.action_space.shape[0]
print("ACTION DIM: {}".format(action_dim))
max_action = float(env.action_space.high[0])
print("RECORDED MAX ACTION: {}".format(max_action))
policy = TD3Agent(state_dim, action_dim, max_action)
policy_num = 2239999
if os.path.exists(models_path + "/" + file_name +
str(policy_num) + "_critic"):
print("Loading Existing Policy")
policy.load(models_path + "/" + file_name + str(policy_num))
replay_buffer = ReplayBuffer()
# Optionally load existing policy, replace 9999 with num
buffer_number = 0 # BY DEFAULT WILL LOAD NOTHING, CHANGE THIS
if os.path.exists(replay_buffer.buffer_path + "/" + "replay_buffer_" +
str(buffer_number) + '.data'):
print("Loading Replay Buffer " + str(buffer_number))
replay_buffer.load(buffer_number)
print(replay_buffer.storage)
# Evaluate untrained policy and init list for storage
evaluations = []
state = env.reset()
done = False
episode_reward = 0
episode_timesteps = 0
episode_num = 0
print("STARTED MINITAUR TEST SCRIPT")
for t in range(int(max_timesteps)):
episode_timesteps += 1
# Deterministic Policy Action
action = np.clip(policy.select_action(np.array(state)),
-max_action, max_action)
# rospy.logdebug("Selected Acton: {}".format(action))
# Perform action
next_state, reward, done, _ = env.step(action)
state = next_state
episode_reward += reward
# print("DT REWARD: {}".format(reward))
if done:
# +1 to account for 0 indexing.
# +0 on ep_timesteps since it will increment +1 even if done=True
print(
"Total T: {} Episode Num: {} Episode T: {} Reward: {}".format(
t + 1, episode_num, episode_timesteps, episode_reward))
# Reset environment
state, done = env.reset(), False
evaluations.append(episode_reward)
episode_reward = 0
episode_timesteps = 0
episode_num += 1
if __name__ == '__main__':
main()
| 3,213 | Python | 27.954955 | 78 | 0.602552 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/old_eval_scripts/ars_eval.py | #!/usr/bin/env python
import numpy as np
from ars_lib.ars import ARSAgent, Normalizer, Policy, ParallelWorker
from mini_bullet.minitaur_gym_env import MinitaurBulletEnv
import torch
import os
def main():
""" The main() function. """
print("STARTING MINITAUR ARS")
# TRAINING PARAMETERS
# env_name = "MinitaurBulletEnv-v0"
seed = 0
max_timesteps = 4e6
file_name = "mini_ars_"
# Find abs path to this file
my_path = os.path.abspath(os.path.dirname(__file__))
results_path = os.path.join(my_path, "../results")
models_path = os.path.join(my_path, "../models")
if not os.path.exists(results_path):
os.makedirs(results_path)
if not os.path.exists(models_path):
os.makedirs(models_path)
env = MinitaurBulletEnv(render=True)
# Set seeds
env.seed(seed)
torch.manual_seed(seed)
np.random.seed(seed)
state_dim = env.observation_space.shape[0]
print("STATE DIM: {}".format(state_dim))
action_dim = env.action_space.shape[0]
print("ACTION DIM: {}".format(action_dim))
max_action = float(env.action_space.high[0])
print("RECORDED MAX ACTION: {}".format(max_action))
# Initialize Normalizer
normalizer = Normalizer(state_dim)
# Initialize Policy
policy = Policy(state_dim, action_dim)
# Initialize Agent with normalizer, policy and gym env
agent = ARSAgent(normalizer, policy, env)
agent_num = raw_input("Policy Number: ")
if os.path.exists(models_path + "/" + file_name + str(agent_num) +
"_policy"):
print("Loading Existing agent")
agent.load(models_path + "/" + file_name + str(agent_num))
agent.policy.episode_steps = 3000
policy = agent.policy
# Evaluate untrained agent and init list for storage
evaluations = []
env.reset()
episode_reward = 0
episode_timesteps = 0
episode_num = 0
print("STARTED MINITAUR TEST SCRIPT")
t = 0
while t < (int(max_timesteps)):
# Maximum timesteps per rollout
t += policy.episode_steps
episode_timesteps += 1
episode_reward = agent.deploy()
# episode_reward = agent.train()
# +1 to account for 0 indexing.
# +0 on ep_timesteps since it will increment +1 even if done=True
print("Total T: {} Episode Num: {} Episode T: {} Reward: {}".format(
t, episode_num, policy.episode_steps, episode_reward))
# Reset environment
evaluations.append(episode_reward)
episode_reward = 0
episode_timesteps = 0
episode_num += 1
env.close()
if __name__ == '__main__':
main()
| 2,662 | Python | 25.63 | 76 | 0.622089 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/old_eval_scripts/spot_sac_eval.py | #!/usr/bin/env python
import numpy as np
from sac_lib import SoftActorCritic, NormalizedActions, ReplayBuffer, PolicyNetwork
import copy
from gym import spaces
import sys
sys.path.append('../../')
from spotmicro.GymEnvs.spot_bezier_env import spotBezierEnv
from spotmicro.Kinematics.SpotKinematics import SpotModel
from spotmicro.GaitGenerator.Bezier import BezierGait
# TESTING
from spotmicro.OpenLoopSM.SpotOL import BezierStepper
import time
import torch
import os
def main():
""" The main() function. """
print("STARTING SPOT SAC")
# TRAINING PARAMETERS
seed = 0
max_timesteps = 4e6
batch_size = 256
eval_freq = 1e4
save_model = True
file_name = "spot_sac_"
# Find abs path to this file
my_path = os.path.abspath(os.path.dirname(__file__))
results_path = os.path.join(my_path, "../results")
models_path = os.path.join(my_path, "../models")
if not os.path.exists(results_path):
os.makedirs(results_path)
if not os.path.exists(models_path):
os.makedirs(models_path)
env = spotBezierEnv(render=True,
on_rack=False,
height_field=False,
draw_foot_path=False)
env = NormalizedActions(env)
# Set seeds
env.seed(seed)
torch.manual_seed(seed)
np.random.seed(seed)
state_dim = env.observation_space.shape[0]
print("STATE DIM: {}".format(state_dim))
action_dim = env.action_space.shape[0]
print("ACTION DIM: {}".format(action_dim))
max_action = float(env.action_space.high[0])
print("RECORDED MAX ACTION: {}".format(max_action))
hidden_dim = 256
policy = PolicyNetwork(state_dim, action_dim, hidden_dim)
replay_buffer_size = 1000000
replay_buffer = ReplayBuffer(replay_buffer_size)
sac = SoftActorCritic(policy=policy,
state_dim=state_dim,
action_dim=action_dim,
replay_buffer=replay_buffer)
policy_num = raw_input("Policy Number: ")
if os.path.exists(models_path + "/" + file_name + str(policy_num) +
"_policy_net"):
print("Loading Existing Policy")
sac.load(models_path + "/" + file_name + str(policy_num))
policy = sac.policy_net
# Evaluate untrained policy and init list for storage
evaluations = []
state = env.reset()
done = False
episode_reward = 0
episode_timesteps = 0
episode_num = 0
max_t_per_ep = 5000
# State Machine for Random Controller Commands
bz_step = BezierStepper(dt=0.01, mode=0)
# Bezier Gait Generator
bzg = BezierGait(dt=0.01)
# Spot Model
spot = SpotModel()
T_bf0 = spot.WorldToFoot
T_bf = copy.deepcopy(T_bf0)
BaseClearanceHeight = bz_step.ClearanceHeight
BasePenetrationDepth = bz_step.PenetrationDepth
print("STARTED SPOT SAC")
for t in range(int(max_timesteps)):
contacts = state[-4:]
t += 1
episode_timesteps += 1
pos, orn, StepLength, LateralFraction, YawRate, StepVelocity, ClearanceHeight, PenetrationDepth = bz_step.StateMachine(
)
env.spot.GetExternalObservations(bzg, bz_step)
# Read UPDATED state based on controls and phase
state = env.return_state()
action = sac.policy_net.get_action(state)
# Bezier params specced by action
CD_SCALE = 0.002
SLV_SCALE = 0.01
StepLength += action[0] * CD_SCALE
StepVelocity += action[1] * SLV_SCALE
LateralFraction += action[2] * SLV_SCALE
YawRate = action[3]
ClearanceHeight += action[4] * CD_SCALE
PenetrationDepth += action[5] * CD_SCALE
# CLIP EVERYTHING
StepLength = np.clip(StepLength, bz_step.StepLength_LIMITS[0],
bz_step.StepLength_LIMITS[1])
StepVelocity = np.clip(StepVelocity, bz_step.StepVelocity_LIMITS[0],
bz_step.StepVelocity_LIMITS[1])
LateralFraction = np.clip(LateralFraction,
bz_step.LateralFraction_LIMITS[0],
bz_step.LateralFraction_LIMITS[1])
YawRate = np.clip(YawRate, bz_step.YawRate_LIMITS[0],
bz_step.YawRate_LIMITS[1])
ClearanceHeight = np.clip(ClearanceHeight,
bz_step.ClearanceHeight_LIMITS[0],
bz_step.ClearanceHeight_LIMITS[1])
PenetrationDepth = np.clip(PenetrationDepth,
bz_step.PenetrationDepth_LIMITS[0],
bz_step.PenetrationDepth_LIMITS[1])
contacts = state[-4:]
# Get Desired Foot Poses
T_bf = bzg.GenerateTrajectory(StepLength, LateralFraction, YawRate,
StepVelocity, T_bf0, T_bf,
ClearanceHeight, PenetrationDepth,
contacts)
# Add DELTA to XYZ Foot Poses
RESIDUALS_SCALE = 0.05
# T_bf["FL"][3, :3] += action[6:9] * RESIDUALS_SCALE
# T_bf["FR"][3, :3] += action[9:12] * RESIDUALS_SCALE
# T_bf["BL"][3, :3] += action[12:15] * RESIDUALS_SCALE
# T_bf["BR"][3, :3] += action[15:18] * RESIDUALS_SCALE
T_bf["FL"][3, 2] += action[6] * RESIDUALS_SCALE
T_bf["FR"][3, 2] += action[7] * RESIDUALS_SCALE
T_bf["BL"][3, 2] += action[8] * RESIDUALS_SCALE
T_bf["BR"][3, 2] += action[9] * RESIDUALS_SCALE
joint_angles = spot.IK(orn, pos, T_bf)
# Pass Joint Angles
env.pass_joint_angles(joint_angles.reshape(-1))
# Perform action
state, reward, done, _ = env.step(action)
episode_reward += reward
# print("DT REWARD: {}".format(reward))
if done:
# +1 to account for 0 indexing.
# +0 on ep_timesteps since it will increment +1 even if done=True
print(
"Total T: {} Episode Num: {} Episode T: {} Reward: {}".format(
t + 1, episode_num, episode_timesteps, episode_reward))
# Reset environment
state, done = env.reset(), False
evaluations.append(episode_reward)
episode_reward = 0
episode_timesteps = 0
episode_num += 1
env.close()
if __name__ == '__main__':
main() | 6,449 | Python | 31.089552 | 127 | 0.575748 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/old_eval_scripts/tg_eval.py | #!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
from ars_lib.ars import ARSAgent, Normalizer, Policy, ParallelWorker
from mini_bullet.minitaur_gym_env import MinitaurBulletEnv
from tg_lib.tg_policy import TGPolicy
import time
import torch
import os
def main():
""" The main() function. """
print("STARTING MINITAUR ARS")
# TRAINING PARAMETERS
# env_name = "MinitaurBulletEnv-v0"
seed = 0
max_timesteps = 1e6
file_name = "mini_tg_ars_"
# Find abs path to this file
my_path = os.path.abspath(os.path.dirname(__file__))
results_path = os.path.join(my_path, "../results")
models_path = os.path.join(my_path, "../models")
if not os.path.exists(results_path):
os.makedirs(results_path)
if not os.path.exists(models_path):
os.makedirs(models_path)
env = MinitaurBulletEnv(render=True, on_rack=False)
dt = env._time_step
# TRAJECTORY GENERATOR
movetype = "walk"
# movetype = "trot"
# movetype = "bound"
# movetype = "pace"
# movetype = "pronk"
TG = TGPolicy(movetype=movetype,
center_swing=0.0,
amplitude_extension=0.2,
amplitude_lift=0.4)
TG_state_dim = len(TG.get_TG_state())
TG_action_dim = 5 # f_tg, Beta, alpha_tg, h_tg, intensity
state_dim = env.observation_space.shape[0] + TG_state_dim
print("STATE DIM: {}".format(state_dim))
action_dim = env.action_space.shape[0] + TG_action_dim
print("ACTION DIM: {}".format(action_dim))
max_action = float(env.action_space.high[0])
print("RECORDED MAX ACTION: {}".format(max_action))
# Initialize Normalizer
normalizer = Normalizer(state_dim)
# Initialize Policy
policy = Policy(state_dim, action_dim)
# Initialize Agent with normalizer, policy and gym env
agent = ARSAgent(normalizer, policy, env, TGP=TG)
agent_num = raw_input("Policy Number: ")
if os.path.exists(models_path + "/" + file_name + str(agent_num) +
"_policy"):
print("Loading Existing agent")
agent.load(models_path + "/" + file_name + str(agent_num))
agent.policy.episode_steps = 1000
policy = agent.policy
# Set seeds
env.seed(seed)
torch.manual_seed(seed)
np.random.seed(seed)
env.reset()
episode_reward = 0
episode_timesteps = 0
episode_num = 0
print("STARTED MINITAUR TEST SCRIPT")
# Just to store correct action space
action = env.action_space.sample()
# Record extends for plot
# LF_ext = []
# LB_ext = []
# RF_ext = []
# RB_ext = []
LF_tp = []
LB_tp = []
RF_tp = []
RB_tp = []
t = 0
while t < (int(max_timesteps)):
action[:] = 0.0
# # Get Action from TG [no policies here]
# action = TG.get_utg(action, alpha_tg, h_tg, intensity,
# env.minitaur.num_motors)
# LF_ext.append(action[env.minitaur.num_motors / 2])
# LB_ext.append(action[1 + env.minitaur.num_motors / 2])
# RF_ext.append(action[2 + env.minitaur.num_motors / 2])
# RB_ext.append(action[3 + env.minitaur.num_motors / 2])
# # Perform action
# next_state, reward, done, _ = env.step(action)
obs = agent.TGP.get_TG_state()
# LF_tp.append(obs[0])
# LB_tp.append(obs[1])
# RF_tp.append(obs[2])
# RB_tp.append(obs[3])
# # Increment phase
# TG.increment(dt, f_tg, Beta)
# # time.sleep(1.0)
# t += 1
# Maximum timesteps per rollout
t += policy.episode_steps
episode_timesteps += 1
episode_reward = agent.deployTG()
# episode_reward = agent.train()
# +1 to account for 0 indexing.
# +0 on ep_timesteps since it will increment +1 even if done=True
print("Total T: {} Episode Num: {} Episode T: {} Reward: {}".format(
t, episode_num, policy.episode_steps, episode_reward))
# Reset environment
episode_reward = 0
episode_timesteps = 0
episode_num += 1
plt.plot(0)
plt.plot(LF_tp, label="LF")
plt.plot(LB_tp, label="LB")
plt.plot(RF_tp, label="RF")
plt.plot(RB_tp, label="RB")
plt.xlabel("t")
plt.ylabel("EXT")
plt.title("Leg Extensions")
plt.legend()
plt.show()
env.close()
if __name__ == '__main__':
main()
| 4,424 | Python | 25.981707 | 76 | 0.583635 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/td3_lib/td3.py | #!/usr/bin/env python
import copy
import pickle
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import gym
import os
# Twin Delayed Deterministic Policy Gradient
# Algorithm Steps
# 1. Initiailize Networks
class Actor(nn.Module):
"""Initialize parameters and build model.
An nn.Module contains layers, and a method
forward(input)that returns the output.
Weights (learnable params) are inherently defined here.
Args:
state_dim (int): Dimension of each state
action_dim (int): Dimension of each action
max_action (float): highest action to take
Return:
action output of network with tanh activation
"""
def __init__(self, state_dim, action_dim, max_action):
# Super calls the nn.Module Constructor
super(Actor, self).__init__()
# input layer
self.fc1 = nn.Linear(state_dim, 256)
# hidden layer
self.fc2 = nn.Linear(256, 256)
# output layer
self.fc3 = nn.Linear(256, action_dim)
# wrap from -max to +max
self.max_action = max_action
def forward(self, state):
# You just have to define the forward function,
# and the backward function (where gradients are computed)
# is automatically defined for you using autograd.
# Learnable params can be accessed using Actor.parameters
# Here, we create the tensor architecture
# state into layer 1
a = F.relu(self.fc1(state))
# layer 1 output into layer 2
a = F.relu(self.fc2(a))
# layer 2 output into layer 3 into tanh activation
return self.max_action * torch.tanh(self.fc3(a))
class Critic(nn.Module):
"""Initialize parameters and build model.
Args:
state_dim (int): Dimension of each state
action_dim (int): Dimension of each action
Return:
value output of network
"""
def __init__(self, state_dim, action_dim):
# Super calls the nn.Module Constructor
super(Critic, self).__init__()
# Q1 architecture
self.fc1 = nn.Linear(state_dim + action_dim, 256)
self.fc2 = nn.Linear(256, 256)
self.fc3 = nn.Linear(256, 1)
# Q2 architecture
self.fc4 = nn.Linear(state_dim + action_dim, 256)
self.fc5 = nn.Linear(256, 256)
self.fc6 = nn.Linear(256, 1)
def forward(self, state, action):
# concatenate state and actions by adding rows
# to form 1D input layer
sa = torch.cat([state, action], 1)
# s,a into input layer into relu activation
q1 = F.relu(self.fc1(sa))
# l1 output into l2 into relu activation
q1 = F.relu(self.fc2(q1))
# l2 output into l3
q1 = self.fc3(q1)
# s,a into input layer into relu activation
q2 = F.relu(self.fc4(sa))
# l4 output into l5 into relu activation
q2 = F.relu(self.fc5(q2))
# l5 output into l6
q2 = self.fc6(q2)
return q1, q2
def Q1(self, state, action):
# Return Q1 for gradient Ascent on Actor
# Note that only Q1 is used for Actor Update
# concatenate state and actions by adding rows
# to form 1D input layer
sa = torch.cat([state, action], 1)
# s,a into input layer into relu activation
q1 = F.relu(self.fc1(sa))
# l1 output into l2 into relu activation
q1 = F.relu(self.fc2(q1))
# l2 output into l3
q1 = self.fc3(q1)
return q1
# https://github.com/openai/baselines/blob/master/baselines/deepq/replay_buffer.py
# Expects tuples of (state, next_state, action, reward, done)
class ReplayBuffer(object):
"""Buffer to store tuples of experience replay"""
def __init__(self, max_size=1000000):
"""
Args:
max_size (int): total amount of tuples to store
"""
self.storage = []
self.max_size = max_size
self.ptr = 0
my_path = os.path.abspath(os.path.dirname(__file__))
self.buffer_path = os.path.join(my_path, "../../replay_buffer")
def add(self, data):
"""Add experience tuples to buffer
Args:
data (tuple): experience replay tuple
"""
if len(self.storage) == self.max_size:
self.storage[int(self.ptr)] = data
self.ptr = (self.ptr + 1) % self.max_size
else:
self.storage.append(data)
def save(self, iterations):
if not os.path.exists(self.buffer_path):
os.makedirs(self.buffer_path)
with open(
self.buffer_path + '/' + 'replay_buffer_' + str(iterations) +
'.data', 'wb') as filehandle:
pickle.dump(self.storage, filehandle)
def load(self, iterations):
with open(
self.buffer_path + '/' + 'replay_buffer_' + str(iterations) +
'.data', 'rb') as filehandle:
self.storage = pickle.load(filehandle)
def sample(self, batch_size):
"""Samples a random amount of experiences from buffer of batch size
NOTE: We don't delete samples here, only overwrite when max_size
Args:
batch_size (int): size of sample
"""
device = torch.device("cuda:1" if torch.cuda.is_available() else "cpu")
ind = np.random.randint(0, len(self.storage), size=batch_size)
states, actions, next_states, rewards, dones = [], [], [], [], []
for i in ind:
s, a, s_, r, d = self.storage[i]
states.append(np.array(s, copy=False))
state = torch.FloatTensor(np.array(states)).to(device)
actions.append(np.array(a, copy=False))
action = torch.FloatTensor(np.array(actions)).to(device)
next_states.append(np.array(s_, copy=False))
next_state = torch.FloatTensor(np.array(next_states)).to(device)
rewards.append(np.array(r, copy=False))
reward = torch.FloatTensor(np.array(rewards).reshape(-1,
1)).to(device)
dones.append(np.array(d, copy=False))
not_done = torch.FloatTensor(
1. - (np.array(dones).reshape(-1, 1))).to(device)
return state, action, next_state, reward, not_done
class TD3Agent(object):
"""Agent class that handles the training of the networks and
provides outputs as actions
Args:
state_dim (int): state size
action_dim (int): action size
max_action (float): highest action to take
device (device): cuda or cpu to process tensors
env (env): gym environment to use
batch_size(int): batch size to sample from replay buffer
discount (float): discount factor
tau (float): soft update for main networks to target networks
"""
def __init__(self,
state_dim,
action_dim,
max_action,
discount=0.99,
tau=0.005,
policy_noise=0.2,
noise_clip=0.5,
policy_freq=2):
self.device = torch.device(
"cuda:1" if torch.cuda.is_available() else "cpu")
self.actor = Actor(state_dim, action_dim, max_action).to(self.device)
self.actor_target = copy.deepcopy(self.actor)
self.actor_optimizer = torch.optim.Adam(self.actor.parameters(),
lr=3e-4)
self.critic = Critic(state_dim, action_dim).to(self.device)
self.critic_target = copy.deepcopy(self.critic)
self.critic_optimizer = torch.optim.Adam(self.critic.parameters(),
lr=3e-4)
self.max_action = max_action
self.discount = discount
self.tau = tau
self.policy_noise = policy_noise
self.noise_clip = noise_clip
self.policy_freq = policy_freq
self.total_it = 0
def select_action(self, state):
"""Select an appropriate action from the agent policy
Args:
state (array): current state of environment
Returns:
action (float): action clipped within action range
"""
# Turn float value into a CUDA Float Tensor
state = torch.FloatTensor(state.reshape(1, -1)).to(self.device)
action = self.actor(state).cpu().data.numpy().flatten()
return action
def train(self, replay_buffer, batch_size=100):
"""Train and update actor and critic networks
Args:
replay_buffer (ReplayBuffer): buffer for experience replay
batch_size(int): batch size to sample from replay buffer\
Return:
actor_loss (float): loss from actor network
critic_loss (float): loss from critic network
"""
self.total_it += 1
# Sample replay buffer
state, action, next_state, reward, not_done = replay_buffer.sample(
batch_size)
with torch.no_grad():
"""
Autograd: if you set its attribute .requires_gras as True,
(DEFAULT)
it tracks all operations on it. When you finish your
computation, call .backward() to have all gradients computed
automatically. The gradient for this tensor is then accumulated
into the .grad attribute.
To prevent tracking history and using memory, wrap the code block
in "with torch.no_grad()". This is heplful when evaluating a model
as it may have trainable params with requires_grad=True (DEFAULT),
but for which we don't need the gradients.
Here, we don't want to track the acyclic graph's history
when getting our next action because we DON'T want to train
our actor in this step. We train our actor ONLY when we perform
the periodic policy update. Could have done .detach() at
target_Q = reward + not_done * self.discount * target_Q
for the same effect
"""
# Select action according to policy and add clipped noise
noise = (torch.randn_like(action) * self.policy_noise).clamp(
-self.noise_clip, self.noise_clip)
next_action = (self.actor_target(next_state) + noise).clamp(
-self.max_action, self.max_action)
# Compute the target Q value
target_Q1, target_Q2 = self.critic_target(next_state, next_action)
target_Q = torch.min(target_Q1, target_Q2)
target_Q = reward + not_done * self.discount * target_Q
# Get current Q estimates
current_Q1, current_Q2 = self.critic(state, action)
# Compute critic loss
# A loss function takes the (output, target) pair of inputs,
# and computes a value that estimates how far away the output
# is from the target.
critic_loss = F.mse_loss(current_Q1, target_Q) + F.mse_loss(
current_Q2, target_Q)
# Optimize the critic
# Zero the gradient buffers of all parameters
self.critic_optimizer.zero_grad()
# Backprops with random gradients
# When we call loss.backward(), the whole graph is differentiated
# w.r.t. the loss, and all Tensors in the graph that has
# requires_grad=True (DEFAULT) will have their .grad Tensor
# accumulated with the gradient.
critic_loss.backward()
# Does the update
self.critic_optimizer.step()
# Delayed policy updates
if self.total_it % self.policy_freq == 0:
# Compute actor losse
actor_loss = -self.critic.Q1(state, self.actor(state)).mean()
# Optimize the actor
# Zero the gradient buffers
self.actor_optimizer.zero_grad()
# Differentiate the whole graph wrt loss
actor_loss.backward()
# Does the update
self.actor_optimizer.step()
# Update target networks (Critic 1, Critic 2, Actor)
for param, target_param in zip(self.critic.parameters(),
self.critic_target.parameters()):
target_param.data.copy_(self.tau * param.data +
(1 - self.tau) * target_param.data)
for param, target_param in zip(self.actor.parameters(),
self.actor_target.parameters()):
target_param.data.copy_(self.tau * param.data +
(1 - self.tau) * target_param.data)
def save(self, filename):
torch.save(self.critic.state_dict(), filename + "_critic")
torch.save(self.critic_optimizer.state_dict(),
filename + "_critic_optimizer")
torch.save(self.actor.state_dict(), filename + "_actor")
torch.save(self.actor_optimizer.state_dict(),
filename + "_actor_optimizer")
def load(self, filename):
self.critic.load_state_dict(
torch.load(filename + "_critic", map_location=self.device))
self.critic_optimizer.load_state_dict(
torch.load(filename + "_critic_optimizer",
map_location=self.device))
self.actor.load_state_dict(
torch.load(filename + "_actor", map_location=self.device))
self.actor_optimizer.load_state_dict(
torch.load(filename + "_actor_optimizer",
map_location=self.device))
# Runs policy for X episodes and returns average reward
# A fixed seed is used for the eval environment
def evaluate_policy(policy, env_name, seed, eval_episodes=10, render=False):
"""run several episodes using the best agent policy
Args:
policy (agent): agent to evaluate
env (env): gym environment
eval_episodes (int): how many test episodes to run
render (bool): show training
Returns:
avg_reward (float): average reward over the number of evaluations
"""
eval_env = gym.make(env_name, render=render)
eval_env.seed(seed + 100)
avg_reward = 0.
for _ in range(eval_episodes):
state, done = eval_env.reset(), False
while not done:
# if render:
# eval_env.render()
# sleep(0.01)
action = policy.select_action(np.array(state))
state, reward, done, _ = eval_env.step(action)
avg_reward += reward
avg_reward /= eval_episodes
print("---------------------------------------")
print("Evaluation over {} episodes: {}".format(eval_episodes, avg_reward))
print("---------------------------------------")
if render:
eval_env.close()
return avg_reward
def trainer(env_name,
seed,
max_timesteps,
start_timesteps,
expl_noise,
batch_size,
eval_freq,
save_model,
file_name="best_avg"):
""" Test Script on stock OpenAI Gym Envs
"""
if not os.path.exists("../results"):
os.makedirs("../results")
if not os.path.exists("../models"):
os.makedirs("../models")
env = gym.make(env_name)
# Set seeds
env.seed(seed)
torch.manual_seed(seed)
np.random.seed(seed)
state_dim = env.observation_space.shape[0]
action_dim = env.action_space.shape[0]
max_action = float(env.action_space.high[0])
policy = TD3Agent(state_dim, action_dim, max_action)
replay_buffer = ReplayBuffer()
# Evaluate untrained policy and init list for storage
evaluations = [evaluate_policy(policy, env_name, seed, 1)]
state = env.reset()
done = False
episode_reward = 0
episode_timesteps = 0
episode_num = 0
for t in range(int(max_timesteps)):
episode_timesteps += 1
# Select action randomly or according to policy
# Random Action - no training yet, just storing in buffer
if t < start_timesteps:
action = env.action_space.sample()
else:
# According to policy + Exploraton Noise
action = (policy.select_action(np.array(state)) + np.random.normal(
0, max_action * expl_noise, size=action_dim)).clip(
-max_action, max_action)
# Perform action
next_state, reward, done, _ = env.step(action)
done_bool = float(
done) if episode_timesteps < env._max_episode_steps else 0
# Store data in replay buffer
replay_buffer.add((state, action, next_state, reward, done_bool))
state = next_state
episode_reward += reward
# Train agent after collecting sufficient data for buffer
if t >= start_timesteps:
policy.train(replay_buffer, batch_size)
if done:
# +1 to account for 0 indexing.
# +0 on ep_timesteps since it will increment +1 even if done=True
print(
"Total T: {} Episode Num: {} Episode T: {} Reward: {}".format(
t + 1, episode_num, episode_timesteps, episode_reward))
# Reset environment
state, done = env.reset(), False
episode_reward = 0
episode_timesteps = 0
episode_num += 1
# Evaluate episode
if (t + 1) % eval_freq == 0:
evaluations.append(evaluate_policy(policy, env_name, seed, 1))
np.save("../results/" + str(file_name) + str(t), evaluations)
if save_model:
policy.save("../models/" + str(file_name) + str(t))
if __name__ == "__main__":
""" The Main Function """
trainer("BipedalWalker-v2", 0, 1e6, 1e4, 0.1, 100, 15e3, True) | 18,049 | Python | 34.392157 | 82 | 0.57017 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/td3_lib/plot_reward.py | #!/usr/bin/env python
import matplotlib.pyplot as plt
import numpy as np
if __name__ == '__main__':
reward = np.load("../../results/plen_walk_gazebo_.npy")
plt.figure(0)
plt.autoscale(enable=True, axis='both', tight=None)
plt.title('Dominant Foot Trajectories - SS')
plt.ylabel('positon (mm)')
plt.xlabel('timestep')
plt.plot(reward, color='b', label="Reward")
plt.legend()
plt.show()
| 426 | Python | 21.473683 | 59 | 0.626761 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/ars_lib/ars.py | # from tg_lib.tg_policy import TGPolicy
import pickle
import numpy as np
from scipy.signal import butter, filtfilt
from spotmicro.GaitGenerator.Bezier import BezierGait
from spotmicro.OpenLoopSM.SpotOL import BezierStepper
from spotmicro.Kinematics.SpotKinematics import SpotModel
from spotmicro.Kinematics.LieAlgebra import TransToRp
import copy
from spotmicro.util.gui import GUI
np.random.seed(0)
# Multiprocessing package for python
# Parallelization improvements based on:
# https://github.com/bulletphysics/bullet3/blob/master/examples/pybullet/gym/pybullet_envs/ARS/ars.py
# Messages for Pipes
_RESET = 1
_CLOSE = 2
_EXPLORE = 3
_EXPLORE_TG = 4
# Params for TG
CD_SCALE = 0.05
SLV_SCALE = 0.05
RESIDUALS_SCALE = 0.015
Z_SCALE = 0.05
# Filter actions
alpha = 0.7
# Added this to avoid filtering residuals
# -1 for all
actions_to_filter = 14
# For auto yaw control
P_yaw = 5.0
# Cummulative timestep exponential reward
# cum_dt_exp = 1.1
cum_dt_exp = 0.0
def butter_lowpass_filter(data, cutoff, fs, order=2):
""" Pass two subsequent datapoints in here to be filtered
"""
nyq = 0.5 * fs # Nyquist Frequency
normal_cutoff = cutoff / nyq
# Get the filter coefficients
b, a = butter(order, normal_cutoff, btype='low', analog=False)
y = filtfilt(b, a, data)
return y
def ParallelWorker(childPipe, env, nb_states):
""" Function to deploy multiple ARS agents in parallel
"""
# nb_states = env.observation_space.shape[0]
# common normalizer
normalizer = Normalizer(nb_states)
max_action = float(env.action_space.high[0])
_ = env.reset()
n = 0
while True:
n += 1
try:
# Only block for short times to have keyboard exceptions be raised.
if not childPipe.poll(0.001):
continue
message, payload = childPipe.recv()
except (EOFError, KeyboardInterrupt):
break
if message == _RESET:
_ = env.reset()
childPipe.send(["reset ok"])
continue
if message == _EXPLORE:
# Payloads received by parent in ARSAgent.train()
# [0]: normalizer, [1]: policy, [2]: direction, [3]: delta
# we use local normalizer so no need for [0] (optional)
# normalizer = payload[0]
policy = payload[1]
direction = payload[2]
delta = payload[3]
desired_velocity = payload[4]
desired_rate = payload[5]
state = env.reset(desired_velocity, desired_rate)
sum_rewards = 0.0
timesteps = 0
done = False
while not done and timesteps < policy.episode_steps:
normalizer.observe(state)
# Normalize State
state = normalizer.normalize(state)
action = policy.evaluate(state, delta, direction)
# # Clip action between +-1 for execution in env
# for a in range(len(action)):
# action[a] = np.clip(action[a], -max_action, max_action)
state, reward, done, _ = env.step(action)
reward = max(min(reward, 1), -1)
sum_rewards += reward
timesteps += 1
childPipe.send([sum_rewards])
continue
if message == _EXPLORE_TG:
# Payloads received by parent in ARSAgent.train()
# [0]: normalizer, [1]: policy, [2]: direction, [3]: delta
# [4]: desired_velocity, [5]: desired_rate, [6]: Trajectory Gen
# we use local normalizer so no need for [0] (optional)
# normalizer = payload[0]
policy = payload[1]
direction = payload[2]
delta = payload[3]
desired_velocity = payload[4]
desired_rate = payload[5]
TGP = payload[6]
smach = payload[7]
spot = payload[8]
state = env.reset()
sum_rewards = 0.0
timesteps = 0
done = False
T_bf = copy.deepcopy(spot.WorldToFoot)
T_b0 = copy.deepcopy(spot.WorldToFoot)
action = env.action_space.sample()
action[:] = 0.0
old_act = action[:actions_to_filter]
# For auto yaw control
yaw = 0.0
while not done and timesteps < policy.episode_steps:
# smach.ramp_up()
pos, orn, StepLength, LateralFraction, YawRate, StepVelocity, ClearanceHeight, PenetrationDepth = smach.StateMachine(
)
env.spot.GetExternalObservations(TGP, smach)
# Read UPDATED state based on controls and phase
state = env.return_state()
normalizer.observe(state)
# NOTE: Don't normalize contacts - must stay 0/1
state = normalizer.normalize(state)
action = policy.evaluate(state, delta, direction)
contacts = state[-4:]
action = np.tanh(action)
# EXP FILTER
action[:actions_to_filter] = alpha * old_act + (
1.0 - alpha) * action[:actions_to_filter]
old_act = action[:actions_to_filter]
ClearanceHeight += action[0] * CD_SCALE
# CLIP EVERYTHING
StepLength = np.clip(StepLength, smach.StepLength_LIMITS[0],
smach.StepLength_LIMITS[1])
StepVelocity = np.clip(StepVelocity,
smach.StepVelocity_LIMITS[0],
smach.StepVelocity_LIMITS[1])
LateralFraction = np.clip(LateralFraction,
smach.LateralFraction_LIMITS[0],
smach.LateralFraction_LIMITS[1])
YawRate = np.clip(YawRate, smach.YawRate_LIMITS[0],
smach.YawRate_LIMITS[1])
ClearanceHeight = np.clip(ClearanceHeight,
smach.ClearanceHeight_LIMITS[0],
smach.ClearanceHeight_LIMITS[1])
PenetrationDepth = np.clip(PenetrationDepth,
smach.PenetrationDepth_LIMITS[0],
smach.PenetrationDepth_LIMITS[1])
# For auto yaw control
yaw = env.return_yaw()
YawRate += -yaw * P_yaw
# Get Desired Foot Poses
if timesteps > 20:
T_bf = TGP.GenerateTrajectory(StepLength, LateralFraction,
YawRate, StepVelocity, T_b0,
T_bf, ClearanceHeight,
PenetrationDepth, contacts)
else:
T_bf = TGP.GenerateTrajectory(0.0, 0.0, 0.0, 0.1, T_b0,
T_bf, ClearanceHeight,
PenetrationDepth, contacts)
action[:] = 0.0
action[2:] *= RESIDUALS_SCALE
# Add DELTA to XYZ Foot Poses
T_bf_copy = copy.deepcopy(T_bf)
T_bf_copy["FL"][:3, 3] += action[2:5]
T_bf_copy["FR"][:3, 3] += action[5:8]
T_bf_copy["BL"][:3, 3] += action[8:11]
T_bf_copy["BR"][:3, 3] += action[11:14]
# Adjust Body Height with action!
pos[2] += abs(action[1]) * Z_SCALE
joint_angles = spot.IK(orn, pos, T_bf_copy)
# Pass Joint Angles
env.pass_joint_angles(joint_angles.reshape(-1))
# Perform action
next_state, reward, done, _ = env.step(action)
sum_rewards += reward
timesteps += 1
# Divide reward by timesteps for normalized reward + add exponential surival reward
childPipe.send([(sum_rewards + timesteps**cum_dt_exp) / timesteps])
continue
if message == _CLOSE:
childPipe.send(["close ok"])
break
childPipe.close()
class Policy():
""" state --> action
"""
def __init__(
self,
state_dim,
action_dim,
# how much weights are changed each step
learning_rate=0.03,
# number of random expl_noise variations generated
# each step
# each one will be run for 2 epochs, + and -
num_deltas=16,
# used to update weights, sorted by highest rwrd
num_best_deltas=16,
# number of timesteps per episode per rollout
episode_steps=5000,
# weight of sampled exploration noise
expl_noise=0.05,
# for seed gen
seed=0):
# Tunable Hyperparameters
self.learning_rate = learning_rate
self.num_deltas = num_deltas
self.num_best_deltas = num_best_deltas
# there cannot be more best_deltas than there are deltas
assert self.num_best_deltas <= self.num_deltas
self.episode_steps = episode_steps
self.expl_noise = expl_noise
self.seed = seed
np.random.seed(seed)
self.state_dim = state_dim
self.action_dim = action_dim
# input/ouput matrix with weights set to zero
# this is the perception matrix (policy)
self.theta = np.zeros((action_dim, state_dim))
def evaluate(self, state, delta=None, direction=None):
""" state --> action
"""
# if direction is None, deployment mode: takes dot product
# to directly sample from (use) policy
if direction is None:
return self.theta.dot(state)
# otherwise, add (+-) directed expl_noise before taking dot product (policy)
# this is where the 2*num_deltas rollouts comes from
elif direction == "+":
return (self.theta + self.expl_noise * delta).dot(state)
elif direction == "-":
return (self.theta - self.expl_noise * delta).dot(state)
def sample_deltas(self):
""" generate array of random expl_noise matrices. Length of
array = num_deltas
matrix dimension: pxn where p=observation dim and
n=action dim
"""
deltas = []
# print("SHAPE THING with *: {}".format(*self.theta.shape))
# print("SHAPE THING NORMALLY: ({}, {})".format(self.theta.shape[0],
# self.theta.shape[1]))
# print("ACTUAL SHAPE: {}".format(self.theta.shape))
# print("SHAPE OF EXAMPLE DELTA WITH *: {}".format(
# np.random.randn(*self.theta.shape).shape))
# print("SHAPE OF EXAMPLE DELTA NOMRALLY: {}".format(
# np.random.randn(self.theta.shape[0], self.theta.shape[1]).shape))
for _ in range(self.num_deltas):
deltas.append(
np.random.randn(self.theta.shape[0], self.theta.shape[1]))
return deltas
def update(self, rollouts, std_dev_rewards):
""" Update policy weights (theta) based on rewards
from 2*num_deltas rollouts
"""
step = np.zeros(self.theta.shape)
for r_pos, r_neg, delta in rollouts:
# how much to deviate from policy
step += (r_pos - r_neg) * delta
self.theta += self.learning_rate / (self.num_best_deltas *
std_dev_rewards) * step
class Normalizer():
""" this ensures that the policy puts equal weight upon
each state component.
"""
# Normalizes the states
def __init__(self, state_dim):
""" Initialize state space (all zero)
"""
self.state = np.zeros(state_dim)
self.mean = np.zeros(state_dim)
self.mean_diff = np.zeros(state_dim)
self.var = np.zeros(state_dim)
def observe(self, x):
""" Compute running average and variance
clip variance >0 to avoid division by zero
"""
self.state += 1.0
last_mean = self.mean.copy()
# running avg
self.mean += (x - self.mean) / self.state
# used to compute variance
self.mean_diff += (x - last_mean) * (x - self.mean)
# variance
self.var = (self.mean_diff / self.state).clip(min=1e-2)
def normalize(self, states):
""" subtract mean state value from current state
and divide by standard deviation (sqrt(var))
to normalize
"""
state_mean = self.mean
state_std = np.sqrt(self.var)
return (states - state_mean) / state_std
class ARSAgent():
def __init__(self,
normalizer,
policy,
env,
smach=None,
TGP=None,
spot=None,
gui=False):
self.normalizer = normalizer
self.policy = policy
self.state_dim = self.policy.state_dim
self.action_dim = self.policy.action_dim
self.env = env
self.max_action = float(self.env.action_space.high[0])
self.successes = 0
self.phase = 0
self.desired_velocity = 0.5
self.desired_rate = 0.0
self.flip = 0
self.increment = 0
self.scaledown = True
self.type = "Stop"
self.smach = smach
if smach is not None:
self.BaseClearanceHeight = self.smach.ClearanceHeight
self.BasePenetrationDepth = self.smach.PenetrationDepth
self.TGP = TGP
self.spot = spot
if gui:
self.g_u_i = GUI(self.env.spot.quadruped)
else:
self.g_u_i = None
self.action_history = []
self.true_action_history = []
# Deploy Policy in one direction over one whole episode
# DO THIS ONCE PER ROLLOUT OR DURING DEPLOYMENT
def deploy(self, direction=None, delta=None):
state = self.env.reset(self.desired_velocity, self.desired_rate)
sum_rewards = 0.0
timesteps = 0
done = False
while not done and timesteps < self.policy.episode_steps:
# print("STATE: ", state)
# print("dt: {}".format(timesteps))
self.normalizer.observe(state)
# Normalize State
state = self.normalizer.normalize(state)
action = self.policy.evaluate(state, delta, direction)
# Clip action between +-1 for execution in env
for a in range(len(action)):
action[a] = np.clip(action[a], -self.max_action,
self.max_action)
# print("ACTION: ", action)
state, reward, done, _ = self.env.step(action)
# print("STATE: ", state)
# Clip reward between -1 and 1 to prevent outliers from
# distorting weights
reward = np.clip(reward, -self.max_action, self.max_action)
sum_rewards += reward
timesteps += 1
# Divide rewards by timesteps for reward-per-step + exp survive rwd
return (sum_rewards + timesteps**cum_dt_exp) / timesteps
# Deploy Policy in one direction over one whole episode
# DO THIS ONCE PER ROLLOUT OR DURING DEPLOYMENT
def deployTG(self, direction=None, delta=None):
state = self.env.reset()
sum_rewards = 0.0
timesteps = 0
done = False
# alpha = []
# h = []
# f = []
T_bf = copy.deepcopy(self.spot.WorldToFoot)
T_b0 = copy.deepcopy(self.spot.WorldToFoot)
self.action_history = []
self.true_action_history = []
action = self.env.action_space.sample()
action[:] = 0.0
old_act = action[:actions_to_filter]
# For auto yaw correction
yaw = 0.0
while not done and timesteps < self.policy.episode_steps:
# self.smach.ramp_up()
pos, orn, StepLength, LateralFraction, YawRate, StepVelocity, ClearanceHeight, PenetrationDepth = self.smach.StateMachine(
)
if self.g_u_i:
pos, orn, StepLength, LateralFraction, YawRate, StepVelocity, ClearanceHeight, PenetrationDepth, SwingPeriod = self.g_u_i.UserInput(
)
self.TGP.Tswing = SwingPeriod
self.env.spot.GetExternalObservations(self.TGP, self.smach)
# Read UPDATED state based on controls and phase
state = self.env.return_state()
self.normalizer.observe(state)
# Don't normalize contacts
state = self.normalizer.normalize(state)
action = self.policy.evaluate(state, delta, direction)
# Action History
self.action_history.append(np.tanh(action))
# Action History
true_action = copy.deepcopy(np.tanh(action))
true_action[0] *= CD_SCALE
true_action[1] = abs(true_action[1]) * Z_SCALE
true_action[2:] *= RESIDUALS_SCALE
self.true_action_history.append(true_action)
action = np.tanh(action)
# EXP FILTER
action[:actions_to_filter] = alpha * old_act + (
1.0 - alpha) * action[:actions_to_filter]
old_act = action[:actions_to_filter]
ClearanceHeight += action[0] * CD_SCALE
# CLIP EVERYTHING
StepLength = np.clip(StepLength, self.smach.StepLength_LIMITS[0],
self.smach.StepLength_LIMITS[1])
StepVelocity = np.clip(StepVelocity,
self.smach.StepVelocity_LIMITS[0],
self.smach.StepVelocity_LIMITS[1])
LateralFraction = np.clip(LateralFraction,
self.smach.LateralFraction_LIMITS[0],
self.smach.LateralFraction_LIMITS[1])
YawRate = np.clip(YawRate, self.smach.YawRate_LIMITS[0],
self.smach.YawRate_LIMITS[1])
ClearanceHeight = np.clip(ClearanceHeight,
self.smach.ClearanceHeight_LIMITS[0],
self.smach.ClearanceHeight_LIMITS[1])
PenetrationDepth = np.clip(PenetrationDepth,
self.smach.PenetrationDepth_LIMITS[0],
self.smach.PenetrationDepth_LIMITS[1])
contacts = copy.deepcopy(state[-4:])
# contacts = [0, 0, 0, 0]
# print("CONTACTS: {}".format(contacts))
yaw = self.env.return_yaw()
if not self.g_u_i:
YawRate += -yaw * P_yaw
# Get Desired Foot Poses
if timesteps > 20:
T_bf = self.TGP.GenerateTrajectory(StepLength, LateralFraction,
YawRate, StepVelocity, T_b0,
T_bf, ClearanceHeight,
PenetrationDepth, contacts)
else:
T_bf = self.TGP.GenerateTrajectory(0.0, 0.0, 0.0, 0.1, T_b0,
T_bf, ClearanceHeight,
PenetrationDepth, contacts)
action[:] = 0.0
action[2:] *= RESIDUALS_SCALE
# Add DELTA to XYZ Foot Poses
T_bf_copy = copy.deepcopy(T_bf)
T_bf_copy["FL"][:3, 3] += action[2:5]
T_bf_copy["FR"][:3, 3] += action[5:8]
T_bf_copy["BL"][:3, 3] += action[8:11]
T_bf_copy["BR"][:3, 3] += action[11:14]
# Adjust Height!
pos[2] += abs(action[1]) * Z_SCALE
joint_angles = self.spot.IK(orn, pos, T_bf_copy)
# Pass Joint Angles
self.env.pass_joint_angles(joint_angles.reshape(-1))
# Perform action
next_state, reward, done, _ = self.env.step(action)
sum_rewards += reward
timesteps += 1
self.TGP.reset()
self.smach.reshuffle()
self.smach.PenetrationDepth = self.BasePenetrationDepth
self.smach.ClearanceHeight = self.BaseClearanceHeight
return sum_rewards, timesteps
def returnPose(self):
return self.env.spot.GetBasePosition()
def train(self):
# Sample random expl_noise deltas
print("-------------------------------")
# print("Sampling Deltas")
deltas = self.policy.sample_deltas()
# Initialize +- reward list of size num_deltas
positive_rewards = [0] * self.policy.num_deltas
negative_rewards = [0] * self.policy.num_deltas
# Execute 2*num_deltas rollouts and store +- rewards
print("Deploying Rollouts")
for i in range(self.policy.num_deltas):
print("Rollout #{}".format(i + 1))
positive_rewards[i] = self.deploy(direction="+", delta=deltas[i])
negative_rewards[i] = self.deploy(direction="-", delta=deltas[i])
# Calculate std dev
std_dev_rewards = np.array(positive_rewards + negative_rewards).std()
# Order rollouts in decreasing list using cum reward as criterion
unsorted_rollouts = [(positive_rewards[i], negative_rewards[i],
deltas[i])
for i in range(self.policy.num_deltas)]
# When sorting, take the max between the reward for +- disturbance
sorted_rollouts = sorted(
unsorted_rollouts,
key=lambda x: max(unsorted_rollouts[0], unsorted_rollouts[1]),
reverse=True)
# Only take first best_num_deltas rollouts
rollouts = sorted_rollouts[:self.policy.num_best_deltas]
# Update Policy
self.policy.update(rollouts, std_dev_rewards)
# Execute Current Policy
eval_reward = self.deploy()
return eval_reward
def train_parallel(self, parentPipes):
""" Execute rollouts in parallel using multiprocessing library
based on: # https://github.com/bulletphysics/bullet3/blob/master/examples/pybullet/gym/pybullet_envs/ARS/ars.py
"""
# USE VANILLA OR TG POLICY
if self.TGP is None:
exploration = _EXPLORE
else:
exploration = _EXPLORE_TG
# Initializing the perturbations deltas and the positive/negative rewards
deltas = self.policy.sample_deltas()
# Initialize +- reward list of size num_deltas
positive_rewards = [0] * self.policy.num_deltas
negative_rewards = [0] * self.policy.num_deltas
smach = copy.deepcopy(self.smach)
smach.ClearanceHeight = self.BaseClearanceHeight
smach.PenetrationDepth = self.BasePenetrationDepth
smach.reshuffle()
if parentPipes:
for i in range(self.policy.num_deltas):
# Execute each rollout on a separate thread
parentPipe = parentPipes[i]
# NOTE: target for parentPipe specified in main_ars.py
# (target is ParallelWorker fcn defined up top)
parentPipe.send([
exploration,
[
self.normalizer, self.policy, "+", deltas[i],
self.desired_velocity, self.desired_rate, self.TGP,
smach, self.spot
]
])
for i in range(self.policy.num_deltas):
# Receive cummulative reward from each rollout
positive_rewards[i] = parentPipes[i].recv()[0]
for i in range(self.policy.num_deltas):
# Execute each rollout on a separate thread
parentPipe = parentPipes[i]
parentPipe.send([
exploration,
[
self.normalizer, self.policy, "-", deltas[i],
self.desired_velocity, self.desired_rate, self.TGP,
smach, self.spot
]
])
for i in range(self.policy.num_deltas):
# Receive cummulative reward from each rollout
negative_rewards[i] = parentPipes[i].recv()[0]
else:
raise ValueError(
"Select 'train' method if you are not using multiprocessing!")
# Calculate std dev
std_dev_rewards = np.array(positive_rewards + negative_rewards).std()
# Order rollouts in decreasing list using cum reward as criterion
# take max between reward for +- disturbance as that rollout's reward
# Store max between positive and negative reward as key for sort
scores = {
k: max(r_pos, r_neg)
for k, (
r_pos,
r_neg) in enumerate(zip(positive_rewards, negative_rewards))
}
indeces = sorted(scores.keys(), key=lambda x: scores[x],
reverse=True)[:self.policy.num_deltas]
# print("INDECES: ", indeces)
rollouts = [(positive_rewards[k], negative_rewards[k], deltas[k])
for k in indeces]
# Update Policy
self.policy.update(rollouts, std_dev_rewards)
# Execute Current Policy USING VANILLA OR TG
if self.TGP is None:
return self.deploy()
else:
return self.deployTG()
def save(self, filename):
""" Save the Policy
:param filename: the name of the file where the policy is saved
"""
with open(filename + '_policy', 'wb') as filehandle:
pickle.dump(self.policy.theta, filehandle)
def load(self, filename):
""" Load the Policy
:param filename: the name of the file where the policy is saved
"""
with open(filename + '_policy', 'rb') as filehandle:
self.policy.theta = pickle.load(filehandle)
| 26,330 | Python | 37.836283 | 148 | 0.536308 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/mini_bullet/terrain_env_randomizer.py | """Generates a random terrain at Minitaur gym environment reset."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import random
import os, inspect
currentdir = os.path.dirname(
os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(os.path.dirname(currentdir))
parentdir = os.path.dirname(os.path.dirname(parentdir))
os.sys.path.insert(0, parentdir)
import itertools
import math
import enum
import numpy as np
from pybullet_envs.minitaur.envs import env_randomizer_base
_GRID_LENGTH = 15
_GRID_WIDTH = 10
_MAX_SAMPLE_SIZE = 30
_MIN_BLOCK_DISTANCE = 0.7
_MAX_BLOCK_LENGTH = _MIN_BLOCK_DISTANCE
_MIN_BLOCK_LENGTH = _MAX_BLOCK_LENGTH / 2
_MAX_BLOCK_HEIGHT = 0.05
_MIN_BLOCK_HEIGHT = _MAX_BLOCK_HEIGHT / 2
class PoissonDisc2D(object):
"""Generates 2D points using Poisson disk sampling method.
Implements the algorithm described in:
http://www.cs.ubc.ca/~rbridson/docs/bridson-siggraph07-poissondisk.pdf
Unlike the uniform sampling method that creates small clusters of points,
Poisson disk method enforces the minimum distance between points and is more
suitable for generating a spatial distribution of non-overlapping objects.
"""
def __init__(self, grid_length, grid_width, min_radius, max_sample_size):
"""Initializes the algorithm.
Args:
grid_length: The length of the bounding square in which points are
sampled.
grid_width: The width of the bounding square in which points are
sampled.
min_radius: The minimum distance between any pair of points.
max_sample_size: The maximum number of sample points around a active site.
See details in the algorithm description.
"""
self._cell_length = min_radius / math.sqrt(2)
self._grid_length = grid_length
self._grid_width = grid_width
self._grid_size_x = int(grid_length / self._cell_length) + 1
self._grid_size_y = int(grid_width / self._cell_length) + 1
self._min_radius = min_radius
self._max_sample_size = max_sample_size
# Flattern the 2D grid as an 1D array. The grid is used for fast nearest
# point searching.
self._grid = [None] * self._grid_size_x * self._grid_size_y
# Generate the first sample point and set it as an active site.
first_sample = np.array(
np.random.random_sample(2)) * [grid_length, grid_width]
self._active_list = [first_sample]
# Also store the sample point in the grid.
self._grid[self._point_to_index_1d(first_sample)] = first_sample
def _point_to_index_1d(self, point):
"""Computes the index of a point in the grid array.
Args:
point: A 2D point described by its coordinates (x, y).
Returns:
The index of the point within the self._grid array.
"""
return self._index_2d_to_1d(self._point_to_index_2d(point))
def _point_to_index_2d(self, point):
"""Computes the 2D index (aka cell ID) of a point in the grid.
Args:
point: A 2D point (list) described by its coordinates (x, y).
Returns:
x_index: The x index of the cell the point belongs to.
y_index: The y index of the cell the point belongs to.
"""
x_index = int(point[0] / self._cell_length)
y_index = int(point[1] / self._cell_length)
return x_index, y_index
def _index_2d_to_1d(self, index2d):
"""Converts the 2D index to the 1D position in the grid array.
Args:
index2d: The 2D index of a point (aka the cell ID) in the grid.
Returns:
The 1D position of the cell within the self._grid array.
"""
return index2d[0] + index2d[1] * self._grid_size_x
def _is_in_grid(self, point):
"""Checks if the point is inside the grid boundary.
Args:
point: A 2D point (list) described by its coordinates (x, y).
Returns:
Whether the point is inside the grid.
"""
return (0 <= point[0] < self._grid_length) and (0 <= point[1] <
self._grid_width)
def _is_in_range(self, index2d):
"""Checks if the cell ID is within the grid.
Args:
index2d: The 2D index of a point (aka the cell ID) in the grid.
Returns:
Whether the cell (2D index) is inside the grid.
"""
return (0 <= index2d[0] < self._grid_size_x) and (0 <= index2d[1] <
self._grid_size_y)
def _is_close_to_existing_points(self, point):
"""Checks if the point is close to any already sampled (and stored) points.
Args:
point: A 2D point (list) described by its coordinates (x, y).
Returns:
True iff the distance of the point to any existing points is smaller than
the min_radius
"""
px, py = self._point_to_index_2d(point)
# Now we can check nearby cells for existing points
for neighbor_cell in itertools.product(xrange(px - 1, px + 2),
xrange(py - 1, py + 2)):
if not self._is_in_range(neighbor_cell):
continue
maybe_a_point = self._grid[self._index_2d_to_1d(neighbor_cell)]
if maybe_a_point is not None and np.linalg.norm(
maybe_a_point - point) < self._min_radius:
return True
return False
def sample(self):
"""Samples new points around some existing point.
Removes the sampling base point and also stores the new jksampled points if
they are far enough from all existing points.
"""
active_point = self._active_list.pop()
for _ in xrange(self._max_sample_size):
# Generate random points near the current active_point between the radius
random_radius = np.random.uniform(self._min_radius,
2 * self._min_radius)
random_angle = np.random.uniform(0, 2 * math.pi)
# The sampled 2D points near the active point
sample = random_radius * np.array(
[np.cos(random_angle),
np.sin(random_angle)]) + active_point
if not self._is_in_grid(sample):
continue
if self._is_close_to_existing_points(sample):
continue
self._active_list.append(sample)
self._grid[self._point_to_index_1d(sample)] = sample
def generate(self):
"""Generates the Poisson disc distribution of 2D points.
Although the while loop looks scary, the algorithm is in fact O(N), where N
is the number of cells within the grid. When we sample around a base point
(in some base cell), new points will not be pushed into the base cell
because of the minimum distance constraint. Once the current base point is
removed, all future searches cannot start from within the same base cell.
Returns:
All sampled points. The points are inside the quare [0, grid_length] x [0,
grid_width]
"""
while self._active_list:
self.sample()
all_sites = []
for p in self._grid:
if p is not None:
all_sites.append(p)
return all_sites
class TerrainType(enum.Enum):
"""The randomzied terrain types we can use in the gym env."""
RANDOM_BLOCKS = 1
TRIANGLE_MESH = 2
class MinitaurTerrainRandomizer(env_randomizer_base.EnvRandomizerBase):
"""Generates an uneven terrain in the gym env."""
def __init__(self,
terrain_type=TerrainType.TRIANGLE_MESH,
mesh_filename="terrain9735.obj",
mesh_scale=None):
"""Initializes the randomizer.
Args:
terrain_type: Whether to generate random blocks or load a triangle mesh.
mesh_filename: The mesh file to be used. The mesh will only be loaded if
terrain_type is set to TerrainType.TRIANGLE_MESH.
mesh_scale: the scaling factor for the triangles in the mesh file.
"""
self._terrain_type = terrain_type
self._mesh_filename = mesh_filename
self._mesh_scale = mesh_scale if mesh_scale else [1.0, 1.0, 0.3]
def randomize_env(self, env):
"""Generate a random terrain for the current env.
Args:
env: A minitaur gym environment.
"""
if self._terrain_type is TerrainType.TRIANGLE_MESH:
self._load_triangle_mesh(env)
if self._terrain_type is TerrainType.RANDOM_BLOCKS:
self._generate_convex_blocks(env)
def _load_triangle_mesh(self, env):
"""Represents the random terrain using a triangle mesh.
It is possible for Minitaur leg to stuck at the common edge of two triangle
pieces. To prevent this from happening, we recommend using hard contacts
(or high stiffness values) for Minitaur foot in sim.
Args:
env: A minitaur gym environment.
"""
env.pybullet_client.removeBody(env.ground_id)
terrain_collision_shape_id = env.pybullet_client.createCollisionShape(
shapeType=env.pybullet_client.GEOM_MESH,
fileName=self._mesh_filename,
flags=1,
meshScale=self._mesh_scale)
env.ground_id = env.pybullet_client.createMultiBody(
baseMass=0,
baseCollisionShapeIndex=terrain_collision_shape_id,
basePosition=[0, 0, 0])
def _generate_convex_blocks(self, env):
"""Adds random convex blocks to the flat ground.
We use the Possion disk algorithm to add some random blocks on the ground.
Possion disk algorithm sets the minimum distance between two sampling
points, thus voiding the clustering effect in uniform N-D distribution.
Args:
env: A minitaur gym environment.
"""
poisson_disc = PoissonDisc2D(_GRID_LENGTH, _GRID_WIDTH,
_MIN_BLOCK_DISTANCE, _MAX_SAMPLE_SIZE)
block_centers = poisson_disc.generate()
for center in block_centers:
# We want the blocks to be in front of the robot.
shifted_center = np.array(center) - [2, _GRID_WIDTH / 2]
# Do not place blocks near the point [0, 0], where the robot will start.
if abs(shifted_center[0]) < 1.0 and abs(shifted_center[1]) < 1.0:
continue
half_length = np.random.uniform(
_MIN_BLOCK_LENGTH, _MAX_BLOCK_LENGTH) / (2 * math.sqrt(2))
half_height = np.random.uniform(_MIN_BLOCK_HEIGHT,
_MAX_BLOCK_HEIGHT) / 2
box_id = env.pybullet_client.createCollisionShape(
env.pybullet_client.GEOM_BOX,
halfExtents=[half_length, half_length, half_height])
env.pybullet_client.createMultiBody(baseMass=0,
baseCollisionShapeIndex=box_id,
basePosition=[
shifted_center[0],
shifted_center[1],
half_height
])
def _generate_height_field(self, env):
random.seed(10)
env.pybullet_client.configureDebugVisualizer(
env.pybullet_client.COV_ENABLE_RENDERING, 0)
terrainShape = env.pybullet_client.createCollisionShape(
shapeType=env.pybullet_client.GEOM_HEIGHTFIELD,
meshScale=[.1, .1, 24],
fileName="heightmaps/wm_height_out.png")
textureId = env.pybullet_client.loadTexture("gimp_overlay_out.png")
terrain = env.pybullet_client.createMultiBody(0, terrainShape)
env.pybullet_client.changeVisualShape(terrain,
-1,
textureUniqueId=textureId)
env.pybullet_client.changeVisualShape(terrain,
-1,
rgbaColor=[1, 1, 1, 1]) | 12,192 | Python | 39.916107 | 85 | 0.602116 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/mini_bullet/env_randomizer_base.py | """Abstract base class for environment randomizer."""
import abc
class EnvRandomizerBase(object):
"""Abstract base class for environment randomizer.
An EnvRandomizer is called in environment.reset(). It will
randomize physical parameters of the objects in the simulation.
The physical parameters will be fixed for that episode and be
randomized again in the next environment.reset().
"""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def randomize_env(self, env):
"""Randomize the simulated_objects in the environment.
Args:
env: The environment to be randomized.
"""
pass
| 622 | Python | 23.919999 | 65 | 0.726688 |
renanmb/Omniverse_legged_robotics/URDF-Descriptions/OpenQuadruped/OpenQuadruped-spot_mini_mini-spot/spot_bullet/src/mini_bullet/minitaur.py | """This file implements the functionalities of a minitaur using pybullet.
"""
import copy
import math
import numpy as np
from . import motor
import os
INIT_POSITION = [0, 0, .2]
INIT_ORIENTATION = [0, 0, 0, 1]
KNEE_CONSTRAINT_POINT_RIGHT = [0, 0.005, 0.2]
KNEE_CONSTRAINT_POINT_LEFT = [0, 0.01, 0.2]
OVERHEAT_SHUTDOWN_TORQUE = 2.45
OVERHEAT_SHUTDOWN_TIME = 1.0
LEG_POSITION = ["front_left", "back_left", "front_right", "back_right"]
MOTOR_NAMES = [
"motor_front_leftL_joint", "motor_front_leftR_joint",
"motor_back_leftL_joint", "motor_back_leftR_joint",
"motor_front_rightL_joint", "motor_front_rightR_joint",
"motor_back_rightL_joint", "motor_back_rightR_joint"
]
LEG_LINK_ID = [2, 3, 5, 6, 8, 9, 11, 12, 15, 16, 18, 19, 21, 22, 24, 25]
MOTOR_LINK_ID = [1, 4, 7, 10, 14, 17, 20, 23]
FOOT_LINK_ID = [3, 6, 9, 12, 16, 19, 22, 25]
BASE_LINK_ID = -1
class Minitaur(object):
"""The minitaur class that simulates a quadruped robot from Ghost Robotics.
"""
def __init__(self,
pybullet_client,
urdf_root=os.path.join(os.path.dirname(__file__), "../data"),
time_step=0.01,
self_collision_enabled=False,
motor_velocity_limit=np.inf,
pd_control_enabled=False,
accurate_motor_model_enabled=False,
motor_kp=0.7,
motor_kd=0.02,
torque_control_enabled=False,
motor_overheat_protection=False,
on_rack=False,
kd_for_pd_controllers=0.3,
desired_velocity=0.5,
desired_rate=0.0):
"""Constructs a minitaur and reset it to the initial states.
Args:
pybullet_client: The instance of BulletClient to manage different
simulations.
urdf_root: The path to the urdf folder.
time_step: The time step of the simulation.
self_collision_enabled: Whether to enable self collision.
motor_velocity_limit: The upper limit of the motor velocity.
pd_control_enabled: Whether to use PD control for the motors.
accurate_motor_model_enabled: Whether to use the accurate DC motor model.
motor_kp: proportional gain for the accurate motor model
motor_kd: derivative gain for the acurate motor model
torque_control_enabled: Whether to use the torque control, if set to
False, pose control will be used.
motor_overheat_protection: Whether to shutdown the motor that has exerted
large torque (OVERHEAT_SHUTDOWN_TORQUE) for an extended amount of time
(OVERHEAT_SHUTDOWN_TIME). See ApplyAction() in minitaur.py for more
details.
on_rack: Whether to place the minitaur on rack. This is only used to debug
the walking gait. In this mode, the minitaur's base is hanged midair so
that its walking gait is clearer to visualize.
kd_for_pd_controllers: kd value for the pd controllers of the motors.
desired_velocity: additional observation space dimension for policy
desired_rate: additional observation space dimension for policy
"""
# used to calculate minitaur acceleration
self.prev_lin_twist = np.array([0, 0, 0])
self.prev_lin_acc = np.array([0, 0, 0])
self.num_motors = 8
self.num_legs = int(self.num_motors / 2)
self._pybullet_client = pybullet_client
self._urdf_root = urdf_root
self._self_collision_enabled = self_collision_enabled
self._motor_velocity_limit = motor_velocity_limit
self._pd_control_enabled = pd_control_enabled
self._motor_direction = [-1, -1, -1, -1, 1, 1, 1, 1]
self._observed_motor_torques = np.zeros(self.num_motors)
self._applied_motor_torques = np.zeros(self.num_motors)
self._max_force = 3.5
self._accurate_motor_model_enabled = accurate_motor_model_enabled
self._torque_control_enabled = torque_control_enabled
self._motor_overheat_protection = motor_overheat_protection
self._on_rack = on_rack
if self._accurate_motor_model_enabled:
self._kp = motor_kp
self._kd = motor_kd
self._motor_model = motor.MotorModel(
torque_control_enabled=self._torque_control_enabled,
kp=self._kp,
kd=self._kd)
elif self._pd_control_enabled:
self._kp = 8
self._kd = kd_for_pd_controllers
else:
self._kp = 1
self._kd = 1
self.time_step = time_step
self.desired_velocity = desired_velocity
self.desired_rate = desired_rate
self.Reset()
def _RecordMassInfoFromURDF(self):
self._base_mass_urdf = self._pybullet_client.getDynamicsInfo(
self.quadruped, BASE_LINK_ID)[0]
self._leg_masses_urdf = []
self._leg_masses_urdf.append(
self._pybullet_client.getDynamicsInfo(self.quadruped,
LEG_LINK_ID[0])[0])
self._leg_masses_urdf.append(
self._pybullet_client.getDynamicsInfo(self.quadruped,
MOTOR_LINK_ID[0])[0])
def _BuildJointNameToIdDict(self):
num_joints = self._pybullet_client.getNumJoints(self.quadruped)
self._joint_name_to_id = {}
for i in range(num_joints):
joint_info = self._pybullet_client.getJointInfo(self.quadruped, i)
self._joint_name_to_id[joint_info[1].decode(
"UTF-8")] = joint_info[0]
def _BuildMotorIdList(self):
self._motor_id_list = [
self._joint_name_to_id[motor_name] for motor_name in MOTOR_NAMES
]
def Reset(self, reload_urdf=True, desired_velocity=None, desired_rate=None):
"""Reset the minitaur to its initial states.
Args:
reload_urdf: Whether to reload the urdf file. If not, Reset() just place
the minitaur back to its starting position.
"""
# UPDATE DESIRED VELOCITY AND RATE STATES
if desired_velocity is not None:
self.desired_velocity = desired_velocity
if desired_rate is not None:
self.desired_rate = desired_rate
if reload_urdf:
if self._self_collision_enabled:
self.quadruped = self._pybullet_client.loadURDF(
"%s/quadruped/minitaur.urdf" % self._urdf_root,
INIT_POSITION,
flags=self._pybullet_client.URDF_USE_SELF_COLLISION)
else:
self.quadruped = self._pybullet_client.loadURDF(
"%s/quadruped/minitaur.urdf" % self._urdf_root,
INIT_POSITION)
self._BuildJointNameToIdDict()
self._BuildMotorIdList()
self._RecordMassInfoFromURDF()
self.ResetPose(add_constraint=True)
if self._on_rack:
self._pybullet_client.createConstraint(
self.quadruped, -1, -1, -1,
self._pybullet_client.JOINT_FIXED, [0, 0, 0], [0, 0, 0],
[0, 0, 1])
else:
self._pybullet_client.resetBasePositionAndOrientation(
self.quadruped, INIT_POSITION, INIT_ORIENTATION)
self._pybullet_client.resetBaseVelocity(self.quadruped, [0, 0, 0],
[0, 0, 0])
self.ResetPose(add_constraint=False)
self._overheat_counter = np.zeros(self.num_motors)
self._motor_enabled_list = [True] * self.num_motors\
def _SetMotorTorqueById(self, motor_id, torque):
self._pybullet_client.setJointMotorControl2(
bodyIndex=self.quadruped,
jointIndex=motor_id,
controlMode=self._pybullet_client.TORQUE_CONTROL,
force=torque)
def _SetDesiredMotorAngleById(self, motor_id, desired_angle):
self._pybullet_client.setJointMotorControl2(
bodyIndex=self.quadruped,
jointIndex=motor_id,
controlMode=self._pybullet_client.POSITION_CONTROL,
targetPosition=desired_angle,
positionGain=self._kp,
velocityGain=self._kd,
force=self._max_force)
def _SetDesiredMotorAngleByName(self, motor_name, desired_angle):
self._SetDesiredMotorAngleById(self._joint_name_to_id[motor_name],
desired_angle)
def ResetPose(self, add_constraint):
"""Reset the pose of the minitaur.
Args:
add_constraint: Whether to add a constraint at the joints of two feet.
"""
for i in range(self.num_legs):
self._ResetPoseForLeg(i, add_constraint)
def _ResetPoseForLeg(self, leg_id, add_constraint):
"""Reset the initial pose for the leg.
Args:
leg_id: It should be 0, 1, 2, or 3, which represents the leg at
front_left, back_left, front_right and back_right.
add_constraint: Whether to add a constraint at the joints of two feet.
"""
knee_friction_force = 0
half_pi = math.pi / 2.0
knee_angle = -2.1834
leg_position = LEG_POSITION[leg_id]
self._pybullet_client.resetJointState(
self.quadruped,
self._joint_name_to_id["motor_" + leg_position + "L_joint"],
self._motor_direction[2 * leg_id] * half_pi,
targetVelocity=0)
self._pybullet_client.resetJointState(
self.quadruped,
self._joint_name_to_id["knee_" + leg_position + "L_link"],
self._motor_direction[2 * leg_id] * knee_angle,
targetVelocity=0)
self._pybullet_client.resetJointState(
self.quadruped,
self._joint_name_to_id["motor_" + leg_position + "R_joint"],
self._motor_direction[2 * leg_id + 1] * half_pi,
targetVelocity=0)
self._pybullet_client.resetJointState(
self.quadruped,
self._joint_name_to_id["knee_" + leg_position + "R_link"],
self._motor_direction[2 * leg_id + 1] * knee_angle,
targetVelocity=0)
if add_constraint:
self._pybullet_client.createConstraint(
self.quadruped,
self._joint_name_to_id["knee_" + leg_position + "R_link"],
self.quadruped,
self._joint_name_to_id["knee_" + leg_position + "L_link"],
self._pybullet_client.JOINT_POINT2POINT, [0, 0, 0],
KNEE_CONSTRAINT_POINT_RIGHT, KNEE_CONSTRAINT_POINT_LEFT)
if self._accurate_motor_model_enabled or self._pd_control_enabled:
# Disable the default motor in pybullet.
self._pybullet_client.setJointMotorControl2(
bodyIndex=self.quadruped,
jointIndex=(self._joint_name_to_id["motor_" + leg_position +
"L_joint"]),
controlMode=self._pybullet_client.VELOCITY_CONTROL,
targetVelocity=0,
force=knee_friction_force)
self._pybullet_client.setJointMotorControl2(
bodyIndex=self.quadruped,
jointIndex=(self._joint_name_to_id["motor_" + leg_position +
"R_joint"]),
controlMode=self._pybullet_client.VELOCITY_CONTROL,
targetVelocity=0,
force=knee_friction_force)
else:
self._SetDesiredMotorAngleByName(
"motor_" + leg_position + "L_joint",
self._motor_direction[2 * leg_id] * half_pi)
self._SetDesiredMotorAngleByName(
"motor_" + leg_position + "R_joint",
self._motor_direction[2 * leg_id + 1] * half_pi)
self._pybullet_client.setJointMotorControl2(
bodyIndex=self.quadruped,
jointIndex=(self._joint_name_to_id["knee_" + leg_position +
"L_link"]),
controlMode=self._pybullet_client.VELOCITY_CONTROL,
targetVelocity=0,
force=knee_friction_force)
self._pybullet_client.setJointMotorControl2(
bodyIndex=self.quadruped,
jointIndex=(self._joint_name_to_id["knee_" + leg_position +
"R_link"]),
controlMode=self._pybullet_client.VELOCITY_CONTROL,
targetVelocity=0,
force=knee_friction_force)
def GetBasePosition(self):
"""Get the position of minitaur's base.
Returns:
The position of minitaur's base.
"""
position, _ = (self._pybullet_client.getBasePositionAndOrientation(
self.quadruped))
return position
def GetBaseOrientation(self):
"""Get the orientation of minitaur's base, represented as quaternion.
Returns:
The orientation of minitaur's base.
"""
_, orientation = (self._pybullet_client.getBasePositionAndOrientation(
self.quadruped))
return orientation
def GetBaseTwitst(self):
"""Get the Twist of minitaur's base.
Returns:
The Twist of the minitaur's base.
"""
return self._pybullet_client.getBaseVelocity(self.quadruped)
def GetActionDimension(self):
"""Get the length of the action list.
Returns:
The length of the action list.
"""
return self.num_motors
def GetObservationUpperBound(self):
"""Get the upper bound of the observation.
Returns:
The upper bound of an observation. See GetObservation() for the details
of each element of an observation.
NOTE: Changed just like GetObservation()
"""
upper_bound = np.array([0.0] * self.GetObservationDimension())
# roll, pitch
upper_bound[0:2] = np.pi / 2.0
# acc, rate in x,y,z
upper_bound[2:8] = np.inf
# 8:10 are velocity and rate bounds, min and max are +-10
# upper_bound[8:10] = 10
# NOTE: ORIGINAL BELOW
# upper_bound[10:10 + self.num_motors] = math.pi # Joint angle.
# upper_bound[self.num_motors + 10:2 * self.num_motors + 10] = (
# motor.MOTOR_SPEED_LIMIT) # Joint velocity.
# upper_bound[2 * self.num_motors + 10:3 * self.num_motors + 10] = (
# motor.OBSERVED_TORQUE_LIMIT) # Joint torque.
# upper_bound[3 *
# self.num_motors:] = 1.0 # Quaternion of base orientation.
# print("UPPER BOUND{}".format(upper_bound))
return upper_bound
def GetObservationLowerBound(self):
"""Get the lower bound of the observation."""
return -self.GetObservationUpperBound()
def GetObservationDimension(self):
"""Get the length of the observation list.
Returns:
The length of the observation list.
"""
return len(self.GetObservation())
def GetObservation(self):
"""Get the observations of minitaur.
It includes the angles, velocities, torques and the orientation of the base.
Returns:
The observation list. observation[0:8] are motor angles. observation[8:16]
are motor velocities, observation[16:24] are motor torques.
observation[24:28] is the orientation of the base, in quaternion form.
NOTE: DIVERGES FROM STOCK MINITAUR ENV. WILL LEAVE ORIGINAL COMMENTED
For my purpose, the observation space includes Roll and Pitch, as well as
acceleration and gyroscopic rate along the x,y,z axes. All of this
information can be collected from an onboard IMU. The reward function
will contain a hidden velocity reward (fwd, bwd) which cannot be measured
and so is not included. For spinning, the gyroscopic z rate will be used
as the (explicit) velocity reward.
This version operates without motor torques, angles and velocities. Erwin
Coumans' paper suggests a sparse observation space leads to higher reward
"""
observation = []
ori = self.GetBaseOrientation()
# Get roll and pitch
roll, pitch, _ = self._pybullet_client.getEulerFromQuaternion(
[ori[0], ori[1], ori[2], ori[3]])
# Get linear accelerations and angular rates
lt, ang_twist = self.GetBaseTwitst()
lin_twist = np.array([lt[0], lt[1], lt[2]])
# Get linear accelerations
lin_acc = self.prev_lin_twist - lin_twist
# if lin_acc.all() == 0.0:
# lin_acc = self.prev_lin_acc
self.prev_lin_acc = lin_acc
# print("LIN ACC: ", lin_acc)
self.prev_lin_twist = lin_twist
# order: roll, pitch, acc(x,y,z), gyro(x,y,z)
observation.append(roll)
observation.append(pitch)
observation.extend(lin_acc.tolist())
observation.extend(list(ang_twist))
# velocity and rate
# observation.append(self.desired_velocity)
# observation.append(self.desired_rate)
# NOTE: ORIGINAL BELOW
# observation.extend(self.GetMotorAngles().tolist())
# observation.extend(self.GetMotorVelocities().tolist())
# observation.extend(self.GetMotorTorques().tolist())
# observation.extend(list(self.GetBaseOrientation()))
return observation
def ApplyAction(self, motor_commands):
"""Set the desired motor angles to the motors of the minitaur.
The desired motor angles are clipped based on the maximum allowed velocity.
If the pd_control_enabled is True, a torque is calculated according to
the difference between current and desired joint angle, as well as the joint
velocity. This torque is exerted to the motor. For more information about
PD control, please refer to: https://en.wikipedia.org/wiki/PID_controller.
Args:
motor_commands: The eight desired motor angles.
"""
if self._motor_velocity_limit < np.inf:
current_motor_angle = self.GetMotorAngles()
motor_commands_max = (current_motor_angle +
self.time_step * self._motor_velocity_limit)
motor_commands_min = (current_motor_angle -
self.time_step * self._motor_velocity_limit)
motor_commands = np.clip(motor_commands, motor_commands_min,
motor_commands_max)
if self._accurate_motor_model_enabled or self._pd_control_enabled:
q = self.GetMotorAngles()
qdot = self.GetMotorVelocities()
if self._accurate_motor_model_enabled:
actual_torque, observed_torque = self._motor_model.convert_to_torque(
motor_commands, q, qdot)
if self._motor_overheat_protection:
for i in range(self.num_motors):
if abs(actual_torque[i]) > OVERHEAT_SHUTDOWN_TORQUE:
self._overheat_counter[i] += 1
else:
self._overheat_counter[i] = 0
if (self._overheat_counter[i] >
OVERHEAT_SHUTDOWN_TIME / self.time_step):
self._motor_enabled_list[i] = False
# The torque is already in the observation space because we use
# GetMotorAngles and GetMotorVelocities.
self._observed_motor_torques = observed_torque
# Transform into the motor space when applying the torque.
self._applied_motor_torque = np.multiply(
actual_torque, self._motor_direction)
for motor_id, motor_torque, motor_enabled in zip(
self._motor_id_list, self._applied_motor_torque,
self._motor_enabled_list):
if motor_enabled:
self._SetMotorTorqueById(motor_id, motor_torque)
else:
self._SetMotorTorqueById(motor_id, 0)
else:
torque_commands = -self._kp * (
q - motor_commands) - self._kd * qdot
# The torque is already in the observation space because we use
# GetMotorAngles and GetMotorVelocities.
self._observed_motor_torques = torque_commands
# Transform into the motor space when applying the torque.
self._applied_motor_torques = np.multiply(
self._observed_motor_torques, self._motor_direction)
for motor_id, motor_torque in zip(self._motor_id_list,
self._applied_motor_torques):
self._SetMotorTorqueById(motor_id, motor_torque)
else:
motor_commands_with_direction = np.multiply(
motor_commands, self._motor_direction)
for motor_id, motor_command_with_direction in zip(
self._motor_id_list, motor_commands_with_direction):
self._SetDesiredMotorAngleById(motor_id,
motor_command_with_direction)
def GetMotorAngles(self):
"""Get the eight motor angles at the current moment.
Returns:
Motor angles.
"""
motor_angles = [
self._pybullet_client.getJointState(self.quadruped, motor_id)[0]
for motor_id in self._motor_id_list
]
motor_angles = np.multiply(motor_angles, self._motor_direction)
return motor_angles
def GetMotorVelocities(self):
"""Get the velocity of all eight motors.
Returns:
Velocities of all eight motors.
"""
motor_velocities = [
self._pybullet_client.getJointState(self.quadruped, motor_id)[1]
for motor_id in self._motor_id_list
]
motor_velocities = np.multiply(motor_velocities, self._motor_direction)
return motor_velocities
def GetMotorTorques(self):
"""Get the amount of torques the motors are exerting.
Returns:
Motor torques of all eight motors.
"""
if self._accurate_motor_model_enabled or self._pd_control_enabled:
return self._observed_motor_torques
else:
motor_torques = [
self._pybullet_client.getJointState(self.quadruped,
motor_id)[3]
for motor_id in self._motor_id_list
]
motor_torques = np.multiply(motor_torques, self._motor_direction)
return motor_torques
def ConvertFromLegModel(self, actions):
"""Convert the actions that use leg model to the real motor actions.
Args:
actions: The theta, phi of the leg model.
actions are of form = [phi, phi, phi, phi, theta, theta, theta, theta]
where phi = swing and theta = extension
Returns:
The eight desired motor angles that can be used in ApplyActions().
"""
motor_angle = copy.deepcopy(actions)
scale_for_singularity = 1
offset_for_singularity = 1.5
half_num_motors = int(self.num_motors / 2)
quater_pi = math.pi / 4
for i in range(self.num_motors):
action_idx = i // 2
forward_backward_component = (
-scale_for_singularity * quater_pi *
(actions[action_idx + half_num_motors] +
offset_for_singularity))
extension_component = (-1)**i * quater_pi * actions[action_idx]
if i >= half_num_motors:
extension_component = -extension_component
motor_angle[i] = (math.pi + forward_backward_component +
extension_component)
return motor_angle
def GetBaseMassFromURDF(self):
"""Get the mass of the base from the URDF file."""
return self._base_mass_urdf
def GetLegMassesFromURDF(self):
"""Get the mass of the legs from the URDF file."""
return self._leg_masses_urdf
def SetBaseMass(self, base_mass):
self._pybullet_client.changeDynamics(self.quadruped,
BASE_LINK_ID,
mass=base_mass)
def SetLegMasses(self, leg_masses):
"""Set the mass of the legs.
A leg includes leg_link and motor. All four leg_links have the same mass,
which is leg_masses[0]. All four motors have the same mass, which is
leg_mass[1].
Args:
leg_masses: The leg masses. leg_masses[0] is the mass of the leg link.
leg_masses[1] is the mass of the motor.
"""
for link_id in LEG_LINK_ID:
self._pybullet_client.changeDynamics(self.quadruped,
link_id,
mass=leg_masses[0])
for link_id in MOTOR_LINK_ID:
self._pybullet_client.changeDynamics(self.quadruped,
link_id,
mass=leg_masses[1])
def SetFootFriction(self, foot_friction):
"""Set the lateral friction of the feet.
Args:
foot_friction: The lateral friction coefficient of the foot. This value is
shared by all four feet.
"""
for link_id in FOOT_LINK_ID:
self._pybullet_client.changeDynamics(self.quadruped,
link_id,
lateralFriction=foot_friction)
def SetBatteryVoltage(self, voltage):
if self._accurate_motor_model_enabled:
self._motor_model.set_voltage(voltage)
def SetMotorViscousDamping(self, viscous_damping):
if self._accurate_motor_model_enabled:
self._motor_model.set_viscous_damping(viscous_damping) | 25,949 | Python | 42.540268 | 85 | 0.582951 |