read encoder and Dynamixel angle

Dependencies:   MX28 PID mbed

Committer:
JJting
Date:
Sat Aug 04 05:55:50 2018 +0000
Revision:
0:2dbbe7d28fab
can read encoder and Dynamixel angle

Who changed what in which revision?

UserRevisionLine numberNew contents of line
JJting 0:2dbbe7d28fab 1 #include "mbed.h"
JJting 0:2dbbe7d28fab 2 #include "encoder.h"
JJting 0:2dbbe7d28fab 3
JJting 0:2dbbe7d28fab 4 DigitalOut encoder_cs(D9);
JJting 0:2dbbe7d28fab 5 //SPI spi_encoder(D11, D12, D13); // mosi, miso, sclk
JJting 0:2dbbe7d28fab 6 SPI spi_encoder(D4, D5, D3); // mosi, miso, sclk
JJting 0:2dbbe7d28fab 7
JJting 0:2dbbe7d28fab 8 unsigned short encoder_value;
JJting 0:2dbbe7d28fab 9 unsigned short angle = 0;
JJting 0:2dbbe7d28fab 10 unsigned short angle_old;
JJting 0:2dbbe7d28fab 11 int angle_dif;
JJting 0:2dbbe7d28fab 12 int a_dif;
JJting 0:2dbbe7d28fab 13 int Angle = 0;
JJting 0:2dbbe7d28fab 14 unsigned short k = 0;
JJting 0:2dbbe7d28fab 15
JJting 0:2dbbe7d28fab 16 void init_SPI_encoder()
JJting 0:2dbbe7d28fab 17 {
JJting 0:2dbbe7d28fab 18 spi_encoder.format(16,3);
JJting 0:2dbbe7d28fab 19 spi_encoder.frequency(1000000); // 1MHz clock rate
JJting 0:2dbbe7d28fab 20 }
JJting 0:2dbbe7d28fab 21
JJting 0:2dbbe7d28fab 22 void init_encoder()
JJting 0:2dbbe7d28fab 23 {
JJting 0:2dbbe7d28fab 24 encoder_cs = 1; // high:disable the device
JJting 0:2dbbe7d28fab 25 }
JJting 0:2dbbe7d28fab 26
JJting 0:2dbbe7d28fab 27 void angle_measure()
JJting 0:2dbbe7d28fab 28 {
JJting 0:2dbbe7d28fab 29 encoder_cs = 0; // Select the device by seting chip select low
JJting 0:2dbbe7d28fab 30 encoder_value = spi_encoder.write(0x00);
JJting 0:2dbbe7d28fab 31 angle = encoder_value >> 3;
JJting 0:2dbbe7d28fab 32 encoder_cs = 1; // Deselect the device
JJting 0:2dbbe7d28fab 33
JJting 0:2dbbe7d28fab 34 if (k == 0) {
JJting 0:2dbbe7d28fab 35 Angle = 0;
JJting 0:2dbbe7d28fab 36 angle_old = angle;
JJting 0:2dbbe7d28fab 37 k++;
JJting 0:2dbbe7d28fab 38 } else {
JJting 0:2dbbe7d28fab 39 angle_dif = angle_count(angle, angle_old);
JJting 0:2dbbe7d28fab 40 Angle = Angle + angle_dif;
JJting 0:2dbbe7d28fab 41 angle_old = angle;
JJting 0:2dbbe7d28fab 42 }
JJting 0:2dbbe7d28fab 43 }
JJting 0:2dbbe7d28fab 44
JJting 0:2dbbe7d28fab 45 int angle_count(unsigned short now,unsigned short old)
JJting 0:2dbbe7d28fab 46 {
JJting 0:2dbbe7d28fab 47 a_dif = now - old;
JJting 0:2dbbe7d28fab 48 if (a_dif > 4096/2) {
JJting 0:2dbbe7d28fab 49 a_dif = -(4096 - a_dif);
JJting 0:2dbbe7d28fab 50 } else if (a_dif < -4096/2) {
JJting 0:2dbbe7d28fab 51 a_dif = 4096 + a_dif;
JJting 0:2dbbe7d28fab 52 } else {
JJting 0:2dbbe7d28fab 53 a_dif = a_dif;
JJting 0:2dbbe7d28fab 54 }
JJting 0:2dbbe7d28fab 55 return a_dif;
JJting 0:2dbbe7d28fab 56 }