用ttl转485接在串口2上,设置波特率9600
预先修改/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/cores里的
HardwareSerial.h
所有buffer都改成128,要大于64
void setup()
{
Serial.begin(9600);
Serial2.begin(9600);
delay(1000);
}
void loop()
{
GetEncoder();
}
long int GetEncoder() {
int _i = 0; int _temp = 0; int _crc = 0;
long int Rotate = 0;
if (Serial1.available() > 0)
{
if (int(Serial1.read()) == 171)
{
//报头AB
if ( (int(Serial1.read()) == 205) && (int(Serial1.read()) == 5))//报头CD和报长5
{
//Serial.println("data received!");
int _recv[6];//接收缓存
while (int(_temp) != 61)
{
_temp = Serial1.read();
_recv[_i] = _temp;
//Serial.println(recv[i], HEX);
//delay(2);
_i++;
}
Serial1.flush(); _i = 0; _temp = 0; //重置
//Serial.println("xor");
_crc = (_recv[0] + _recv[1] + _recv[2] + _recv[3] + 5) & 0xff;
if (int(_recv[4]) == _crc)
{
long int _rotatenum = _recv[0]; _rotatenum <<= 8; _rotatenum |= _recv[1];
long int _rotateangle = _recv[2]; _rotateangle <<= 8; _rotateangle |= _recv[3];
Rotate = _rotatenum * 4096 + _rotateangle;
//Serial.println(Rotate/100);
return Rotate / 100;
}
//delay(10);
}
}
}
}