forked from nanoframework/nanoFramework.IoT.Device
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Base4Relay.cs
79 lines (69 loc) · 2.39 KB
/
Base4Relay.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Device.I2c;
namespace Iot.Device.Relay
{
/// <summary>
/// Base relay common to both Module and Unit 4 Relay.
/// </summary>
public class Base4Relay
{
/// <summary>
/// 4 Relay default I2C Address.
/// </summary>
public const byte DefaultI2cAddress = 0x26;
private I2cDevice _i2cDevice;
private RelayType _relayType;
internal Base4Relay(I2cDevice i2cDevice, RelayType relayType)
{
_i2cDevice = i2cDevice ?? throw new ArgumentNullException();
_relayType = relayType;
}
/// <summary>
/// Sets the state of a specific Relay.
/// </summary>
/// <param name="number">The Relay number from 0 to 3.</param>
/// <param name="state">The state On or Off.</param>
/// <exception cref="ArgumentException">Relay number must be between 0 and 3.</exception>
public void SetRelay(byte number, State state)
{
if (number > 3)
{
throw new ArgumentException();
}
Register reg = _relayType == RelayType.Unit ? Register.UnitRelay : Register.ModuleRelay;
byte status = Read(reg);
if (state == State.On)
{
status &= (byte)~(0x01 << number);
}
else
{
status |= (byte)(0x01 << number);
}
Write(Register.UnitRelay, status);
}
/// <summary>
/// Sets all relays in the desired state.
/// </summary>
/// <param name="state">The state On or Off.</param>
public void SetAllRelays(State state)
{
Register reg = _relayType == RelayType.Unit ? Register.UnitRelay : Register.ModuleRelay;
byte relays = (byte)(Read(reg) & 0xF0);
relays |= (byte)(state == State.On ? 0x0F : 0x00);
Write(reg, relays);
}
internal byte Read(Register reg)
{
_i2cDevice.WriteByte((byte)reg);
return _i2cDevice.ReadByte();
}
internal void Write(Register reg, byte val)
{
SpanByte span = new byte[2] { (byte)reg, val };
_i2cDevice.Write(span);
}
}
}