在我们电脑连接arduino MEGA 2560后,我们打开arduino设置完串口和板子,这时候我们就需要写程序了!
- encoder.h
//below can be changed, but should be PORTD pins;
//A wheel encode pin
#define ENC_A_PIN_A 2 //pin 2 -- interrupt 0
#define ENC_A_PIN_B 3 //pin 3 -- interrupt 1
//B wheel encode pin
#define ENC_B_PIN_A 21 //pin 21 -- interrupt 2
#define ENC_B_PIN_B 20 //pin 20 -- interrupt 3
//C wheel encode pin
#define ENC_C_PIN_A 19 //pin 19 -- interrupt 4
#define ENC_C_PIN_B 18 //pin 18 -- interrupt 5
long readEncoder(int i);
void resetEncoder(int i);
void resetEncoders();
void initEncoders();
编码器的引脚连接就是根据这个来连接的!
2.. encoder_driver
static volatile long A_enc_pos = 0L;
static volatile long B_enc_pos = 0L;
static volatile long C_enc_pos = 0L;
/*init encoder connect pin*/
void initEncoders()
{
pinMode(ENC_A_PIN_A, INPUT);
pinMode(ENC_A_PIN_B, INPUT);
attachInterrupt(0, encoderA_ISR, CHANGE);
attachInterrupt(1, encoderA_ISR, CHANGE);
pinMode(ENC_B_PIN_A, INPUT);
pinMode(ENC_B_PIN_B, INPUT);
attachInterrupt(2, encoderB_ISR, CHANGE);
attachInterrupt(3, encoderB_ISR, CHANGE);
pinMode(ENC_C_PIN_A, INPUT);
pinMode(ENC_C_PIN_B, INPUT);
attachInterrupt(4, encoderC_ISR, CHANGE);
attachInterrupt(5, encoderC_ISR, CHANGE);
}
/* Interrupt routine for A encoder, taking care of actual counting */
void encoderA_ISR ()
{
if (directionWheel(A_WHEEL) == BACKWARDS)
{
A_enc_pos--;
}
else
{
A_enc_pos++;
}
}
/* Interrupt routine for B encoder, taking care of actual counting */
void encoderB_ISR ()
{
if (directionWheel(B_WHEEL) == BACKWARDS)
{
B_enc_pos--;
}
else
{
B_enc_pos++;
}
}
/* Interrupt routine for C encoder, taking care of actual counting */
void encoderC_ISR ()
{
if (directionWheel(C_WHEEL) == BACKWARDS)
{
C_enc_pos--;
}
else
{
C_enc_pos++;
}
}
/* Wrap the encoder reading function */
long readEncoder(int i)
{
if (i == A_WHEEL)
{
return A_enc_pos;
}
else if (i == B_WHEEL)
{
return B_enc_pos;
}
else
{
return C_enc_pos;
}
}
/* Wrap the encoder reset function */
void resetEncoders() {
A_enc_pos = 0L;
B_enc_pos = 0L;
C_enc_pos = 0L;
}
在这些程序中,最重要的就是编码器程序了。
这个是小车底盘的所有arduino程序(三轮全向轮小车):
链接:https://pan.baidu.com/s/1Y5HgqodHH7eNaTVKtFND0g
密码:y2re