
int addr= 0x40;//PCA9685address
ioctl(file_i2c,I2C_SLAVE,addr);//SettheI2Caddressforu
pcoming
//transactions
ioctl() is a general purpose function not specifically limited to working
with I2C.
Configure the PCA9685 Chip for Proper
Operation
The default setup of the PCA9685 chip is not quite right for our purposes.
We need to write to a couple of registers on the chip to make things right.
First we must enable the chip, turning on the PWM output. This is
accomplished by writing the value 0x20 to register 0.
buffer[0]=0;//targetregister
buffer[1]= 0x20;//desiredvalue
length=2;//numberofbytes,includingaddress
write(file_i2c,buffer,length);//initiatewrite
Next, we must enable multi-byte writing, as we’ll be writing two bytes at a
time later when we set the PWM values. This time we don’t need to set the
length variable as it’s already correctly configured.
buffer[0]= 0xfe;
buffer[1]= 0x1e;
write(file_i2c,buffer,length);
Write Values to the PWM Registers
That’s all the setup that needs to be done. From here on out, we can write
data to the PWM chip and expect to have it respond. Here’s an example.
buffer[0]= 0x06;//"starttime"regforchannel0
buffer[1]=0;//Wewantthepulsetostartattimet=0
buffer[2]=0;
length=3;//3bytestotalwritten
write(file_i2c,buffer,length);//initiatethewrite
buffer[0]= 0x08;//"stoptime"regforchannel0
buffer[1]= 1250 & 0xff;//The"low"bytecomesfirst...
buffer[2]=(1250>>8)&0xff;//followedbythehighbyte.
write(file_i2c,buffer,length);//Initiatethewrite.
The first write is to the “start time” register for channel 0. By default, the
PWM frequency of the chip is 200Hz, or one pulse every 5ms. The start
time register determines when the pulse goes high in the 5ms cycle. All
channels are synchronized to that cycle. Generally, this should be written to
0. The second write is to the “stop time” register, and it controls when the
pulse should go low. The range for this value is from 0 to 4095, and each
count represents one slice of that 5ms period (5ms/4095), or about 1.2us.
Thus, the value of 1250 written above represents about 1.5ms of high time
per 5ms period.
Servo motors get their control signal from that pulse width. Generally
speaking, a pulse width of 1.5ms yields a “neutral” position, halfway
between the extremes of the motor’s range. 1.0ms yields approximately 90
degrees off center, and 2.0ms yields -90 degrees off center. In practice,
Page 8 of 10