123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
- #include "PressureSensor.h"
- #include "Modbus.h"
- PressureSensor::PressureSensor(SerialUi* pSerial)
- {
- m_pSerial = pSerial;
- }
- bool PressureSensor::Read(float& pressure)
- {
- QByteArray tx_buf;
- char zero = 0x00;
- tx_buf.append(PRESSURESENSOR_ADDRESS);
- tx_buf.append(0x04);
- tx_buf.append(zero);
- tx_buf.append(zero);
- tx_buf.append(zero);
- tx_buf.append(0x02);
- unsigned short crc;
- crc=CRC16_MODBUS((unsigned char *)tx_buf.data(),tx_buf.size());
- tx_buf.append((crc>>8)&0xff);
- tx_buf.append(crc&0xff);
- QByteArray rx_buf;
- rx_buf = m_pSerial->serialWriteReponse(tx_buf);
- if(rx_buf.size() > 0){
- if(check_crc(rx_buf)){
- char value[4];
- value[3] = rx_buf.at(5);
- value[2] = rx_buf.at(6);
- value[1] = rx_buf.at(3);
- value[0] = rx_buf.at(4);
- float* p = (float*)value;
- pressure = *p;
- return true;
- }else{
- qDebug("PressureSensor::Read <<< check crc failed");
- return false;
- }
- }else{
- qDebug("PressureSensor::Read <<< no data received");
- return false;
- }
- }
- bool PressureSensor::Set_Zero()
- {
- QByteArray tx_buf;
- char zero = 0x00;
- tx_buf.append(PRESSURESENSOR_ADDRESS);
- tx_buf.append(0x06);
- tx_buf.append(zero);
- tx_buf.append(0x1E);
- tx_buf.append(zero);
- tx_buf.append(0x01);
- unsigned short crc;
- crc=CRC16_MODBUS((unsigned char *)tx_buf.data(),tx_buf.size());
- tx_buf.append((crc>>8)&0xff);
- tx_buf.append(crc&0xff);
- QByteArray rx_buf;
- rx_buf = m_pSerial->serialWriteReponse(tx_buf);
- if(rx_buf.size() > 0){
- if(check_crc(rx_buf)){
- return true;
- }else{
- qDebug("PressureSensor::Set_Zero <<< check crc failed");
- return false;
- }
- }else{
- qDebug("PressureSensor::Set_Zero <<< no data received");
- return false;
- }
- }
- bool PressureSensor::check_crc(QByteArray data)
- {
- int size = data.size();
- unsigned short crc1 =0, crc2= 0;
- unsigned char crc_h = data.at(size-2);
- unsigned char crc_l = data.at(size-1);
- crc1 = (crc_h <<8) |crc_l;
- crc2 = CRC16_MODBUS((unsigned char *)data.data(),data.size()-2);
- if(crc1 == crc2){
- return true;
- }else{
- return false;
- }
- }
|