旋转编码器

旋转编码器

增量编码式和绝对编码

增量编码式

有两对光电接受管和发射管,中间是码盘,通过旋转,A,B两相输出不同的波形,根据相位关系判断顺逆时针旋转。

旋转编码器_第1张图片
旋转编码器_第2张图片当按键按下时,相当于普通开关。
旋转编码器_第3张图片旋转编码器_第4张图片

#define _BV(bit) (1 << (bit))

#define BLEN_A 0
#define BLEN_B 1
    // Encoder click is directly connected
#if BUTTON_EXISTS(ENC)
      #define BLEN_C 2
#endif
#define EN_A (_BV(BLEN_A))   //0001
#define EN_B (_BV(BLEN_B))   //0010
#define EN_C (_BV(BLEN_C))	//0100


#define BUTTON_PRESSED(BN) !READ(BTN_## BN)
#define ENCODER_PULSES_PER_STEP 2

uint8_t newbutton = 0;
volatile uint8_t buttons;
volatile int8_t encoderDiff; // Updated in lcd_buttons_update, added to encoderPosition every LCD update
uint32_t encoderPosition;

if (BUTTON_PRESSED(EN1)) newbutton |= EN_A;
if (BUTTON_PRESSED(EN2)) newbutton |= EN_B; 
if (BUTTON_PRESSED(ENC)) newbutton |= EN_C;
#define encrot0 0
#define encrot1 2
#define encrot2 3
#define encrot3 1

#define ENCODER_DIFF_CW  (encoderDiff--)
#define ENCODER_DIFF_CCW (encoderDiff++)
#define ENCODER_SPIN(_E1, _E2) switch (lastEncoderBits) { case _E1: ENCODER_DIFF_CW; break; case _E2: ENCODER_DIFF_CCW; }
buttons = newbutton;
uint8_t enc = 0;
void lcd_update()
{
	static uint8_t lastEncoderBits;
	if (buttons & EN_A) 
		enc |= B01;
	if (buttons & EN_B) 
		enc |= B10;
	if (enc != lastEncoderBits) 
	{
		//logic refrence pic
      switch (enc) 
	  {
        
		case 0:
			switch(lastEncoderBits)
			{
				case 1:
					encoderDiff--;
					break;
				case 2:
					encoderDiff++;
					break;
			}
		case 2:
			switch(lastEncoderBits)
			{
				case 0:
					encoderDiff--;
					break;
				case 3:
					encoderDiff++;
					break;
			}
		case 3:
			switch(lastEncoderBits)
			{
				case 2:
					encoderDiff--;
					break;
				case 1:
					encoderDiff++;
					break;
			}
		case 1:
			switch(lastEncoderBits)
			{
				case 3:
					encoderDiff--;
					break;
				case 0:
					encoderDiff++;
					break;
			}
        
      }
	  
	  lastEncoderBits = enc;
	}
}


bool encoderPastThreshold = (abs(encoderDiff) >= ENCODER_PULSES_PER_STEP);//编码位置改变
if (encoderPastThreshold || lcd_clicked) 
{
	if (encoderPastThreshold) //编码器转动了
	{
		uin32_t encoderMultiplier = 1;
		encoderPosition += (encoderDiff * encoderMultiplier) / ENCODER_PULSES_PER_STEP;
		encoderDiff=0;
	}
}



脉冲数20个

你可能感兴趣的:(电子技术)