1-Wire USB 接口
使用 VB6 读取 DS18B20 传感器温度的 1-Wire USB 接口。
引言
我在网上找不到基于 USB 的 1-Wire 接口,所以阅读了相关说明并制作了一个。最初我用 C 编写代码,但因为我需要 VB6 中的接口,所以我重写了它。这个想法是使用 USB 转 RS232 适配器和 Maxim 1-Wire SDK 中的受版权保护的 'IBFS32.dll'。你只需要两个晶体管和两个电阻就可以使其工作。我使用的适配器是 'USB-Serial CH340',非常便宜,我创建了一个虚拟 COM17 端口。我能够从我的 USB 适配器(GRD,来自计算机的 5VDC)为 1-Wire 设备供电,并使用 RS232 的 RX、TX(pin2 和 pin3)。我还将振荡晶体焊接到板子的另一侧。
背景
- 温度测量作为 1-Wire 技术应用的一个例子:Jakub Piwowarczyk 著:onewire.aspx
- http://www.maxim-ic.com/app-notes/index.mvp/id/214
- http://martybugs.net/electronics/tempsensor/
- Maxim “通过串行接口读取和写入 1-Wire® 设备”:http://www.maxim-ic.com/app-notes/index.mvp/id/74
Using the Code
由于这是一个廉价的适配器,因此无法使用 COM17。相反,我打开了 COM3,就这样,我能够从 18b20 读取温度。
RetValue = TMReadDefaultPort(PortNum, PortType)
If (RetValue < 1) Then
PortNum = 3 '// COM 3
PortType = 1 '// DS9097E style adapter
End If
从命令行执行程序时,可以像这样修改端口号和端口类型
'DS18b20.exe <portnumber> <porttype> '. ('DS18b20.exe 3 1')
类型可用的选项在 'OneWire.h' 中
OW_ADAPTER_DS9097 = 1, (we are really using only this one)
OW_ADAPTER_DS1413 = 2,
OW_ADAPTER_DS9097E = 3,
OW_ADAPTER_DS9097U = 4,
OW_ADAPTER_DS9097U9 = 5,
OW_ADAPTER_DS1411 = 6,
OW_ADAPTER_DS1410D = 7,
OW_ADAPTER_DS1410E = 8
由于虚拟适配器未实现 OW_ADAPTER_DS9097
,我们只能使用小于 15 的数字。读取传感器时,我们还可以使用中断来确定数据何时准备好。要使用此功能,我们必须使用 5VDC 电源为传感器供电(而不是使用寄生电源)。在寄生电源模式下,传感器不会发送数据就绪信号进行处理。相反,来自传感器的的数据使用时间片读取,这取决于使用的温度精度
to accuracy 0.5°C - 93,75 ms, 0.25°C - 187,5 ms,
0.125°C - 375 ms,
and for 0.0625°C - 750 ms
在 FindDevices
过程中,我们可以从 ROM 的最后一个字节读取 familycode:在 DS18b20 中是 '28h',DS18s20 是 '10h','DS2780' 相应的是 '32h' 等。
Public Function FindDevices() As Integer
Dim didsetup As Integer, result As Integer, DevId As Integer, i As Integer
ReDim ROM(8) As Integer
If SHandle > 0 Then
result = TMSetup(SHandle)
If Not (result = 1) Then FindDevices = 1
' only get the next rom after setup complete
result = TMNext(SHandle, state_buffer(0))
If result > 0 Then
SelectROM(0) = 0
result = TMRom(SHandle, state_buffer(0), SelectROM(0))
For i = 0 To 7
Debug.Print "SelectROM(" & i & ") = " & SelectROM(i)
Next i
If SelectROM(0) = 40 Then Debug.Print "DS18b20 detected"
If SelectROM(0) = 50 Then Debug.Print "DS2780 detected"
FindDevices = 0
End If
Else
FindDevices = 1
End If
End Function
因此,通过修改代码,我们可以读取任何传感器数据并将其写入 EEPROM。例如在 DS18b20 中,我们可以改变温度的精度。
温度传感器的分辨率可由用户配置为 9、10、11 或 12 位,分别对应于 0.5°C、0.25°C、0.125°C 和 0.0625°C 的增量。上电时的默认分辨率为 12 位。
If Not (res = DS18B20_RES_10) Then
WriteScratchpad DS18B20_RES_10, 0, 20
CopyScratchpadToEEPROM
End If
执行此操作的命令在 WriteScratchPad()
函数中
Select Case res
Case DS18B20_RES_9: TMTouchByte SHandle, 31
Case DS18B20_RES_10: TMTouchByte SHandle, 63
Case DS18B20_RES_11: TMTouchByte SHandle, 95
Case DS18B20_RES_12: TMTouchByte SHandle, 127
Case Else: TMTouchByte SHandle, 31
End Select
关注点
在使用 Jakub Piwowarczyk 的代码时,我曾想知道当从传感器读取温度达到 50% 时 CPU 进程使用率。当我用 'MsgWaitForMultipleObjects()
' 替换函数 'GetTickCount()
' 时,进程使用率降至 1%。这是异步处理中的一个已知错误,当进程被阻止运行时。
现在我可以将使用 1-Wire 协议的设备连接到我的计算机 USB 端口。