Skip to content

Commit 528c6f8

Browse files
authored
Adding Mcp9808 (#49)
1 parent 5951c2c commit 528c6f8

15 files changed

+558
-0
lines changed

devices/Mcp9808/Mcp9808.cs

+201
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
4+
using System;
5+
using System.Device.I2c;
6+
using System.Device.Model;
7+
using System.Threading;
8+
using UnitsNet;
9+
10+
namespace Iot.Device.Mcp9808
11+
{
12+
/// <summary>
13+
/// Microchip's MCP9808 I2C Temp sensor
14+
/// </summary>
15+
[Interface("Microchip's MCP9808 I2C Temp sensor")]
16+
public class Mcp9808 : IDisposable
17+
{
18+
private I2cDevice _i2cDevice;
19+
20+
/// <summary>
21+
/// MCP9808 I2C Address
22+
/// </summary>
23+
public const byte DefaultI2cAddress = 0x18;
24+
25+
#region prop
26+
27+
/// <summary>
28+
/// MCP9808 Temperature
29+
/// </summary>
30+
[Telemetry]
31+
public Temperature Temperature { get => Temperature.FromDegreesCelsius(GetTemperature()); }
32+
33+
private bool _disable;
34+
35+
/// <summary>
36+
/// Disable MCP9808
37+
/// </summary>
38+
[Property]
39+
public bool Disabled
40+
{
41+
get => _disable;
42+
set
43+
{
44+
SetShutdown(value);
45+
}
46+
}
47+
48+
#endregion
49+
50+
/// <summary>
51+
/// Creates a new instance of the MCP9808
52+
/// </summary>
53+
/// <param name="i2cDevice">The I2C device used for communication.</param>
54+
public Mcp9808(I2cDevice i2cDevice)
55+
{
56+
_i2cDevice = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
57+
58+
Disabled = false;
59+
60+
if (!Init())
61+
{
62+
throw new Exception("Unable to identify manufacturer/device id");
63+
}
64+
}
65+
66+
/// <summary>
67+
/// Checks if the device is a MCP9808
68+
/// </summary>
69+
/// <returns>True if device has been correctly detected</returns>
70+
private bool Init()
71+
{
72+
if (Read16(Register8.MCP_MANUF_ID) != 0x0054)
73+
{
74+
return false;
75+
}
76+
77+
if (Read16(Register8.MCP_DEVICE_ID) != 0x0400)
78+
{
79+
return false;
80+
}
81+
82+
return true;
83+
}
84+
85+
/// <summary>
86+
/// Return the internal resolution register
87+
/// </summary>
88+
/// <returns>Resolution setting</returns>
89+
[Property("Resolution")]
90+
public byte GetResolution() => Read8(Register8.MCP_RESOLUTION);
91+
92+
/// <summary>
93+
/// Wakes-up the device
94+
/// </summary>
95+
[Command]
96+
public void Wake()
97+
{
98+
SetShutdown(false);
99+
100+
// Sleep 250 ms, which is the typical temperature conversion time for the highest resolution (page 3 in datasheet, tCONV)
101+
Thread.Sleep(250);
102+
}
103+
104+
/// <summary>
105+
/// Shuts down the device
106+
/// </summary>
107+
[Command]
108+
public void Shutdown() => SetShutdown(true);
109+
110+
/// <summary>
111+
/// Read MCP9808 Temperature (℃)
112+
/// </summary>
113+
/// <returns>Temperature</returns>
114+
private double GetTemperature()
115+
{
116+
ushort value = Read16(Register8.MCP_AMBIENT_TEMP);
117+
118+
if (value == 0xFFFF)
119+
{
120+
// Return NaN if the MCP9808 doesn't have a measurement ready at the time of reading
121+
return double.NaN;
122+
}
123+
124+
double temp = value & 0x0FFF;
125+
temp /= 16.0;
126+
if ((value & 0x1000) != 0)
127+
{
128+
temp -= 256;
129+
}
130+
131+
return Math.Round(temp * 100000) / 100000;
132+
}
133+
134+
/// <summary>
135+
/// Set MCP9808 Shutdown
136+
/// </summary>
137+
/// <param name="isShutdown">Shutdown when value is true.</param>
138+
private void SetShutdown(bool isShutdown)
139+
{
140+
Register16 curVal = ReadRegister16(Register8.MCP_CONFIG);
141+
142+
if (isShutdown)
143+
{
144+
curVal |= Register16.MCP_CONFIG_SHUTDOWN;
145+
}
146+
else
147+
{
148+
curVal &= ~Register16.MCP_CONFIG_SHUTDOWN;
149+
}
150+
151+
Write16(Register8.MCP_CONFIG, curVal);
152+
153+
_disable = isShutdown;
154+
}
155+
156+
/// <summary>
157+
/// Cleanup
158+
/// </summary>
159+
public void Dispose()
160+
{
161+
_i2cDevice?.Dispose();
162+
_i2cDevice = null!;
163+
}
164+
165+
internal Register16 ReadRegister16(Register8 reg) => (Register16)Read16(reg);
166+
167+
internal ushort Read16(Register8 reg)
168+
{
169+
_i2cDevice.WriteByte((byte)reg);
170+
SpanByte buf = new byte[2];
171+
_i2cDevice.Read(buf);
172+
173+
return (ushort)(buf[0] << 8 | buf[1]);
174+
}
175+
176+
internal void Write16(Register8 reg, Register16 value)
177+
{
178+
_i2cDevice.Write(new byte[]
179+
{
180+
(byte)reg,
181+
(byte)((ushort)value >> 8),
182+
(byte)((ushort)value & 0xFF)
183+
});
184+
}
185+
186+
internal byte Read8(Register8 reg)
187+
{
188+
_i2cDevice.WriteByte((byte)reg);
189+
return _i2cDevice.ReadByte();
190+
}
191+
192+
internal void Write8(Register8 reg, byte value)
193+
{
194+
_i2cDevice.Write(new byte[]
195+
{
196+
(byte)reg,
197+
value
198+
});
199+
}
200+
}
201+
}

devices/Mcp9808/Mcp9808.nfproj

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<Project ToolsVersion="Current" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3+
<PropertyGroup Label="Globals">
4+
<NanoFrameworkProjectSystemPath>$(MSBuildToolsPath)..\..\..\nanoFramework\v1.0\</NanoFrameworkProjectSystemPath>
5+
</PropertyGroup>
6+
<Import Project="$(NanoFrameworkProjectSystemPath)NFProjectSystem.Default.props" Condition="Exists('$(NanoFrameworkProjectSystemPath)NFProjectSystem.Default.props')" />
7+
<PropertyGroup>
8+
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
9+
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
10+
<ProjectTypeGuids>{11A8DD76-328B-46DF-9F39-F559912D0360};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
11+
<ProjectGuid>{3C3FB348-B711-4CDA-8EA6-40EEFF8628AE}</ProjectGuid>
12+
<OutputType>Library</OutputType>
13+
<AppDesignerFolder>Properties</AppDesignerFolder>
14+
<FileAlignment>512</FileAlignment>
15+
<RootNamespace>Iot.Device.Mcp9808</RootNamespace>
16+
<AssemblyName>Iot.Device.Mcp9808</AssemblyName>
17+
<TargetFrameworkVersion>v1.0</TargetFrameworkVersion>
18+
<DocumentationFile>bin\$(Configuration)\Iot.Device.Mcp9808.xml</DocumentationFile>
19+
<LangVersion>9.0</LangVersion>
20+
</PropertyGroup>
21+
<Import Project="$(NanoFrameworkProjectSystemPath)NFProjectSystem.props" Condition="Exists('$(NanoFrameworkProjectSystemPath)NFProjectSystem.props')" />
22+
<ItemGroup>
23+
<Reference Include="mscorlib">
24+
<HintPath>packages\nanoFramework.CoreLibrary.1.10.4-preview.11\lib\mscorlib.dll</HintPath>
25+
<Private>True</Private>
26+
</Reference>
27+
<Reference Include="System.Device.I2c">
28+
<HintPath>packages\nanoFramework.System.Device.I2c.1.0.1-preview.33\lib\System.Device.I2c.dll</HintPath>
29+
<Private>True</Private>
30+
</Reference>
31+
<Reference Include="System.Math">
32+
<HintPath>packages\nanoFramework.System.Math.1.4.0-preview.7\lib\System.Math.dll</HintPath>
33+
<Private>True</Private>
34+
</Reference>
35+
<Reference Include="UnitsNet.Temperature, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
36+
<HintPath>packages\UnitsNet.nanoFramework.Temperature.4.92.1\lib\UnitsNet.Temperature.dll</HintPath>
37+
<Private>True</Private>
38+
<SpecificVersion>True</SpecificVersion>
39+
</Reference>
40+
</ItemGroup>
41+
<ItemGroup>
42+
<None Include="packages.config" />
43+
<Compile Include="Register.cs" />
44+
<Compile Include="Mcp9808.cs" />
45+
</ItemGroup>
46+
<ItemGroup>
47+
<Compile Include="Properties\AssemblyInfo.cs" />
48+
<None Include="*.md" />
49+
</ItemGroup>
50+
<Import Project="$(NanoFrameworkProjectSystemPath)NFProjectSystem.CSharp.targets" Condition="Exists('$(NanoFrameworkProjectSystemPath)NFProjectSystem.CSharp.targets')" />
51+
<Import Project="..\..\src\System.Device.Model\System.Device.Model.projitems" Label="Shared" />
52+
<ProjectExtensions>
53+
<ProjectCapabilities>
54+
<ProjectConfigurationsDeclaredAsItems />
55+
</ProjectCapabilities>
56+
</ProjectExtensions>
57+
<Import Project="packages\Nerdbank.GitVersioning.3.4.194\build\Nerdbank.GitVersioning.targets" Condition="Exists('packages\Nerdbank.GitVersioning.3.4.194\build\Nerdbank.GitVersioning.targets')" />
58+
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
59+
<PropertyGroup>
60+
<ErrorText> This project references NuGet package(s) that are missing on this computer.Enable NuGet Package Restore to download them.For more information, see http://go.microsoft.com/fwlink/?LinkID=322105.The missing file is {0}.</ErrorText>
61+
</PropertyGroup>
62+
<Error Condition="!Exists('packages\Nerdbank.GitVersioning.3.4.194\build\Nerdbank.GitVersioning.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\Nerdbank.GitVersioning.3.4.194\build\Nerdbank.GitVersioning.targets'))" />
63+
</Target>
64+
</Project>

devices/Mcp9808/Mcp9808.nuspec

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<package xmlns="http://schemas.microsoft.com/packaging/2012/06/nuspec.xsd">
3+
<metadata>
4+
<id>nanoFramework.Iot.Device.Mcp9808</id>
5+
<version>$version$</version>
6+
<title>nanoFramework.Iot.Device.Mcp9808</title>
7+
<authors>nanoFramework project contributors</authors>
8+
<owners>nanoFramework project contributors,dotnetfoundation</owners>
9+
<requireLicenseAcceptance>false</requireLicenseAcceptance>
10+
<license type="file">LICENSE.md</license>
11+
<releaseNotes>
12+
</releaseNotes>
13+
<developmentDependency>false</developmentDependency>
14+
<projectUrl>https://github.com/nanoframework/nanoFramework.IoT.Device</projectUrl>
15+
<iconUrl>https://secure.gravatar.com/avatar/97d0e092247f0716db6d4b47b7d1d1ad</iconUrl>
16+
<icon>images\nf-logo.png</icon>
17+
<repository type="git" url="https://github.com/nanoframework/nanoFramework.IoT.Device" commit="$commit$" />
18+
<copyright>Copyright (c) .NET Foundation and Contributors</copyright>
19+
<description>This package includes the .NET IoT Core binding Iot.Device.Mcp9808 for .NET nanoFramework C# projects.</description>
20+
<summary>Iot.Device.Mcp9808 assembly for .NET nanoFramework C# projects</summary>
21+
<tags>nanoFramework C# csharp netmf netnf Iot.Device.Mcp9808</tags>
22+
<dependencies>
23+
<dependency id="nanoFramework.CoreLibrary" version="1.10.4-preview.11" />
24+
<dependency id="nanoFramework.System.Device.I2c" version="1.0.1-preview.33" />
25+
<dependency id="nanoFramework.System.Math" version="1.4.0-preview.7" />
26+
<dependency id="UnitsNet.nanoFramework.Temperature" version="4.92.1" />
27+
</dependencies>
28+
</metadata>
29+
<files>
30+
<file src="bin\Release\Iot.Device.Mcp9808.dll" target="lib\Iot.Device.Mcp9808.dll" />
31+
<file src="bin\Release\Iot.Device.Mcp9808.pdb" target="lib\Iot.Device.Mcp9808.pdb" />
32+
<file src="bin\Release\Iot.Device.Mcp9808.pdbx" target="lib\Iot.Device.Mcp9808.pdbx" />
33+
<file src="bin\Release\Iot.Device.Mcp9808.pe" target="lib\Iot.Device.Mcp9808.pe" />
34+
<file src="bin\Release\Iot.Device.Mcp9808.xml" target="lib\Iot.Device.Mcp9808.xml" />
35+
<file src="readme.md" target="" />
36+
<file src="..\..\assets\nf-logo.png" target="images" />
37+
<file src="..\..\LICENSE.md" target="" />
38+
</files>
39+
</package>

devices/Mcp9808/Mcp9808.sln

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
Microsoft Visual Studio Solution File, Format Version 12.00
2+
# Visual Studio Version 16
3+
VisualStudioVersion = 16.0.30413.136
4+
MinimumVisualStudioVersion = 10.0.40219.1
5+
Project("{11A8DD76-328B-46DF-9F39-F559912D0360}") = "Mcp9808", "Mcp9808.nfproj", "{3C3FB348-B711-4CDA-8EA6-40EEFF8628AE}"
6+
EndProject
7+
Project("{11A8DD76-328B-46DF-9F39-F559912D0360}") = "Mcp9808.Samples", "samples\Mcp9808.Samples.nfproj", "{FC1C40B5-D066-4C8F-A0F3-1B648C88F97D}"
8+
EndProject
9+
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Shared Projects", "Shared Projects", "{91F7F51D-F167-4F5D-ABD1-0464DE8B33D5}"
10+
EndProject
11+
Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "System.Device.Model", "..\..\src\System.Device.Model\System.Device.Model.shproj", "{23325B14-3651-4879-9697-9846FF123FEB}"
12+
EndProject
13+
Global
14+
GlobalSection(SharedMSBuildProjectFiles) = preSolution
15+
..\..\src\System.Device.Model\System.Device.Model.projitems*{23325b14-3651-4879-9697-9846ff123feb}*SharedItemsImports = 13
16+
EndGlobalSection
17+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
18+
Debug|Any CPU = Debug|Any CPU
19+
Release|Any CPU = Release|Any CPU
20+
EndGlobalSection
21+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
22+
{3C3FB348-B711-4CDA-8EA6-40EEFF8628AE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
23+
{3C3FB348-B711-4CDA-8EA6-40EEFF8628AE}.Debug|Any CPU.Build.0 = Debug|Any CPU
24+
{3C3FB348-B711-4CDA-8EA6-40EEFF8628AE}.Debug|Any CPU.Deploy.0 = Debug|Any CPU
25+
{3C3FB348-B711-4CDA-8EA6-40EEFF8628AE}.Release|Any CPU.ActiveCfg = Release|Any CPU
26+
{3C3FB348-B711-4CDA-8EA6-40EEFF8628AE}.Release|Any CPU.Build.0 = Release|Any CPU
27+
{3C3FB348-B711-4CDA-8EA6-40EEFF8628AE}.Release|Any CPU.Deploy.0 = Release|Any CPU
28+
{FC1C40B5-D066-4C8F-A0F3-1B648C88F97D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
29+
{FC1C40B5-D066-4C8F-A0F3-1B648C88F97D}.Debug|Any CPU.Build.0 = Debug|Any CPU
30+
{FC1C40B5-D066-4C8F-A0F3-1B648C88F97D}.Debug|Any CPU.Deploy.0 = Debug|Any CPU
31+
{FC1C40B5-D066-4C8F-A0F3-1B648C88F97D}.Release|Any CPU.ActiveCfg = Release|Any CPU
32+
{FC1C40B5-D066-4C8F-A0F3-1B648C88F97D}.Release|Any CPU.Build.0 = Release|Any CPU
33+
{FC1C40B5-D066-4C8F-A0F3-1B648C88F97D}.Release|Any CPU.Deploy.0 = Release|Any CPU
34+
EndGlobalSection
35+
GlobalSection(SolutionProperties) = preSolution
36+
HideSolutionNode = FALSE
37+
EndGlobalSection
38+
GlobalSection(NestedProjects) = preSolution
39+
{23325B14-3651-4879-9697-9846FF123FEB} = {91F7F51D-F167-4F5D-ABD1-0464DE8B33D5}
40+
EndGlobalSection
41+
GlobalSection(ExtensibilityGlobals) = postSolution
42+
SolutionGuid = {9A866EC4-9D7E-40D1-84BF-5698E5B9A1A4}
43+
EndGlobalSection
44+
EndGlobal
+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
using System.Reflection;
2+
using System.Runtime.CompilerServices;
3+
using System.Runtime.InteropServices;
4+
5+
[assembly: AssemblyTitle("Iot.Device.Mcp9808")]
6+
[assembly: AssemblyCompany("nanoFramework Contributors")]
7+
[assembly: AssemblyCopyright("Copyright(c).NET Foundation and Contributors")]
8+
9+
[assembly: ComVisible(false)]
10+

devices/Mcp9808/README.md

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# MCP9808 - Digital Temperature Sensor
2+
Microchip Technology Inc.’s MCP9808 digital temperature sensor converts temperatures between -20°C and +100°C to a digital word with ±0.25°C/±0.5°C (typical/maximum) accuracy
3+
4+
## Usage
5+
```C#
6+
I2cConnectionSettings settings = new I2cConnectionSettings(1, Mcp9808.DefaultI2cAddress);
7+
I2cDevice device = I2cDevice.Create(settings);
8+
9+
using(Mcp9808 sensor = new Mcp9808(device))
10+
{
11+
double temperature = sensor.Temperature.Celsius;
12+
}
13+
```
14+
15+
## References
16+
http://ww1.microchip.com/downloads/en/DeviceDoc/25095A.pdf

0 commit comments

Comments
 (0)