Wyatt  1.0.1
AdafruitPWMServoHat.cpp
1 #include "hardwareinterface/AdafruitPWMServoHat.h"
2 #include <chrono>
3 #include <thread>
4 #include <iostream>
5 #include <cmath>
6 
8  m_hz(pwmFrequency)
9 {
10  m_i2c = wiringPiI2CSetup(PCA9685_ADDRESS);
11  this->setAllPwm(0, 0);
12  wiringPiI2CWriteReg8(m_i2c, MODE2, OUTDRV);
13  wiringPiI2CWriteReg8(m_i2c, MODE1, ALLCALL);
14  std::this_thread::sleep_for(std::chrono::milliseconds(5));
15  int mode1 = wiringPiI2CReadReg8(m_i2c, MODE1);
16  mode1 = mode1 & ~SLEEP;
17  wiringPiI2CWriteReg8(m_i2c, MODE1, mode1);
18  std::this_thread::sleep_for(std::chrono::milliseconds(5));
19 
20  this->setPwmFrequency((double)m_hz);
21 }
22 
24 {
25 }
26 
27 bool AdafruitPWMServoHat::setMotor(int motorID, int speed)
28 {
29  speed = (speed > 4095) ? 4095 : (speed < 0) ? 0 : speed;
30  this->setPwm(motorID, 0, speed);
31  return true;
32 }
33 
35 {
36  this->setMotor(motorID, 0);
37  return true;
38 }
39 
41 {
42  for (int i = 0; i < 16; i++)
43  {
44  this->stopMotor(i);
45  }
46  return true;
47 }
48 
49 void AdafruitPWMServoHat::softwareReset()
50 {
51  wiringPiI2CWrite(m_i2c, 0x06); // Software Reset
52 }
53 
54 void AdafruitPWMServoHat::setPwmFrequency(double freqHz)
55 {
56  double prescaleval = 25000000.0;
57  prescaleval /= 4096.0;
58  prescaleval /= freqHz;
59  prescaleval -= 1.0;
60  std::cout << "Setting PWM Frequency to " << freqHz << "Hz" << std::endl;
61  std::cout << "Estimated Prescale: " << prescaleval << std::endl;
62  int prescale = (int)floor(prescaleval + 0.5);
63  std::cout << "Final Prescale: " << prescale << std::endl;
64  int oldmode = wiringPiI2CReadReg8(m_i2c, MODE1);
65  int newmode = (oldmode & 0x7F) | 0x10;
66  wiringPiI2CWriteReg8(m_i2c, MODE1, newmode);
67  wiringPiI2CWriteReg8(m_i2c, PRESCALE, prescale);
68  wiringPiI2CWriteReg8(m_i2c, MODE1, oldmode);
69  std::this_thread::sleep_for(std::chrono::milliseconds(5));
70  wiringPiI2CWriteReg8(m_i2c, MODE1, oldmode | 0x80);
71 }
72 
73 void AdafruitPWMServoHat::setPwm(int channel, int on, int off)
74 {
75  wiringPiI2CWriteReg8(m_i2c, LED0_ON_L + 4*channel, on & 0xFF);
76  wiringPiI2CWriteReg8(m_i2c, LED0_ON_H + 4*channel, on >> 8);
77  wiringPiI2CWriteReg8(m_i2c, LED0_OFF_L + 4*channel, off & 0xFF);
78  wiringPiI2CWriteReg8(m_i2c, LED0_OFF_H + 4*channel, off >> 8);
79 }
80 
81 void AdafruitPWMServoHat::setAllPwm(int on, int off)
82 {
83  wiringPiI2CWriteReg8(m_i2c, ALL_LED_ON_L, on & 0xFF);
84  wiringPiI2CWriteReg8(m_i2c, ALL_LED_ON_H, on >> 8);
85  wiringPiI2CWriteReg8(m_i2c, ALL_LED_OFF_L, off & 0xFF);
86  wiringPiI2CWriteReg8(m_i2c, ALL_LED_OFF_H, off >> 8);
87 }
void setAllPwm(int on, int off)
bool setMotor(int motorID, int speed)
bool stopMotor(int motorID)
AdafruitPWMServoHat(int pwmFrequency=60)
void setPwm(int channel, int on, int off)