Advertisement
mikroavr

urm14_rs485

Jun 7th, 2023
1,220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. #define RXD1 32
  3. #define TXD1 25
  4. #define EN_RS485 33
  5. #define LED 12
  6. #include <ModbusMaster.h>
  7. ModbusMaster node;
  8. #define   SLAVE_ADDR                ((uint16_t)0x0C)
  9. #define   TEMP_CPT_SEL_BIT          ((uint16_t)0x01)
  10. #define   TEMP_CPT_ENABLE_BIT       ((uint16_t)0x01 << 1)
  11. #define   MEASURE_MODE_BIT          ((uint16_t)0x01 << 2)
  12. #define   MEASURE_TRIG_BIT          ((uint16_t)0x01 << 3)
  13. uint16_t trigger  = 0;
  14. float jarak = 0.0;
  15. float suhu = 0.0;
  16. void preTransmission()
  17. {
  18.   digitalWrite(EN_RS485, 1);
  19.   digitalWrite(LED, 1);
  20. }
  21. void postTransmission()
  22. {
  23.   digitalWrite(EN_RS485, 0);
  24.   digitalWrite(LED, 0);
  25. }
  26. void setup() {
  27.   // put your setup code here, to run once:
  28.   pinMode(EN_RS485, OUTPUT);
  29.   pinMode(LED, OUTPUT);
  30.    
  31.   Serial.begin(115200);
  32.   Serial1.begin(115200, SERIAL_8N1, RXD1, TXD1);
  33.    
  34.   node.preTransmission(preTransmission);
  35.   node.postTransmission(postTransmission);
  36.   node.begin(SLAVE_ADDR, Serial1);
  37.   delay(1000);
  38.   trigger |= MEASURE_MODE_BIT;//Set bit2 , Set to trigger mode
  39.   trigger &= ~(uint16_t)TEMP_CPT_SEL_BIT;//Select internal temperature compensation
  40.   trigger &= ~(uint16_t)TEMP_CPT_ENABLE_BIT;//enable temperature compensation
  41.   delay(1000);
  42.   conf_autoDistance();
  43. }
  44. void loop() {
  45.   // put your main code here, to run repeatedly:
  46.   baca_urm14();
  47.   delay(2000);
  48. }
  49. void baca_urm14() {
  50.   Serial.println("baca urm14");
  51.   uint8_t result;
  52.   uint16_t data[6];
  53.   trigger |= MEASURE_TRIG_BIT;//Set trig bit
  54.   result = node.writeSingleRegister(3, trigger);
  55.   Serial.print("result_t: ");
  56.   Serial.println(result);
  57.   delay(300);
  58.   result = node.readHoldingRegisters(0, 9);
  59.   Serial.print("result_r: ");
  60.   Serial.println(result);
  61.   if (result == node.ku8MBSuccess)
  62.   {
  63.     jarak = node.getResponseBuffer(5) / 10;
  64.     suhu = node.getResponseBuffer(6) / 10;
  65.     Serial.print("jarak: ");
  66.     Serial.print(jarak);
  67.     Serial.println(" mm");
  68.     Serial.print("suhu: ");
  69.     Serial.print(suhu);
  70.     Serial.println(" C");
  71.     Serial.println("-----------------------");
  72.   }else{
  73.     Serial.println("modbus fail");
  74.   }
  75. }
  76. void conf_autoDistance(){
  77.   uint8_t result = node.writeSingleRegister(0x08, 0); // write address 0x08 with data 0000 /
  78.   Serial.print("write config: ");
  79.   Serial.println(result);
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement