read encoder

Dependencies:   mbed

Committer:
JJting
Date:
Tue Jul 31 14:19:56 2018 +0000
Revision:
2:33062fc279ca
Parent:
1:2f2a74337b77
20180731ver3(encoder read with header file)

Who changed what in which revision?

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