2021.12.22
Dependents: 4dof_attitude 4dof_screw
PCA9685.cpp
- Committer:
- Kotttaro
- Date:
- 2022-02-24
- Revision:
- 3:a4e0f41bd0b6
- Parent:
- 0:a95a8df36651
File content as of revision 3:a4e0f41bd0b6:
#include <mbed.h> #include "PCA9685.h" #define i2c_addr 0x80 I2C i2c(p9,p10); Serial pc(USBTX,USBRX); //PCA9685::PCA9685(uint8_t addr) { // i2c_addr = addr; //} void PCA9685::begin(void) { // WIRE.begin(); reset(); } void PCA9685::reset(void) { write8(PCA9685_MODE1, 0x0); } void PCA9685::setPWMFreq(float freq) { float prescaleval = 25000000; prescaleval /= 4096; prescaleval /= freq; prescaleval -= 1; uint8_t prescale = floor(prescaleval + 0.5); uint8_t oldreg = read8(PCA9685_MODE1); //pc.printf("oldreg=%02X , ",oldreg); uint8_t newreg = (oldreg&0x7F) | 0x10; // sleep write8(PCA9685_MODE1, newreg); // go to sleep wait_ms(5); write8(PCA9685_PRESCALE, prescale); // set the prescaler write8(PCA9685_MODE1, oldreg); wait_ms(5); write8(PCA9685_MODE1, oldreg | 0xa1); // This sets the MODE1 register to turn on auto increment. } void PCA9685::setPWM(uint8_t num, uint16_t on, uint16_t off) { //Serial.print("Setting PWM "); Serial.print(num); Serial.print(": "); Serial.print(on); Serial.print("->"); Serial.println(off); //int ded; char cmd[5];//WIRE.beginTransmission(i2c_addr); cmd[0]=LED0_ON_L+4*num;//WIRE.write(LED0_ON_L+4*num); cmd[1]=on&0xFF;//WIRE.write(on); cmd[2]=on>>8;//WIRE.write(on>>8); cmd[3]=off&0xFF;//WIRE.write(off); cmd[4]=off>>8;//WIRE.write(off>>8); i2c.write(i2c_addr,cmd,5);//WIRE.endTransmission(); //pc.printf("write 5 %d\r\n",ded); } void PCA9685::write8(uint8_t addr, uint8_t d) { //int val; char cmd[2];//WIRE.beginTransmission(i2c_addr); cmd[0]=addr;//WIRE.write(addr); cmd[1]=d;//WIRE.write(d); i2c.write(i2c_addr,cmd,2);//WIRE.endTransmission(); //pc.printf("write %d\r\n",val); } uint8_t PCA9685::read8(uint8_t addr) { //int val; char cmd[1]; //WIRE.beginTransmission(i2c_addr); cmd[0]=addr; i2c.write(i2c_addr,cmd,1); //WIRE.write(addr); //WIRE.endTransmission(); //pc.printf("write %d\r\n",val); char rtn[1]; i2c.read(i2c_addr,rtn,1); //WIRE.requestFrom((uint8_t)i2c_addr, (uint8_t)1); //pc.printf("read %d %c\r\n",val,rtn[0]); return rtn[0]; //return WIRE.read(); }