Main Content

Read Temperature from a Remote Temperature Sensor

This example shows how to read temperature and humidity measurements from a remote sensor on a PLC connected via TCP/IP. The temperature sensor is connected to a holding register at address 1 on the board, and the humidity sensor is at address 5.

  1. Create the Modbus object, using TCP/IP.

    m = modbus('tcpip', '192.168.2.1', 502)
    m = 
    
       Modbus TCPIP with properties:
    
        DeviceAddress: '192.168.2.1'
                 Port: 502
               Status: 'open'
           NumRetries: 1
              Timeout: 10 (seconds)
            ByteOrder: 'big-endian'
            WordOrder: 'big-endian'
  2. The humidity sensor does not always respond instantly, so increase the timeout value to 20 seconds.

    m.Timeout = 20
  3. The temperature sensor is connected to a holding register at address 1 on the board. Read one value to get the current temperature reading. As the temperature value is a double, set the precision to double.

    read(m,'holdingregs',1,1,'double')
    ans = 
    
       46.7
  4. The humidity sensor is connected to the holding register at address 5 on the board. Read one value to get the current humidity reading.

    read(m,'holdingregs',5,1,'double')
    ans = 
    
       35.8
  5. Disconnect from the server and clear the object.

    clear m