6 .clock_speed = 1000000,
8 .angle_register = 0x3FFF,
11 .command_parity_bit = 15
20 .clock_speed = 1000000,
22 .angle_register = 0x0000,
25 .command_parity_bit = 0
39 cpr = pow(2,_bit_resolution);
42 bit_resolution = _bit_resolution;
44 command_parity_bit = 15;
72 pinMode(chip_select_pin, OUTPUT);
76 #ifndef ESP_H // if not ESP32 board
77 spi->setBitOrder(MSBFIRST);
79 spi->setClockDivider(SPI_CLOCK_DIV8);
82 digitalWrite(chip_select_pin, HIGH);
85 velocity_calc_timestamp =
_micros();
88 full_rotation_offset = 0;
89 angle_data_prev = getRawCount();
96 float angle_data = getRawCount();
101 float d_angle = angle_data - angle_data_prev;
103 if(abs(d_angle) > (0.8*cpr) ) full_rotation_offset += d_angle > 0 ? -
_2PI :
_2PI;
106 angle_data_prev = angle_data;
110 return full_rotation_offset + ( angle_data / (float)cpr) *
_2PI;
116 unsigned long now_us =
_micros();
117 float Ts = (now_us - velocity_calc_timestamp)*1e-6;
119 if(Ts <= 0 || Ts > 0.5) Ts = 1e-3;
124 float vel = (angle_c - angle_prev)/Ts;
127 angle_prev = angle_c;
128 velocity_calc_timestamp = now_us;
134 int MagneticSensorSPI::getRawCount(){
135 return (
int)MagneticSensorSPI::read(angle_register);
142 byte MagneticSensorSPI::spiCalcEvenParity(word value){
146 for (i = 0; i < 16; i++)
148 if (value & 0x1) cnt++;
159 word MagneticSensorSPI::read(word angle_register){
161 word command = angle_register;
163 if (command_rw_bit > 0) {
164 command = angle_register | (1 << command_rw_bit);
166 if (command_parity_bit > 0) {
168 command |= ((word)spiCalcEvenParity(command) << command_parity_bit);
171 #if !defined(_STM32_DEF_) // if not stm chips
173 spi->beginTransaction(settings);
177 digitalWrite(chip_select_pin, LOW);
178 digitalWrite(chip_select_pin, LOW);
179 spi->transfer16(command);
180 digitalWrite(chip_select_pin,HIGH);
181 digitalWrite(chip_select_pin,HIGH);
183 #if defined( ESP_H ) // if ESP32 board
184 delayMicroseconds(50);
186 delayMicroseconds(10);
190 digitalWrite(chip_select_pin, LOW);
191 digitalWrite(chip_select_pin, LOW);
192 word register_value = spi->transfer16(0x00);
193 digitalWrite(chip_select_pin, HIGH);
194 digitalWrite(chip_select_pin,HIGH);
196 #if !defined(_STM32_DEF_) // if not stm chips
198 spi->endTransaction();
201 register_value = register_value >> (1 + data_start_bit - bit_resolution);
203 const static word data_mask = 0xFFFF >> (16 - bit_resolution);
205 return register_value & data_mask;
212 void MagneticSensorSPI::close(){