从 NI USB-8452 控制器上的 I2C 外围设备测量温度
此示例说明如何与 NI™ USB-8452 控制器上的 I2C 外围设备通信。在此示例中,TMP102 数字温度传感器连接到 NI USB-8452 控制器。
TMP102 是一种双线串行输出数字传感器,能够以 0.0625 °C 的分辨率读取温度。它还可以在扩展模式下读取高于 128 °C 的温度值。
设置硬件
将传感器的 SDA、SCL、GND 和 VCC 引脚连接到 NI USB-8452 硬件上的对应引脚。对于此示例,将传感器的 SDA 和 SCL 引脚分别连接到 NI USB-8452 的引脚 3 和引脚 5。将 GND 和 VCC 引脚分别连接到引脚 2 和引脚 7 (DIO(0))。
连接到 I2C 外围设备
使用 ni845xlist 搜索连接到您计算机的 NI USB-8452 硬件,并在 MATLAB® 中使用 ni845x 连接到它。
list = ni845xlist
list=1×2 table
"NI USB-8452" "01F26E0A"
controller = ni845x(list.SerialNumber)
controller =
NI845x with properties:
Model: "NI USB-8452"
SerialNumber: "01F26E0A"
AvailableDigitalPins: ["P0.0" "P0.1" "P0.2" "P0.3" "P0.4" "P0.5" "P0.6" "P0.7"]
Show all properties, functions
将 DIO(0) 引脚配置为输出,并输出 3.3 V 的逻辑高电平电压为温度传感器供电。
configureDigitalPin(controller,"P0.0","output"); writeDigitalPin(controller,"P0.0",1);
扫描 NI USB-8452 硬件以获取可用的 I2C 地址。温度传感器由 I2C 地址 0x48 表示。
address = scanI2CBus(controller)
address = 1×2 string array
"0x48" "0x53"
使用 device 函数和 scanI2CBus 返回的 I2C 地址连接到 I2C 外围设备。
tempSensor = device(controller,I2CAddress=address(1))
tempSensor =
I2CDevice with properties:
Protocol: "I2C"
I2CAddress: 72
BitRate: 100000
ByteOrder: "little-endian"
Show all functions
读取温度值
在普通模式下,传感器返回数字化为 12 位的温度值,其中 8 位在 MSB 中,4 位在 LSB 中。每个 LSB 等于 0.0625 °C。从传感器的寄存器地址 0 读取两个字节的数据,数据类型为 uint8。
使用 tmp102Temperature 辅助函数以 °C 为单位计算温度。您可以在此示例末尾找到此辅助函数,它作为支持文件包含在此示例中。
data = readRegister(tempSensor,0,2,"uint8");
temperature = tmp102Temperature(data,12)temperature = 24.7500
使用更高测量限值读取温度
您可以通过在 TMP102 传感器的扩展模式下使用 13 位来测量高于 128 °C 的温度。为此,按照 TMP102 设备数据手册中的规定,将十六进制值 'B060' 写入地址 1 处的配置寄存器。
writeRegister(tempSensor,1,0xB060,"uint16");从寄存器地址 0 读取温度以获得更精确的结果。由于 TMP102 传感器的转换速率默认为 4 Hz,因此每次读取前将 MATLAB 暂停约 0.25 秒。使用 tmp102Temperature 辅助函数将数据转换为 °C。
write(tempSensor,0x0,"uint8"); pause(0.25); data = read(tempSensor,2,"uint8"); temperature = tmp102Temperature(data,13)
temperature = 24.7500
按照 TMP102 设备数据手册中的规定,更改回默认配置。
writeRegister(tempSensor,1,0xA060,"uint16");清理
在您使用 NI USB-8452 完成工作后,清除关联的 device 和 ni845x 对象。
clear tempSensor controller
辅助函数
function T = tmp102Temperature(data,numBits) % tmp102Temperature Convert TMP102 raw temperature register data to temperature in °C % % T = tmp102Temperature(data,numBits) % data is 1x2 row vector of uint8 values in big-endian order % numBits corresponds to the TMP102 temperature mode (12 bits for normal % mode, or 13 bits for extended mode) % TMP102 resolution (°C / count) resolution = 0.0625; % Digital temperature output (counts) numShiftBits = 16-numBits; digitalT = bitshift(typecast(uint8(fliplr(data)),'int16'),-numShiftBits); % Temperature in °C T = double(digitalT) * resolution; end
另请参阅
ni845xlist | ni845x | configureDigitalPin | writeDigitalPin | scanI2CBus | device | readRegister | writeRegister | write | read