Hier ist ein Code Auszug:
Code: Alles auswählen
/**************************************************************************/
/*!
@brief read 2 bytes from a hardware register
@param reg the register to read
@return the read value as a 2 byte unsigned integer
*/
/**************************************************************************/
uint16_t Adafruit_AM2320::readRegister16(uint8_t reg) {
// wake up
Wire.beginTransmission(_i2caddr);
Wire.write(0x00);
Wire.endTransmission();
delay(10); // wait 10 ms
// send a command to read register
Wire.beginTransmission(_i2caddr);
Wire.write(AM2320_CMD_READREG);
Wire.write(reg);
Wire.write(2); // 2 bytes
Wire.endTransmission();
delay(2); // wait 2 ms
// 2 bytes preamble, 2 bytes data, 2 bytes CRC
Wire.requestFrom(_i2caddr, (uint8_t)6);
if (Wire.available() != 6)
return 0xFFFF;
uint8_t buffer[6];
for (int i=0; i<6; i++) {
buffer[i] = Wire.read();
//Serial.print("byte #"); Serial.print(i); Serial.print(" = 0x"); Serial.println(buffer[i], HEX);
}
if (buffer[0] != 0x03) return 0xFFFF; // must be 0x03 modbus reply
if (buffer[1] != 2) return 0xFFFF; // must be 2 bytes reply
uint16_t the_crc = buffer[5];
the_crc <<= 8;
the_crc |= buffer[4];
uint16_t calc_crc = crc16(buffer, 4); // preamble + data
//Serial.print("CRC: 0x"); Serial.println(calc_crc, HEX);
if (the_crc != calc_crc)
return 0xFFFF;
// All good!
uint16_t ret = buffer[2];
ret <<= 8;
ret |= buffer[3];
return ret;
}
/**************************************************************************/
/*!
@brief perfor a CRC check to verify data
@param buffer the pointer to the data to check
@param nbytes the number of bytes to calculate the CRC over
@return the calculated CRC
*/
/**************************************************************************/
uint16_t Adafruit_AM2320::crc16(uint8_t *buffer, uint8_t nbytes) {
uint16_t crc = 0xffff;
for (int i=0; i<nbytes; i++) {
uint8_t b = buffer[i];
crc ^= b;
for (int x=0; x<8; x++) {
if (crc & 0x0001) {
crc >>= 1;
crc ^= 0xA001;
} else {
crc >>= 1;
}
}
}
return crc;
}
Code: Alles auswählen
uint16_t ret = buffer[2];
ret <<= 8;
ret |= buffer[3];
Code: Alles auswählen
ret:=buffer[2];
ret:=ret shl 8;
ret:=ret or buffer[3];
Code: Alles auswählen
function readRegister16(reg: UInt8): UInt16;
var
Buffer: PUInt8Array;
i:Integer;
ret:UInt16;
begin
TWIStart((ADSaddr0 shl 1) or TWI_Write);
TWIWrite($0);
TWIStop;
UARTSendString('TestA'#13#10);
TWIStart((ADSaddr0 shl 1) or TWI_Write);
TWIWrite(00);
TWIStop;
mysleep(1000*9);
UARTSendString('TestB'#13#10);
TWIStart((ADSaddr0 shl 1) or TWI_Write);
TWIWrite(AM2320_CMD_READREG);
TWIWrite(reg);
TWIWrite($02);
TWIStop;
// 250000 = 500
// 2
mysleep(4);
UARTSendString('TestC'#13#10);
TWIStart((ADSaddr0 shl 1) or TWI_Read);
for i:=0 to 6 do begin
buffer[i]:=TWIReadACK;
end;
TWIStop;
ret:=buffer[2];
ret:=ret shl 8;
ret:=ret or buffer[3];
// UARTSendByte();
UARTSendString('Test1:'+Char(ret)+#13#10);
// UARTSendIntArray(Buffer);
result:=0;
end;