├── .gitignore
├── BlinkLED
├── BlinkLED.csproj
├── Program.cs
└── nuget.config
├── IotSample
├── BMP280.cs
├── Deploy.txt
├── I2CBus.cs
├── I2CNativeLib.cs
├── I2cConnectionSettings.cs
├── II2CBus.cs
├── IotSample.csproj
├── Program.cs
└── nuget.config
├── LICENSE
├── Pi.IO.Components
├── Clocks
│ └── Ds1307Connection.cs
├── Controllers
│ ├── HT16K33
│ │ └── HT16K33Connection.cs
│ ├── Pca9685
│ │ ├── IPwmDevice.cs
│ │ ├── Pca9685Connection.cs
│ │ └── PwmChannel.cs
│ └── Tlc59711
│ │ ├── ExtensionMethods
│ │ └── ByteExtensionMethods.cs
│ │ ├── IPwmChannels.cs
│ │ ├── IPwmDevice.cs
│ │ ├── ITlc59711Cluster.cs
│ │ ├── ITlc59711Connection.cs
│ │ ├── ITlc59711Device.cs
│ │ ├── ITlc59711Settings.cs
│ │ ├── Tlc59711Channels.cs
│ │ ├── Tlc59711Cluster.cs
│ │ ├── Tlc59711ClusterChannels.cs
│ │ ├── Tlc59711Connection.cs
│ │ ├── Tlc59711Device.cs
│ │ └── Tlc59711Settings.cs
├── Converters
│ ├── Mcp3002
│ │ ├── Mcp3002AnalogPinExtensionMethods.cs
│ │ ├── Mcp3002Channel.cs
│ │ ├── Mcp3002InputAnalogPin.cs
│ │ └── Mcp3002SpiConnection.cs
│ ├── Mcp3008
│ │ ├── Mcp3008AnalogPinExtensionMethods.cs
│ │ ├── Mcp3008Channel.cs
│ │ ├── Mcp3008InputAnalogPin.cs
│ │ └── Mcp3008SpiConnection.cs
│ ├── Mcp3208
│ │ ├── Mcp3208AnalogPinExtensionMethods.cs
│ │ ├── Mcp3208Channel.cs
│ │ ├── Mcp3208InputAnalogPin.cs
│ │ └── Mcp3208SpiConnection.cs
│ └── Mcp4822
│ │ ├── Mcp4822AnalogPinExtensionMethods.cs
│ │ ├── Mcp4822Channel.cs
│ │ ├── Mcp4822OutputAnalogPin.cs
│ │ └── Mcp4822SpiConnection.cs
├── Devices
│ └── PiFaceDigital
│ │ ├── InputPinChangedArgs.cs
│ │ ├── InputPinChangedHandler.cs
│ │ ├── PiFaceDigitalDevice.cs
│ │ ├── PiFaceInputPin.cs
│ │ ├── PiFaceOutputPin.cs
│ │ └── PiFacePin.cs
├── Displays
│ ├── Hd44780
│ │ ├── Command.cs
│ │ ├── CursorShiftFlags.cs
│ │ ├── DisplayFlags.cs
│ │ ├── EntryModeFlags.cs
│ │ ├── Functions.cs
│ │ ├── Hd44780A00Encoding.cs
│ │ ├── Hd44780LcdConnection.cs
│ │ ├── Hd44780LcdConnectionSettings.cs
│ │ ├── Hd44780Pins.cs
│ │ └── Hd44780Position.cs
│ ├── Sda5708
│ │ ├── Sda5708Brightness.cs
│ │ ├── Sda5708Connection.cs
│ │ └── Sda5708Font.cs
│ └── Ssd1306
│ │ ├── Command.cs
│ │ ├── Fonts
│ │ ├── Fixed1L.cs
│ │ ├── IFont.cs
│ │ ├── Proportional2L.cs
│ │ └── Proportional3L.cs
│ │ ├── ScrollDirection.cs
│ │ ├── ScrollSpeed.cs
│ │ └── Ssd1306Connection.cs
├── Expanders
│ ├── Mcp23008
│ │ ├── Mcp23008I2cConnection.cs
│ │ ├── Mcp23008InputBinaryPin.cs
│ │ ├── Mcp23008OutputBinaryPin.cs
│ │ ├── Mcp23008Pin.cs
│ │ ├── Mcp23008PinDirection.cs
│ │ ├── Mcp23008PinExtensionMethods.cs
│ │ ├── Mcp23008PinPolarity.cs
│ │ └── Mcp23008PinResistor.cs
│ ├── Mcp23017
│ │ ├── Mcp23017I2cConnection.cs
│ │ ├── Mcp23017InputBinaryPin.cs
│ │ ├── Mcp23017OutputBinaryPin.cs
│ │ ├── Mcp23017Pin.cs
│ │ ├── Mcp23017PinDirection.cs
│ │ ├── Mcp23017PinExtensionMethods.cs
│ │ ├── Mcp23017PinPolarity.cs
│ │ └── Mcp23017PinResistor.cs
│ └── Pcf8574
│ │ ├── Pcf8574I2cConnection.cs
│ │ ├── Pcf8574InputBinaryPin.cs
│ │ ├── Pcf8574OutputBinaryPin.cs
│ │ ├── Pcf8574Pin.cs
│ │ └── Pcf8574PinExtensionMethods.cs
├── Leds
│ ├── BiColor24Bargraph
│ │ └── BiColor24Bargraph.cs
│ ├── GroveBar
│ │ └── GroveBarConnection.cs
│ └── GroveRgb
│ │ ├── GroveRgbConnection.cs
│ │ └── RgbColor.cs
├── Pi.IO.Components.csproj
└── Sensors
│ ├── Distance
│ └── HcSr04
│ │ ├── HcSr04Connection.cs
│ │ └── Units.cs
│ ├── Light
│ └── BH1750Connection.cs
│ ├── Pressure
│ └── Bmp085
│ │ ├── Bmp085Data.cs
│ │ ├── Bmp085I2CConnection.cs
│ │ ├── Bmp085I2cConnectionExtensionMethods.cs
│ │ └── Bmp085Precision.cs
│ ├── ResistiveDivider.cs
│ ├── Temperature
│ ├── Dht
│ │ ├── Dht11Connection.cs
│ │ ├── Dht22Connection.cs
│ │ ├── DhtConnection.cs
│ │ ├── DhtData.cs
│ │ └── InvalidChecksumException.cs
│ ├── Ds18b20
│ │ └── Ds18b20Connection.cs
│ └── Tmp36
│ │ └── Tmp36Connection.cs
│ └── VariableResistiveDividerConnection.cs
├── Pi.IO.GeneralPurpose
├── Behaviors
│ ├── BlinkBehavior.cs
│ ├── ChaserBehavior.cs
│ ├── PatternBehavior.cs
│ ├── PinsBehavior.cs
│ └── PinsBehaviorExtensionMethods.cs
├── Configuration
│ └── GpioConnectionConfigurationSection.cs
├── ConnectedPin.cs
├── ConnectedPins.cs
├── ConnectorPin.cs
├── FileGpioConnectionDriver.cs
├── FileGpioHandle.cs
├── GpioBinaryPinExtensionMethods.cs
├── GpioConnection.cs
├── GpioConnectionDriver.cs
├── GpioConnectionDriverCapabilities.cs
├── GpioConnectionDriverExtensionMethods.cs
├── GpioConnectionSettings.cs
├── GpioInputBinaryPin.cs
├── GpioInputOutputBinaryPin.cs
├── GpioOutputBinaryPin.cs
├── IGpioConnectionDriver.cs
├── InputPinConfiguration.cs
├── Interop.cs
├── MemoryGpioConnectionDriver.cs
├── OutputPinConfiguration.cs
├── Pi.IO.GeneralPurpose.csproj
├── PinConfiguration.cs
├── PinConfigurationExtensionMethods.cs
├── PinDetectedEdges.cs
├── PinDirection.cs
├── PinMapping.cs
├── PinResistor.cs
├── PinStatusEventArgs.cs
├── ProcessorPin.cs
├── ProcessorPinExtensionMethods.cs
├── ProcessorPins.cs
└── SwitchInputPinConfiguration.cs
├── Pi.IO.InterIntegratedCircuit
├── I2cAction.cs
├── I2cDeviceConnection.cs
├── I2cDriver.cs
├── I2cReadAction.cs
├── I2cTransaction.cs
├── I2cWriteAction.cs
├── Interop.cs
└── Pi.IO.InterIntegratedCircuit.csproj
├── Pi.IO.Interop
├── ControlDevice.cs
├── EnumTypes
│ ├── MemoryFlags.cs
│ ├── MemoryProtection.cs
│ └── UnixFileMode.cs
├── ErrNum.cs
├── Exceptions
│ ├── MemoryMapFailedException.cs
│ └── MemoryUnmapFailedException.cs
├── IControlDevice.cs
├── IFile.cs
├── IMemory.cs
├── ManagedMemory.cs
├── MemoryMap.cs
├── MemorySubset.cs
├── Pi.IO.Interop.csproj
├── UnixFile.cs
└── UnmanagedMemory.cs
├── Pi.IO.SerialPeripheralInterface
├── Endianness.cs
├── EnumTypes
│ ├── SpiMode.cs
│ └── SpiTransferMode.cs
├── Exceptions
│ ├── ReadonlyTransferBufferException.cs
│ ├── SendSpiMessageException.cs
│ ├── SetBitsPerWordException.cs
│ ├── SetMaxSpeedException.cs
│ ├── SetSpiModeException.cs
│ └── WriteOnlyTransferBufferException.cs
├── INativeSpiConnection.cs
├── ISpiControlDevice.cs
├── ISpiTransferBuffer.cs
├── ISpiTransferBufferCollection.cs
├── Interop
│ ├── Interop.cs
│ └── SpiTransferControlStructure.cs
├── NativeSpiConnection.cs
├── Pi.IO.SerialPeripheralInterface.csproj
├── SpiConnection.cs
├── SpiConnectionSettings.cs
├── SpiControlDevice.cs
├── SpiSlaveSelectionContext.cs
├── SpiTransferBuffer.cs
└── SpiTransferBufferCollection.cs
├── Pi.IO
├── AnalogValue.cs
├── BinaryPinExtensionMethods.cs
├── ByteExtensionMethods.cs
├── IInputAnalogPin.cs
├── IInputBinaryPin.cs
├── IInputOutputBinaryPin.cs
├── IOutputAnalogPin.cs
├── IOutputBinaryPin.cs
├── Pi.IO.csproj
└── StringExtensionMethods.cs
├── Pi.System
├── Board.cs
├── ConnectorPinout.cs
├── Model.cs
├── Pi.System.csproj
├── Processor.cs
└── Timers
│ ├── HighResolutionTimer.cs
│ ├── ITimer.cs
│ ├── Interop.cs
│ ├── StandardTimer.cs
│ ├── TimeSpanUtility.cs
│ └── Timer.cs
├── Pi.sln
└── README.md
/.gitignore:
--------------------------------------------------------------------------------
1 | ### Repo-specific things ###
2 |
3 | # User-specific files
4 | *.suo
5 | *.user
6 | *.userosscache
7 | *.sln.docstates
8 | .vs/
9 |
10 | # Build results
11 | [Dd]ebug/
12 | [Rr]elease/
13 | [Bb]in/
14 | [Oo]bj/
15 |
16 | # Nuget
17 | project.lock.json
18 |
19 | # VS Code
20 | .vscode/
--------------------------------------------------------------------------------
/BlinkLED/BlinkLED.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp2.0
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/BlinkLED/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Threading;
3 | using Pi.IO.GeneralPurpose;
4 | using Pi.IO;
5 |
6 | namespace BlinkLED
7 | {
8 | class Program
9 | {
10 | static void Main(string[] args)
11 | {
12 | var driver = new GpioConnectionDriver();
13 | var ledPin = driver.Out(ConnectorPin.P1Pin23);
14 |
15 | bool ledState = false;
16 | while (true)
17 | {
18 | ledPin.Write(ledState);
19 | Thread.Sleep(500);
20 | ledState = ledState ? false : true;
21 | }
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/BlinkLED/nuget.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/IotSample/BMP280.cs:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Petermarcu/Pi/bf6c6234c19819095aa773cd997dc9dec5eea71e/IotSample/BMP280.cs
--------------------------------------------------------------------------------
/IotSample/Deploy.txt:
--------------------------------------------------------------------------------
1 | param (
2 | [string]$Username,
3 | [string]$Password,
4 | [string]$LocalDir,
5 | [string]$RemoteDir,
6 | [string]$IP
7 |
8 | )
9 | Write-Host Copying $($LocalDir) to ($IP)
10 |
11 | $pwd = ConvertTo-SecureString $Password -AsPlainText -Force
12 | $mycreds = New-Object System.Management.Automation.PSCredential ($Username, $pwd)
13 |
14 | $session = New-WinSCPSession -GiveUpSecurityAndAcceptAnySshHostKey -Credential $mycreds -HostName $IP -Protocol Scp
15 |
16 | New-WinSCPItem -Path "dotnetcore" -ItemType directory -ErrorAction SilentlyContinue
17 | New-WinSCPItem -Path "dotnetcore/$($RemoteDir)" -ItemType directory -ErrorAction SilentlyContinue
18 |
19 | $transferOptions = New-WinSCPTransferOption -TransferMode Binary
20 |
21 | Sync-WinSCPPath -WinSCPSession $session -Mode Remote `
22 | -LocalPath $LocalDir -RemotePath "dotnetcore/$($RemoteDir)" `
23 | -TransferOptions $transferOptions
24 |
25 |
26 |
27 |
28 |
29 | make sure to run "Install-Module Winscp" before using the script
30 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/IotSample/I2CNativeLib.cs:
--------------------------------------------------------------------------------
1 | using System.Runtime.InteropServices;
2 |
3 | namespace I2C.Net
4 | {
5 | internal static class I2CNativeLib
6 | {
7 | internal static int OPEN_READ_WRITE = 2;
8 |
9 | // constant, even for different devices
10 | internal static int I2C_SLAVE = 0x0703;
11 |
12 | [DllImport("libc.so.6", EntryPoint = "open")]
13 | internal static extern int Open(string fileName, int mode);
14 |
15 | [DllImport("libc.so.6", EntryPoint = "close", SetLastError = true)]
16 | internal static extern int Close(int busHandle);
17 |
18 | [DllImport("libc.so.6", EntryPoint = "ioctl", SetLastError = true)]
19 | internal extern static int Ioctl(int fd, int request, int data);
20 |
21 | [DllImport("libc.so.6", EntryPoint = "read", SetLastError = true)]
22 | internal static extern int Read(int handle, byte[] data, int length);
23 |
24 | [DllImport("libc.so.6", EntryPoint = "write", SetLastError = true)]
25 | internal static extern int Write(int handle, byte[] data, int length);
26 |
27 | /*TODO: Move these to C# based on the above.
28 |
29 |
30 | [DllImport("libnativei2c.so", EntryPoint = "readBytes", SetLastError = true)]
31 | internal static extern int ReadBytes(int busHandle, int addr, byte[] buf, int len);
32 |
33 | */
34 | }
35 | }
--------------------------------------------------------------------------------
/IotSample/I2cConnectionSettings.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace IotSample
6 | {
7 | public class I2cConnectionSettings
8 | {
9 | private byte baseAddress;
10 | public I2cConnectionSettings(byte baseAddress)
11 | {
12 | this.baseAddress = baseAddress;
13 | }
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/IotSample/II2CBus.cs:
--------------------------------------------------------------------------------
1 | using System.Text;
2 |
3 | namespace I2C.Net
4 | {
5 | public interface II2CBus
6 | {
7 | ///
8 | /// Writes single byte.
9 | ///
10 | /// Address of a destination device
11 | ///
12 | void WriteByte(int address, byte b);
13 |
14 | ///
15 | /// Writes array of bytes.
16 | ///
17 | /// Do not write more than 3 bytes at once, RPi drivers don't support this currently.
18 | /// Address of a destination device
19 | ///
20 | void WriteBytes(int address, byte[] bytes);
21 |
22 |
23 | ///
24 | /// Writes command with data.
25 | ///
26 | ///
27 | ///
28 | ///
29 | void WriteCommand(int address, byte command, byte data);
30 |
31 | ///
32 | /// Writes command with data.
33 | ///
34 | ///
35 | ///
36 | ///
37 | ///
38 | void WriteCommand(int address, byte command, byte data1, byte data2);
39 |
40 | ///
41 | /// Writes command with data.
42 | ///
43 | ///
44 | ///
45 | ///
46 | void WriteCommand(int address, byte command, ushort data);
47 |
48 |
49 | ///
50 | /// Reads bytes from device with passed address.
51 | ///
52 | ///
53 | ///
54 | ///
55 | byte[] ReadBytes(int address, int count);
56 |
57 | }
58 | }
--------------------------------------------------------------------------------
/IotSample/IotSample.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | netcoreapp2.0
6 | NU1701
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/IotSample/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Threading;
3 | using Pi.IO.Components.Converters.Mcp3008;
4 | using Pi.IO.GeneralPurpose;
5 | using Pi.IO;
6 |
7 | namespace IotSample
8 | {
9 | class Program
10 | {
11 | static void Main(string[] args)
12 | {
13 | var bmp280 = new BMP280();
14 | bmp280.Initialize();
15 |
16 | const ConnectorPin adcClock = ConnectorPin.P1Pin23;
17 | const ConnectorPin adcMiso = ConnectorPin.P1Pin21;
18 | const ConnectorPin adcMosi = ConnectorPin.P1Pin19;
19 | const ConnectorPin adcCs = ConnectorPin.P1Pin24;
20 |
21 | const ConnectorPin pir = ConnectorPin.P1Pin31;
22 | const ConnectorPin led = ConnectorPin.P1Pin29;
23 |
24 | var driver = new GpioConnectionDriver();
25 |
26 | var adcConnection = new Mcp3008SpiConnection(
27 | driver.Out(adcClock),
28 | driver.Out(adcCs),
29 | driver.In(adcMiso),
30 | driver.Out(adcMosi));
31 |
32 | var pirPin = driver.In(pir);
33 | var ledPin = driver.Out(led);
34 |
35 | bool ledState = false;
36 | ledPin.Write(ledState);
37 |
38 | while (true)
39 | {
40 | Thread.Sleep(500);
41 |
42 | // Read the temperature and pressure
43 | float p = bmp280.ReadPreasure().Result;
44 | float t = bmp280.ReadTemperature().Result;
45 |
46 | float tempF = (t * 9 / 5 + 32);
47 | float pressureInHg = p * .295357F / 1000;
48 |
49 | Console.WriteLine("Pressure: " + pressureInHg + " inHg");
50 | Console.WriteLine("Temperature: " + tempF + " F");
51 |
52 | // Read the analog inputs
53 | AnalogValue a0 = adcConnection.Read(Mcp3008Channel.Channel0);
54 | AnalogValue a1 = adcConnection.Read(Mcp3008Channel.Channel1);
55 | AnalogValue a2 = adcConnection.Read(Mcp3008Channel.Channel2);
56 |
57 | Console.WriteLine("Value 1: " + a0.Value);
58 | Console.WriteLine("Value 2: " + a1.Value);
59 | Console.WriteLine("Value 3: " + a2.Value);
60 |
61 | // Read the pir sensor
62 | var pirState = pirPin.Read();
63 | Console.WriteLine("Pir Pin Value: " + pirState.ToString());
64 | if (pirState && !ledState)
65 | {
66 | ledState = true;
67 | ledPin.Write(ledState);
68 | }
69 | else if (!pirState && ledState)
70 | {
71 | ledState = false;
72 | ledPin.Write(ledState);
73 | }
74 | }
75 | }
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/IotSample/nuget.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Pi.IO.Components/Controllers/Pca9685/IPwmDevice.cs:
--------------------------------------------------------------------------------
1 | using UnitsNet;
2 |
3 | namespace Pi.IO.Components.Controllers.Pca9685
4 | {
5 | ///
6 | /// Provides an interface for PWM devices.
7 | ///
8 | public interface IPwmDevice
9 | {
10 | #region Methods
11 |
12 | ///
13 | /// Sets the PWM update rate.
14 | ///
15 | /// The frequency.
16 | void SetPwmUpdateRate(Frequency frequency);
17 |
18 | ///
19 | /// Sets a single PWM channel with on / off values to control the duty cycle
20 | ///
21 | /// The channel.
22 | /// The on values.
23 | /// The off values.
24 | void SetPwm(PwmChannel channel, int on, int off);
25 |
26 | ///
27 | /// Set a channel to fully on or off
28 | ///
29 | /// The channel.
30 | /// if set to true, all values are on; otherwise they are all off.
31 | void SetFull(PwmChannel channel, bool fullOn);
32 |
33 | #endregion
34 | }
35 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Controllers/Pca9685/PwmChannel.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Controllers.Pca9685
2 | {
3 | ///
4 | /// Denotes available PWM channels
5 | ///
6 | public enum PwmChannel
7 | {
8 | C0 = 0,
9 | C1 = 1,
10 | C2 = 2,
11 | C3 = 3,
12 | C4 = 4,
13 | C5 = 5,
14 | C6 = 6,
15 | C7 = 7,
16 | C8 = 8,
17 | C9 = 9,
18 | C10 = 10,
19 | C11 = 11,
20 | C12 = 12,
21 | C13 = 13,
22 | C14 = 14,
23 | C15 = 15
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Pi.IO.Components/Controllers/Tlc59711/ExtensionMethods/ByteExtensionMethods.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 |
5 | #endregion
6 |
7 | namespace Pi.IO.Components.Controllers.Tlc59711
8 | {
9 | internal static class ByteExtensionMethods
10 | {
11 | #region Constants
12 | public const byte BRIGHTNESS_CONTROL_MAX = 127;
13 | #endregion
14 |
15 | #region Methods
16 |
17 | public static void ThrowOnInvalidBrightnessControl(this byte value) {
18 | if (value <= BRIGHTNESS_CONTROL_MAX)
19 | return;
20 |
21 | var message = String.Format("The maximum value for brightness control is {0}. You set a value of {1}.", BRIGHTNESS_CONTROL_MAX, value);
22 |
23 | throw new ArgumentException(message, "value");
24 | }
25 |
26 | #endregion
27 | }
28 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Controllers/Tlc59711/IPwmChannels.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 |
5 | #endregion
6 |
7 | namespace Pi.IO.Components.Controllers.Tlc59711
8 | {
9 | ///
10 | /// The Pulse-width modulation (PWM) channels.
11 | ///
12 | public interface IPwmChannels {
13 |
14 | #region Properties
15 |
16 | ///
17 | /// Indexer, which will allow client code to use [] notation on the class instance itself to modify PWM channel values.
18 | ///
19 | /// channel index
20 | /// The current PWM value from
21 | UInt16 this[int index] { get; set; }
22 |
23 | ///
24 | /// Returns the number of channels.
25 | ///
26 | int Count { get; }
27 |
28 | #endregion
29 |
30 | #region Methods
31 |
32 | ///
33 | /// Returns the PWM value at the specified channel .
34 | ///
35 | /// Channel index
36 | /// The PWM value at the specified channel
37 | UInt16 Get(int index);
38 |
39 | ///
40 | /// Sets the PWM value at channel .
41 | ///
42 | /// Channel index
43 | /// The PWM value
44 | void Set(int index, UInt16 value);
45 |
46 | #endregion
47 | }
48 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Controllers/Tlc59711/IPwmDevice.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Controllers.Tlc59711
2 | {
3 | ///
4 | /// A pulse-width modulation (PWM) device
5 | ///
6 | public interface IPwmDevice
7 | {
8 | #region Properties
9 |
10 | ///
11 | /// The PWM channels
12 | ///
13 | IPwmChannels Channels { get; }
14 |
15 | #endregion
16 | }
17 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Controllers/Tlc59711/ITlc59711Cluster.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System.Collections.Generic;
4 |
5 | #endregion
6 |
7 | namespace Pi.IO.Components.Controllers.Tlc59711
8 | {
9 | ///
10 | /// A chained cluster of Adafruit's 12-channel 16bit PWM/LED driver TLC59711.
11 | /// The devices should be connected together with their SDTI/SDTO pins.
12 | ///
13 | public interface ITlc59711Cluster : IEnumerable, IPwmDevice
14 | {
15 | #region Properties
16 |
17 | ///
18 | /// Number of TLC59711 devices chained together
19 | ///
20 | int Count { get; }
21 |
22 | ///
23 | /// Returns the TLC59711 device at the requested position
24 | ///
25 | /// TLC59711 index
26 | /// TLC59711 device
27 | ITlc59711Device this[int index] { get; }
28 |
29 | #endregion
30 |
31 | #region Methods
32 |
33 | ///
34 | /// Returns the TLC59711 device at the requested position
35 | ///
36 | /// TLC59711 index
37 | /// TLC59711 device
38 | ITlc59711Device Get(int index);
39 |
40 | ///
41 | /// Set BLANK on/off at all connected devices.
42 | ///
43 | /// If set to true all outputs are forced off.
44 | void Blank(bool blank);
45 |
46 | #endregion
47 | }
48 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Controllers/Tlc59711/ITlc59711Connection.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 |
5 | #endregion
6 |
7 | namespace Pi.IO.Components.Controllers.Tlc59711
8 | {
9 | ///
10 | /// A connection the one or more TLC59711 devices.
11 | ///
12 | public interface ITlc59711Connection : IDisposable
13 | {
14 | #region Properties
15 |
16 | ///
17 | /// A chained cluster of Adafruit's 12-channel 16bit PWM/LED driver TLC59711.
18 | ///
19 | ITlc59711Cluster Devices { get; }
20 |
21 | #endregion
22 |
23 | #region Methods
24 |
25 | ///
26 | /// Creates a TLC59711 command and sends it to the first device using the SPI bus.
27 | ///
28 | void Update();
29 |
30 | #endregion
31 | }
32 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Controllers/Tlc59711/ITlc59711Device.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Controllers.Tlc59711
2 | {
3 | ///
4 | /// Adafruit 12-Channel 16-bit PWM LED Driver TLC59711
5 | ///
6 | public interface ITlc59711Device : IPwmDevice, ITlc59711Settings
7 | {
8 | #region Methods
9 |
10 | ///
11 | /// Initializes the device with default values.
12 | ///
13 | void Reset();
14 |
15 | #endregion
16 | }
17 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Converters/Mcp3002/Mcp3002AnalogPinExtensionMethods.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Converters.Mcp3002
2 | {
3 | public static class Mcp3002AnalogPinExtensionMethods
4 | {
5 | #region Methods
6 |
7 | ///
8 | /// Creates an analog input pin.
9 | ///
10 | /// The connection.
11 | /// The channel.
12 | /// The pin.
13 | public static Mcp3002InputAnalogPin In(this Mcp3002SpiConnection connection, Mcp3002Channel channel)
14 | {
15 | return new Mcp3002InputAnalogPin(connection, channel);
16 | }
17 |
18 | #endregion
19 | }
20 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Converters/Mcp3002/Mcp3002Channel.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Converters.Mcp3002
2 | {
3 | public enum Mcp3002Channel
4 | {
5 | Channel0 = 0,
6 | Channel1 = 1
7 | }
8 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Converters/Mcp3002/Mcp3002InputAnalogPin.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Converters.Mcp3002
2 | {
3 | public class Mcp3002InputAnalogPin : IInputAnalogPin
4 | {
5 | #region Fields
6 |
7 | private readonly Mcp3002SpiConnection connection;
8 | private readonly Mcp3002Channel channel;
9 |
10 | #endregion
11 |
12 | #region Instance Management
13 |
14 | ///
15 | /// Initializes a new instance of the class.
16 | ///
17 | /// The connection.
18 | /// The channel.
19 | public Mcp3002InputAnalogPin(Mcp3002SpiConnection connection, Mcp3002Channel channel)
20 | {
21 | this.connection = connection;
22 | this.channel = channel;
23 | }
24 |
25 | ///
26 | /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
27 | ///
28 | public void Dispose(){}
29 |
30 | #endregion
31 |
32 | #region Methods
33 |
34 | ///
35 | /// Reads the value of the pin.
36 | ///
37 | ///
38 | /// The value.
39 | ///
40 | public AnalogValue Read()
41 | {
42 | return connection.Read(channel);
43 | }
44 |
45 | #endregion
46 | }
47 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Converters/Mcp3002/Mcp3002SpiConnection.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 | using Pi.IO.SerialPeripheralInterface;
5 |
6 | #endregion
7 |
8 | namespace Pi.IO.Components.Converters.Mcp3002
9 | {
10 | ///
11 | /// Represents a connection to MCP3002 ADC converter.
12 | ///
13 | public class Mcp3002SpiConnection : IDisposable
14 | {
15 | #region Fields
16 |
17 | private readonly SpiConnection spiConnection;
18 |
19 | #endregion
20 |
21 | #region Instance Management
22 |
23 | ///
24 | /// Initializes a new instance of the class.
25 | ///
26 | /// The clock pin.
27 | /// The slave select pin.
28 | /// The miso pin.
29 | /// The mosi pin.
30 | public Mcp3002SpiConnection(IOutputBinaryPin clockPin, IOutputBinaryPin slaveSelectPin, IInputBinaryPin misoPin, IOutputBinaryPin mosiPin)
31 | {
32 | spiConnection = new SpiConnection(clockPin, slaveSelectPin, misoPin, mosiPin, Endianness.LittleEndian);
33 | }
34 |
35 | ///
36 | /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
37 | ///
38 | void IDisposable.Dispose()
39 | {
40 | Close();
41 | }
42 |
43 | #endregion
44 |
45 | #region Methods
46 |
47 | ///
48 | /// Reads the specified channel.
49 | ///
50 | /// The channel.
51 | /// The value
52 | public AnalogValue Read(Mcp3002Channel channel)
53 | {
54 | using(spiConnection.SelectSlave())
55 | {
56 | // Start bit
57 | spiConnection.Write(true);
58 |
59 | // Channel is single-ended
60 | spiConnection.Write(true);
61 |
62 | // Channel Id
63 | spiConnection.Write((byte)channel, 1);
64 |
65 | // Let one clock to sample
66 | spiConnection.Synchronize();
67 |
68 | // Read 10 bits
69 | var data = (int)spiConnection.Read(10);
70 |
71 | return new AnalogValue(data, 0x3FF);
72 | }
73 | }
74 |
75 | ///
76 | /// Closes this instance.
77 | ///
78 | public void Close()
79 | {
80 | spiConnection.Close();
81 | }
82 |
83 | #endregion
84 | }
85 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Converters/Mcp3008/Mcp3008AnalogPinExtensionMethods.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Converters.Mcp3008
2 | {
3 | public static class Mcp3008AnalogPinExtensionMethods
4 | {
5 | #region Methods
6 |
7 | ///
8 | /// Creates an analog input pin.
9 | ///
10 | /// The connection.
11 | /// The channel.
12 | /// The pin.
13 | public static Mcp3008InputAnalogPin In(this Mcp3008SpiConnection connection, Mcp3008Channel channel)
14 | {
15 | return new Mcp3008InputAnalogPin(connection, channel);
16 | }
17 |
18 | #endregion
19 | }
20 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Converters/Mcp3008/Mcp3008Channel.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Converters.Mcp3008
2 | {
3 | public enum Mcp3008Channel
4 | {
5 | Channel0 = 0,
6 | Channel1 = 1,
7 | Channel2 = 2,
8 | Channel3 = 3,
9 | Channel4 = 4,
10 | Channel5 = 5,
11 | Channel6 = 6,
12 | Channel7 = 7
13 | }
14 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Converters/Mcp3008/Mcp3008InputAnalogPin.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Converters.Mcp3008
2 | {
3 | public class Mcp3008InputAnalogPin : IInputAnalogPin
4 | {
5 | #region Fields
6 |
7 | private readonly Mcp3008SpiConnection connection;
8 | private readonly Mcp3008Channel channel;
9 |
10 | #endregion
11 |
12 | #region Instance Management
13 |
14 | ///
15 | /// Initializes a new instance of the class.
16 | ///
17 | /// The connection.
18 | /// The channel.
19 | public Mcp3008InputAnalogPin(Mcp3008SpiConnection connection, Mcp3008Channel channel)
20 | {
21 | this.connection = connection;
22 | this.channel = channel;
23 | }
24 |
25 | ///
26 | /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
27 | ///
28 | public void Dispose(){}
29 |
30 | #endregion
31 |
32 | #region Methods
33 |
34 | ///
35 | /// Reads the value of the pin.
36 | ///
37 | ///
38 | /// The value.
39 | ///
40 | public AnalogValue Read()
41 | {
42 | return connection.Read(channel);
43 | }
44 |
45 | #endregion
46 | }
47 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Converters/Mcp3008/Mcp3008SpiConnection.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 | using Pi.IO.SerialPeripheralInterface;
5 |
6 | #endregion
7 |
8 | namespace Pi.IO.Components.Converters.Mcp3008
9 | {
10 | ///
11 | /// Represents a connection to MCP3004/3008 ADC converter.
12 | ///
13 | ///
14 | /// See specification at http://www.adafruit.com/datasheets/MCP3008.pdf
15 | ///
16 | public class Mcp3008SpiConnection : IDisposable
17 | {
18 | #region Fields
19 |
20 | private readonly SpiConnection spiConnection;
21 |
22 | #endregion
23 |
24 | #region Instance Management
25 |
26 | ///
27 | /// Initializes a new instance of the class.
28 | ///
29 | /// The clock pin.
30 | /// The slave select pin.
31 | /// The miso pin.
32 | /// The mosi pin.
33 | public Mcp3008SpiConnection(IOutputBinaryPin clockPin, IOutputBinaryPin slaveSelectPin, IInputBinaryPin misoPin, IOutputBinaryPin mosiPin)
34 | {
35 | spiConnection = new SpiConnection(clockPin, slaveSelectPin, misoPin, mosiPin, Endianness.LittleEndian);
36 | }
37 |
38 | ///
39 | /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
40 | ///
41 | void IDisposable.Dispose()
42 | {
43 | Close();
44 | }
45 |
46 | #endregion
47 |
48 | #region Methods
49 |
50 | ///
51 | /// Reads the specified channel.
52 | ///
53 | /// The channel.
54 | /// The value
55 | public AnalogValue Read(Mcp3008Channel channel)
56 | {
57 | using(spiConnection.SelectSlave())
58 | {
59 | // Start bit
60 | spiConnection.Write(true);
61 |
62 | // Channel is single-ended
63 | spiConnection.Write(true);
64 |
65 | // Channel Id
66 | spiConnection.Write((byte)channel, 3);
67 |
68 | // Let one clock to sample
69 | spiConnection.Synchronize();
70 |
71 | // Read 10 bits
72 | var data = (int)spiConnection.Read(10);
73 |
74 | return new AnalogValue(data, 0x3FF);
75 | }
76 | }
77 |
78 | ///
79 | /// Closes this instance.
80 | ///
81 | public void Close()
82 | {
83 | spiConnection.Close();
84 | }
85 |
86 | #endregion
87 | }
88 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Converters/Mcp3208/Mcp3208AnalogPinExtensionMethods.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Converters.Mcp3208
2 | {
3 | public static class Mcp3208AnalogPinExtensionMethods
4 | {
5 | #region Methods
6 |
7 | ///
8 | /// Creates an analog input pin.
9 | ///
10 | /// The connection.
11 | /// The channel.
12 | /// The pin.
13 | public static Mcp3208InputAnalogPin In(this Mcp3208SpiConnection connection, Mcp3208Channel channel)
14 | {
15 | return new Mcp3208InputAnalogPin(connection, channel);
16 | }
17 |
18 | #endregion
19 | }
20 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Converters/Mcp3208/Mcp3208Channel.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Converters.Mcp3208
2 | {
3 | public enum Mcp3208Channel
4 | {
5 | Channel0 = 0,
6 | Channel1 = 1,
7 | Channel2 = 2,
8 | Channel3 = 3,
9 | Channel4 = 4,
10 | Channel5 = 5,
11 | Channel6 = 6,
12 | Channel7 = 7
13 | }
14 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Converters/Mcp3208/Mcp3208InputAnalogPin.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Converters.Mcp3208
2 | {
3 | public class Mcp3208InputAnalogPin : IInputAnalogPin
4 | {
5 | #region Fields
6 |
7 | private readonly Mcp3208SpiConnection connection;
8 | private readonly Mcp3208Channel channel;
9 |
10 | #endregion
11 |
12 | #region Instance Management
13 |
14 | ///
15 | /// Initializes a new instance of the class.
16 | ///
17 | /// The connection.
18 | /// The channel.
19 | public Mcp3208InputAnalogPin(Mcp3208SpiConnection connection, Mcp3208Channel channel)
20 | {
21 | this.connection = connection;
22 | this.channel = channel;
23 | }
24 |
25 | ///
26 | /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
27 | ///
28 | public void Dispose(){}
29 |
30 | #endregion
31 |
32 | #region Methods
33 |
34 | ///
35 | /// Reads the value of the pin.
36 | ///
37 | ///
38 | /// The value.
39 | ///
40 | public AnalogValue Read()
41 | {
42 | return connection.Read(channel);
43 | }
44 |
45 | #endregion
46 | }
47 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Converters/Mcp3208/Mcp3208SpiConnection.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 | using Pi.IO.SerialPeripheralInterface;
5 |
6 | #endregion
7 |
8 | namespace Pi.IO.Components.Converters.Mcp3208
9 | {
10 | ///
11 | /// Represents a connection to MCP3204/3208 ADC converter.
12 | ///
13 | ///
14 | /// See specification at http://www.adafruit.com/datasheets/MCP3208.pdf
15 | ///
16 | public class Mcp3208SpiConnection : IDisposable
17 | {
18 | #region Fields
19 |
20 | private readonly SpiConnection spiConnection;
21 |
22 | #endregion
23 |
24 | #region Instance Management
25 |
26 | ///
27 | /// Initializes a new instance of the class.
28 | ///
29 | /// The clock pin.
30 | /// The slave select pin.
31 | /// The miso pin.
32 | /// The mosi pin.
33 | public Mcp3208SpiConnection(IOutputBinaryPin clockPin, IOutputBinaryPin slaveSelectPin, IInputBinaryPin misoPin, IOutputBinaryPin mosiPin)
34 | {
35 | spiConnection = new SpiConnection(clockPin, slaveSelectPin, misoPin, mosiPin, Endianness.LittleEndian);
36 | }
37 |
38 | ///
39 | /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
40 | ///
41 | void IDisposable.Dispose()
42 | {
43 | Close();
44 | }
45 |
46 | #endregion
47 |
48 | #region Methods
49 |
50 | ///
51 | /// Reads the specified channel.
52 | ///
53 | /// The channel.
54 | /// The value
55 | public AnalogValue Read(Mcp3208Channel channel)
56 | {
57 | using (spiConnection.SelectSlave())
58 | {
59 | // Start bit
60 | spiConnection.Write(true);
61 |
62 | // Channel is single-ended
63 | spiConnection.Write(true);
64 |
65 | spiConnection.Write((byte)channel, 3);
66 |
67 | // Let one clock to sample
68 | spiConnection.Synchronize();
69 |
70 | // Read 12 bits
71 | var data = (int)spiConnection.Read(12);
72 |
73 | return new AnalogValue(data, 0xFFF);
74 | }
75 | }
76 |
77 | ///
78 | /// Closes this instance.
79 | ///
80 | public void Close()
81 | {
82 | spiConnection.Close();
83 | }
84 |
85 | #endregion
86 | }
87 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Converters/Mcp4822/Mcp4822AnalogPinExtensionMethods.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Converters.Mcp4822
2 | {
3 | public static class Mcp4822AnalogPinExtensionMethods
4 | {
5 | #region Methods
6 |
7 | ///
8 | /// Creates an output analog pin.
9 | ///
10 | /// The connection.
11 | /// The channel.
12 | /// The maximum.
13 | /// The pin.
14 | public static Mcp4822OutputAnalogPin Out(this Mcp4822SpiConnection connection, Mcp4822Channel channel)
15 | {
16 | return new Mcp4822OutputAnalogPin(connection, channel);
17 | }
18 |
19 | #endregion
20 | }
21 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Converters/Mcp4822/Mcp4822Channel.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Converters.Mcp4822
2 | {
3 | public enum Mcp4822Channel
4 | {
5 | ChannelA = 0,
6 | ChannelB = 1
7 | }
8 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Converters/Mcp4822/Mcp4822OutputAnalogPin.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Converters.Mcp4822
2 | {
3 | public class Mcp4822OutputAnalogPin : IOutputAnalogPin
4 | {
5 | #region Fields
6 |
7 | private readonly Mcp4822SpiConnection connection;
8 | private readonly Mcp4822Channel channel;
9 |
10 | #endregion
11 |
12 | #region Instance Management
13 |
14 | ///
15 | /// Initializes a new instance of the class.
16 | ///
17 | /// The connection.
18 | /// The channel.
19 | public Mcp4822OutputAnalogPin(Mcp4822SpiConnection connection, Mcp4822Channel channel)
20 | {
21 | this.connection = connection;
22 | this.channel = channel;
23 | }
24 |
25 | ///
26 | /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
27 | ///
28 | public void Dispose()
29 | {
30 | }
31 |
32 | #endregion
33 |
34 | #region Methods
35 |
36 | ///
37 | /// Writes the specified value to the pin.
38 | ///
39 | /// The value.
40 | public void Write(AnalogValue value)
41 | {
42 | connection.Write(channel, value);
43 | }
44 |
45 | #endregion
46 | }
47 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Converters/Mcp4822/Mcp4822SpiConnection.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 | using Pi.IO.SerialPeripheralInterface;
5 |
6 | #endregion
7 |
8 | namespace Pi.IO.Components.Converters.Mcp4822
9 | {
10 | ///
11 | /// Represents a SPI connection to a MCP4802/4812/4822 DAC.
12 | ///
13 | /// See http://ww1.microchip.com/downloads/en/DeviceDoc/22249A.pdf for specifications.
14 | public class Mcp4822SpiConnection : IDisposable
15 | {
16 | #region Fields
17 |
18 | private readonly SpiConnection spiConnection;
19 |
20 | #endregion
21 |
22 | #region Instance Management
23 |
24 | ///
25 | /// Initializes a new instance of the class.
26 | ///
27 | /// The clock pin.
28 | /// The slave select pin.
29 | /// The mosi pin.
30 | public Mcp4822SpiConnection(IOutputBinaryPin clockPin, IOutputBinaryPin slaveSelectPin, IOutputBinaryPin mosiPin)
31 | {
32 | spiConnection = new SpiConnection(clockPin, slaveSelectPin, null, mosiPin, Endianness.LittleEndian);
33 | }
34 |
35 | ///
36 | /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
37 | ///
38 | void IDisposable.Dispose()
39 | {
40 | Close();
41 | }
42 |
43 | #endregion
44 |
45 | #region Methods
46 |
47 | ///
48 | /// Closes this instance.
49 | ///
50 | public void Close()
51 | {
52 | spiConnection.Close();
53 | }
54 |
55 | ///
56 | /// Writes the specified data.
57 | ///
58 | /// The channel.
59 | /// The data.
60 | public void Write(Mcp4822Channel channel, AnalogValue data)
61 | {
62 | using (spiConnection.SelectSlave())
63 | {
64 | var value = (uint)(data.Relative * 0xFFF);
65 | if (value > 0xFFF)
66 | value = 0xFFF;
67 |
68 | // Set active channel
69 | spiConnection.Write(channel == Mcp4822Channel.ChannelB);
70 |
71 | // Ignored bit
72 | spiConnection.Synchronize();
73 |
74 | // Select 1x Gain
75 | spiConnection.Write(true);
76 |
77 | // Active mode operation
78 | spiConnection.Write(true);
79 |
80 | // Write 12 bits data (some lower bits are ignored by MCP4802/4812
81 | spiConnection.Write(value, 12);
82 | }
83 | }
84 |
85 | #endregion
86 | }
87 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Devices/PiFaceDigital/InputPinChangedArgs.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace Pi.IO.Components.Devices.PiFaceDigital
7 | {
8 | public class InputPinChangedArgs : EventArgs
9 | {
10 | public PiFaceInputPin pin;
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/Pi.IO.Components/Devices/PiFaceDigital/InputPinChangedHandler.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace Pi.IO.Components.Devices.PiFaceDigital
7 | {
8 | ///
9 | /// delgate for pin state changed events. The pin that changed is in the args
10 | ///
11 | ///
12 | ///
13 | public delegate void InputPinChangedHandler (object sender, InputPinChangedArgs e);
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/Pi.IO.Components/Devices/PiFaceDigital/PiFaceInputPin.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace Pi.IO.Components.Devices.PiFaceDigital
7 | {
8 | public class PiFaceInputPin : PiFacePin
9 | {
10 |
11 | #region events
12 | ///
13 | /// Event fired when the state of a pin changes
14 | ///
15 | public event InputPinChangedHandler OnStateChanged;
16 |
17 | #endregion
18 |
19 | #region Instance Management
20 |
21 | ///
22 | /// Initializes a new instance of the class.
23 | ///
24 | /// Number of the pin in the range 0 to 7
25 | internal PiFaceInputPin(int pinNumber)
26 | : base(pinNumber)
27 | {
28 | }
29 |
30 | #endregion
31 |
32 | #region Properties
33 |
34 | ///
35 | /// Indicates that sensor grounding the input pin is closed
36 | ///
37 | public bool IsGrounded { get { return !state; } }
38 |
39 | ///
40 | /// Gets the state of the pin, note true indicates the pin is high i.e. open.
41 | /// if this throws off your logic use the IsGrounded property instead.
42 | ///
43 | public bool State
44 | {
45 | get { return state; }
46 | }
47 |
48 | #endregion
49 |
50 | #region Methods
51 |
52 | ///
53 | /// Update the state of this pin based on a byte that contains the state of every pin
54 | ///
55 | /// byte with all pin values
56 | internal override void Update(byte allPinState)
57 | {
58 | var oldState = state;
59 | state = (allPinState & mask) > 0;
60 | if (oldState != state && OnStateChanged != null)
61 | {
62 | OnStateChanged(this, new InputPinChangedArgs { pin = this });
63 | }
64 | }
65 |
66 | ///
67 | /// helper to set the state of every pin in a collection
68 | ///
69 | ///
70 | ///
71 | internal static void SetAllPinStates(IEnumerable inputPins, byte allPinState)
72 | {
73 | foreach (var inputPin in inputPins)
74 | {
75 | inputPin.Update(allPinState);
76 | }
77 | }
78 |
79 | #endregion
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/Pi.IO.Components/Devices/PiFaceDigital/PiFaceOutputPin.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace Pi.IO.Components.Devices.PiFaceDigital
7 | {
8 | ///
9 | /// Derivative of PiFacePin that allows setting of the internal state
10 | ///
11 | public class PiFaceOutputPin : PiFacePin
12 | {
13 | #region Instance Management
14 |
15 | ///
16 | /// Initializes a new instance of the class.
17 | ///
18 | /// Number of the pin in the range 0 to 7
19 | internal PiFaceOutputPin(int pinNumber)
20 | : base(pinNumber)
21 | {
22 | }
23 |
24 | #endregion
25 |
26 | #region Properties
27 |
28 | ///
29 | /// Gets/Sets the state of the pin in software but does not update the PiFaceDigital device
30 | /// Allows individual pins to be modified then everything updated with a call to UpdatePiFaceOutputPins
31 | ///
32 | public bool State
33 | {
34 | get { return state; }
35 | set { state = value; }
36 | }
37 |
38 | #endregion
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/Pi.IO.Components/Devices/PiFaceDigital/PiFacePin.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace Pi.IO.Components.Devices.PiFaceDigital
7 | {
8 | ///
9 | /// Represents the pins on a PiFace Digital board
10 | ///
11 | public abstract class PiFacePin
12 | {
13 |
14 |
15 | #region Fields
16 |
17 | ///
18 | /// bit mask that allows this pin to get / set it's value from a byte
19 | ///
20 | protected byte mask;
21 |
22 | ///
23 | /// state of this pin
24 | ///
25 | protected bool state;
26 |
27 | #endregion
28 |
29 |
30 |
31 | #region Instance Management
32 |
33 | ///
34 | /// Initializes a new instance of the class.
35 | ///
36 | /// Number of the pin in the range 0 to 7
37 | internal PiFacePin(int pinNumber)
38 | {
39 | if (pinNumber < 0 || pinNumber > 7)
40 | {
41 | throw new ArgumentOutOfRangeException("pin numbers must be in the range 0 to 7");
42 | }
43 | mask = (byte)(1 << pinNumber);
44 | Id = pinNumber;
45 | }
46 |
47 | #endregion
48 |
49 | #region Properties
50 |
51 | ///
52 | /// Number of the pin 0..7
53 | ///
54 | public int Id { get; private set; }
55 |
56 | #endregion
57 |
58 | #region Methods
59 |
60 | ///
61 | /// Update this pin based on a byte that contains the data for every pin
62 | ///
63 | /// byte with all pin values
64 | internal virtual void Update(byte allPinState)
65 | {
66 | state = (allPinState & mask) > 0;
67 | }
68 |
69 | ///
70 | /// Returns a byte representing the state of all pins
71 | ///
72 | /// collection of pins to aggregate over
73 | /// byte of all pin state
74 | internal static byte AllPinState(IEnumerable pins)
75 | {
76 | byte allPinState = 0;
77 | foreach (var pin in pins)
78 | {
79 | if (pin.state)
80 | {
81 | allPinState = (byte)(allPinState | pin.mask);
82 | }
83 | }
84 | return allPinState;
85 | }
86 |
87 |
88 | #endregion
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/Pi.IO.Components/Displays/Hd44780/Command.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Displays.Hd44780
2 | {
3 | internal enum Command
4 | {
5 | ClearDisplay = 0x01,
6 | ReturnHome = 0x02,
7 | SetEntryModeFlags = 0x04,
8 | SetDisplayFlags = 0x08,
9 | MoveCursor = 0x10,
10 | SetFunctions = 0x20,
11 | SetCGRamAddr = 0x40,
12 | //SetDDRamAddr = 0x80
13 | }
14 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Displays/Hd44780/CursorShiftFlags.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Pi.IO.Components.Displays.Hd44780
4 | {
5 | [Flags]
6 | internal enum CursorShiftFlags
7 | {
8 | None = 0,
9 |
10 | CursorMove = 0,
11 | MoveLeft = 0,
12 |
13 | MoveRight = 0x04,
14 | DisplayMove = 0x08
15 | }
16 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Displays/Hd44780/DisplayFlags.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Pi.IO.Components.Displays.Hd44780
4 | {
5 | [Flags]
6 | internal enum DisplayFlags
7 | {
8 | None = 0,
9 |
10 | BlinkOff = 0,
11 | CursorOff = 0,
12 | DisplayOff = 0,
13 |
14 | BlinkOn = 0x01,
15 | CursorOn = 0x02,
16 | DisplayOn = 0x04
17 | }
18 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Displays/Hd44780/EntryModeFlags.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Pi.IO.Components.Displays.Hd44780
4 | {
5 | [Flags]
6 | internal enum EntryModeFlags
7 | {
8 | None = 0,
9 |
10 | EntryRight = 0,
11 | EntryShiftDecrement = 0,
12 |
13 | EntryShiftIncrement = 0x01,
14 | EntryLeft = 0x02
15 | }
16 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Displays/Hd44780/Functions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Pi.IO.Components.Displays.Hd44780
4 | {
5 | [Flags]
6 | internal enum Functions
7 | {
8 | None = 0,
9 |
10 | Matrix5x8 = 0,
11 | Matrix5x10 = 0x04,
12 |
13 | OneLine = 0,
14 | TwoLines = 0x08,
15 |
16 | Data4bits = 0x0,
17 | Data8bits = 0x10,
18 | }
19 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Displays/Hd44780/Hd44780LcdConnectionSettings.cs:
--------------------------------------------------------------------------------
1 | using System.Text;
2 |
3 | namespace Pi.IO.Components.Displays.Hd44780
4 | {
5 | public class Hd44780LcdConnectionSettings
6 | {
7 | #region Instance Management
8 |
9 | ///
10 | /// Initializes a new instance of the class.
11 | ///
12 | public Hd44780LcdConnectionSettings()
13 | {
14 | ScreenWidth = 20;
15 | ScreenHeight = 2;
16 | PatternWidth = 5;
17 | PatternHeight = 8;
18 |
19 | Encoding = new Hd44780A00Encoding();
20 | //RightToLeft = false;
21 | }
22 |
23 | #endregion
24 |
25 | #region Properties
26 |
27 | ///
28 | /// Gets or sets the width of the screen.
29 | ///
30 | ///
31 | /// The width of the screen.
32 | ///
33 | public int ScreenWidth { get; set; }
34 |
35 | ///
36 | /// Gets or sets the height of the screen.
37 | ///
38 | ///
39 | /// The height of the screen.
40 | ///
41 | public int ScreenHeight { get; set; }
42 |
43 | ///
44 | /// Gets or sets the width of the pattern.
45 | ///
46 | ///
47 | /// The width of the pattern.
48 | ///
49 | public int PatternWidth { get; set; }
50 |
51 | ///
52 | /// Gets or sets the height of the pattern.
53 | ///
54 | ///
55 | /// The height of the pattern.
56 | ///
57 | public int PatternHeight { get; set; }
58 |
59 | ///
60 | /// Gets or sets the encoding.
61 | ///
62 | ///
63 | /// The encoding.
64 | ///
65 | public Encoding Encoding { get; set; }
66 |
67 | //public bool RightToLeft { get; set; }
68 |
69 | #endregion
70 | }
71 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Displays/Hd44780/Hd44780Pins.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Linq;
6 |
7 | #endregion
8 |
9 | namespace Pi.IO.Components.Displays.Hd44780
10 | {
11 | ///
12 | /// Represents the pins of a HD44780 LCD display.
13 | ///
14 | public class Hd44780Pins : IDisposable
15 | {
16 | #region Instance Management
17 |
18 | ///
19 | /// Initializes a new instance of the class.
20 | ///
21 | /// The register select.
22 | /// The clock.
23 | /// The data.
24 | public Hd44780Pins(IOutputBinaryPin registerSelect, IOutputBinaryPin clock, IEnumerable data)
25 | : this(registerSelect, clock, data.ToArray())
26 | {
27 | }
28 |
29 | ///
30 | /// Initializes a new instance of the class.
31 | ///
32 | /// The register select.
33 | /// The clock.
34 | /// The data.
35 | public Hd44780Pins(IOutputBinaryPin registerSelect, IOutputBinaryPin clock, params IOutputBinaryPin[] data)
36 | {
37 | RegisterSelect = registerSelect;
38 | Clock = clock;
39 | Data = data;
40 | }
41 |
42 | ///
43 | /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
44 | ///
45 | void IDisposable.Dispose()
46 | {
47 | Close();
48 | }
49 |
50 | #endregion
51 |
52 | #region Properties
53 |
54 | ///
55 | /// The register select (RS) pin.
56 | ///
57 | public IOutputBinaryPin RegisterSelect { get; private set; }
58 |
59 | ///
60 | /// The clock (EN) pin.
61 | ///
62 | public IOutputBinaryPin Clock { get; private set; }
63 |
64 | ///
65 | /// The backlight pin.
66 | ///
67 | public IOutputBinaryPin Backlight;
68 |
69 | ///
70 | /// The read write (RW) pin.
71 | ///
72 | public IOutputBinaryPin ReadWrite;
73 |
74 | ///
75 | /// The data pins.
76 | ///
77 | public IOutputBinaryPin[] Data { get; private set; }
78 |
79 | #endregion
80 |
81 | #region Methods
82 |
83 | ///
84 | /// Closes this instance.
85 | ///
86 | public void Close()
87 | {
88 |
89 | RegisterSelect.Dispose();
90 | Clock.Dispose();
91 |
92 | if (Backlight != null)
93 | Backlight.Dispose();
94 | if (ReadWrite != null)
95 | ReadWrite.Dispose();
96 |
97 | foreach (var dataPin in Data)
98 | dataPin.Dispose();
99 | }
100 |
101 | #endregion
102 |
103 | }
104 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Displays/Hd44780/Hd44780Position.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Displays.Hd44780
2 | {
3 | ///
4 | /// Represents the position of the cursor on a Hd44780 display.
5 | ///
6 | public struct Hd44780Position
7 | {
8 | public int Row;
9 | public int Column;
10 |
11 | public static Hd44780Position Zero = new Hd44780Position {Row = 0, Column = 0};
12 | }
13 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Displays/Sda5708/Sda5708Brightness.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Pi.IO.Components.Displays.Sda5708
4 | {
5 | public enum Sda5708Brightness
6 | {
7 | Level100 = 0,
8 | Level53 = 1,
9 | Level40 = 2,
10 | Level27 = 3,
11 | Level20 = 4,
12 | Level13 = 5,
13 | Level6_6 = 6,
14 | Level0 = 7
15 | }
16 | }
17 |
18 |
--------------------------------------------------------------------------------
/Pi.IO.Components/Displays/Sda5708/Sda5708Connection.cs:
--------------------------------------------------------------------------------
1 | /* Sda5708Connection
2 | * Parts of this code are ported from https://github.com/pimium/sda5708
3 | * which in turn used the information from http://www.sbprojects.com/knowledge/footprints/sda5708.php.
4 | * The font is taken from http://sunge.awardspace.com/glcd-sd/node4.html
5 | * with additional german characters added. */
6 | using System;
7 | using System.IO;
8 | using System.Text;
9 | using System.Linq;
10 | using System.Threading;
11 | using Pi.IO;
12 | using Pi.IO.GeneralPurpose;
13 | using System.Collections.Generic;
14 |
15 | namespace Pi.IO.Components.Displays.Sda5708
16 | {
17 | public sealed class Sda5708Connection : IDisposable
18 | {
19 | private Sda5708Brightness _brightness = Sda5708Brightness.Level100;
20 |
21 | private readonly ProcessorPin _load;
22 | private readonly ProcessorPin _data;
23 | private readonly ProcessorPin _sdclk;
24 | private readonly ProcessorPin _reset;
25 | private readonly GpioConnection _baseConnection;
26 |
27 | public Sda5708Connection () : this(
28 | ProcessorPin.Pin7,
29 | ProcessorPin.Pin8,
30 | ProcessorPin.Pin18,
31 | ProcessorPin.Pin23)
32 | {
33 | }
34 |
35 | public Sda5708Connection (ProcessorPin load, ProcessorPin data, ProcessorPin sdclk, ProcessorPin reset)
36 | {
37 | this._load = load;
38 | this._data = data;
39 | this._sdclk = sdclk;
40 | this._reset = reset;
41 |
42 | this._baseConnection = new GpioConnection (
43 | load.Output (),
44 | data.Output (),
45 | sdclk.Output (),
46 | reset.Output ());
47 |
48 | this._baseConnection [reset] = false;
49 | this._baseConnection [reset] = false;
50 | Thread.Sleep (50);
51 | this._baseConnection [reset] = true;
52 |
53 | this.Clear();
54 | }
55 |
56 | public void SetBrightness(Sda5708Brightness brightness)
57 | {
58 | this._brightness = brightness;
59 | this.Write(0xe0 | (int)brightness);
60 | }
61 |
62 | public void Clear()
63 | {
64 | this.Write(0xc0 | (int)this._brightness);
65 | }
66 |
67 | public void WriteString(string str)
68 | {
69 | var chars = str
70 | .PadRight (8, ' ')
71 | .Substring (0, 8);
72 |
73 | for(var i = 0; i < chars.Length; i++)
74 | {
75 | this.WriteChar (i, chars [i]);
76 | }
77 | }
78 |
79 | private void WriteChar(int position, char value)
80 | {
81 | this.Write(0xa0 + position);
82 |
83 | string[] pattern;
84 | if (!Sda5708Font.Patterns.TryGetValue(value, out pattern))
85 | pattern = Sda5708Font.Patterns['?'];
86 |
87 | for(var i = 0; i < 7; i++)
88 | {
89 | this.Write (Convert.ToInt32 (pattern[i].Replace (' ', '0'), 2));
90 | }
91 | }
92 |
93 | private void Write(int value)
94 | {
95 | this._baseConnection [this._sdclk] = false;
96 | this._baseConnection [this._load] = false;
97 |
98 | for(var i = 8; i > 0; i--)
99 | {
100 | this._baseConnection[this._data] = (value & 0x1) == 0x1;
101 |
102 | this._baseConnection [this._sdclk] = true;
103 | this._baseConnection [this._sdclk] = false;
104 |
105 | value = value >> 1;
106 | }
107 |
108 | this._baseConnection [this._sdclk] = false;
109 | this._baseConnection [this._load] = true;
110 | }
111 |
112 | #region IDisposable implementation
113 | public void Dispose ()
114 | {
115 | this._baseConnection [this._reset] = false;
116 | ((IDisposable)this._baseConnection).Dispose ();
117 | }
118 | #endregion
119 | }
120 | }
121 |
--------------------------------------------------------------------------------
/Pi.IO.Components/Displays/Ssd1306/Command.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Displays.Ssd1306
2 | {
3 | public class Command
4 | {
5 | public const byte SetContrast = 0x81;
6 | //
7 | public const byte DisplayAllOnResume = 0xA4;
8 | public const byte DisplayAllOn = 0xA5;
9 | public const byte DisplayNormal = 0xA6;
10 | public const byte DisplayInvert = 0xA7;
11 | public const byte DisplayOff = 0xAE;
12 | public const byte DisplayOn = 0xAF;
13 | //
14 | public const byte SetDisplayOffset = 0xD3;
15 | public const byte SetComPins = 0xDA;
16 | public const byte SetVComDetect = 0xDB;
17 | public const byte SetDisplayClockDivider = 0xD5;
18 | public const byte SetPreCharge = 0xD9;
19 | public const byte SetMultiplex = 0xA8;
20 | public const byte SetLowColumn = 0x00;
21 | public const byte SetHighColumn = 0x10;
22 | public const byte SetStartLine = 0x40;
23 | public const byte MemoryMode = 0x20;
24 | public const byte ColumnAddress = 0x21;
25 | public const byte PageAddress = 0x22;
26 | //
27 | public const byte ActivateScroll = 0x2F;
28 | public const byte DeactivateScroll = 0x2E;
29 | public const byte SetVerticalScrollArea = 0xA3;
30 | public const byte SetScrollDirection = 0x25;
31 | //
32 | public const byte ComScanIncrement = 0xC0;
33 | public const byte ComScanDecrement = 0xC8;
34 | public const byte SegRemap = 0xA0;
35 | public const byte ChargePump = 0x8D;
36 | public const byte ExternalVcc = 0x1;
37 | public const byte SwitchCapVcc = 0x2;
38 | }
39 | }
40 |
41 |
--------------------------------------------------------------------------------
/Pi.IO.Components/Displays/Ssd1306/Fonts/IFont.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Pi.IO.Components.Displays.Ssd1306.Fonts
4 | {
5 | public interface IFont
6 | {
7 | byte[][] GetData();
8 | }
9 | }
10 |
11 |
--------------------------------------------------------------------------------
/Pi.IO.Components/Displays/Ssd1306/ScrollDirection.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Pi.IO.Components.Displays.Ssd1306
4 | {
5 | [Flags]
6 | public enum ScrollDirection : byte
7 | {
8 | HorizontalRight = 0x01,
9 | HorizontalLeft = 0x02,
10 | VerticalAndHorizontalRight = 0x04,
11 | VerticalAndHorizontalLeft = 0x05
12 | }
13 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Displays/Ssd1306/ScrollSpeed.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Pi.IO.Components.Displays.Ssd1306
4 | {
5 | [Flags]
6 | public enum ScrollSpeed : byte
7 | {
8 | F2 = 0x7,
9 | F3 = 0x4,
10 | F4 = 0x5,
11 | F5 = 0x0,
12 | F25 = 0x6,
13 | F64 = 0x1,
14 | F128 = 0x2,
15 | F256 = 0x3
16 | }
17 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Expanders/Mcp23008/Mcp23008InputBinaryPin.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 |
5 | #endregion
6 |
7 | namespace Pi.IO.Components.Expanders.Mcp23008
8 | {
9 | ///
10 | /// Represents a binary intput pin on a MCP23017 I/O expander.
11 | ///
12 | public class Mcp23008InputBinaryPin : IInputBinaryPin
13 | {
14 | #region Fields
15 |
16 | private readonly Mcp23008I2cConnection connection;
17 | private readonly Mcp23008Pin pin;
18 |
19 | ///
20 | /// The default timeout (5 seconds).
21 | ///
22 | public static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(5);
23 |
24 | #endregion
25 |
26 | #region Instance Management
27 |
28 | ///
29 | /// Initializes a new instance of the class.
30 | ///
31 | /// The connection.
32 | /// The pin.
33 | /// The resistor.
34 | /// The polarity.
35 | public Mcp23008InputBinaryPin(Mcp23008I2cConnection connection, Mcp23008Pin pin,
36 | Mcp23008PinResistor resistor = Mcp23008PinResistor.None,
37 | Mcp23008PinPolarity polarity = Mcp23008PinPolarity.Normal)
38 | {
39 | this.connection = connection;
40 | this.pin = pin;
41 |
42 | connection.SetDirection(pin, Mcp23008PinDirection.Input);
43 | connection.SetResistor(pin, resistor);
44 | connection.SetPolarity(pin, polarity);
45 | }
46 |
47 | ///
48 | /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
49 | ///
50 | public void Dispose(){}
51 |
52 | #endregion
53 |
54 | #region Methods
55 |
56 | ///
57 | /// Reads the state of the pin.
58 | ///
59 | ///
60 | /// true if the pin is in high state; otherwise, false.
61 | ///
62 | public bool Read()
63 | {
64 | return connection.GetPinStatus(pin);
65 | }
66 |
67 | ///
68 | /// Waits for the specified pin to be in the specified state.
69 | ///
70 | /// if set to true waits for the pin to be up. Default value is true.
71 | /// The timeout. Default value is .
72 | /// If timeout is set to , a default timeout is used instead.
73 | public void Wait(bool waitForUp = true, TimeSpan timeout = new TimeSpan())
74 | {
75 | var startWait = DateTime.UtcNow;
76 | if (timeout == TimeSpan.Zero)
77 | timeout = DefaultTimeout;
78 |
79 | while (Read() != waitForUp)
80 | {
81 | if (DateTime.UtcNow - startWait >= timeout)
82 | throw new TimeoutException("A timeout occurred while waiting for pin status to change");
83 | }
84 | }
85 |
86 | #endregion
87 |
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/Pi.IO.Components/Expanders/Mcp23008/Mcp23008OutputBinaryPin.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Pi.IO.Components.Expanders.Mcp23008
4 | {
5 | ///
6 | /// Represents a binary output pin on a MCP23008 I/O expander.
7 | ///
8 | public class Mcp23008OutputBinaryPin : IOutputBinaryPin
9 | {
10 | #region Properties
11 |
12 | private readonly Mcp23008I2cConnection connection;
13 | private readonly Mcp23008Pin pin;
14 |
15 | #endregion
16 |
17 | #region Instance Management
18 |
19 | ///
20 | /// Initializes a new instance of the class.
21 | ///
22 | /// The connection.
23 | /// The pin.
24 | /// The resistor.
25 | /// The polarity.
26 | public Mcp23008OutputBinaryPin(Mcp23008I2cConnection connection, Mcp23008Pin pin,
27 | Mcp23008PinResistor resistor = Mcp23008PinResistor.None,
28 | Mcp23008PinPolarity polarity = Mcp23008PinPolarity.Normal)
29 | {
30 | this.connection = connection;
31 | this.pin = pin;
32 |
33 | connection.SetDirection(pin, Mcp23008PinDirection.Output);
34 | connection.SetResistor(pin, resistor);
35 | connection.SetPolarity(pin, polarity);
36 | }
37 |
38 | ///
39 | /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
40 | ///
41 | public void Dispose(){}
42 |
43 | #endregion
44 |
45 | #region Methods
46 |
47 | ///
48 | /// Writes the value of the pin.
49 | ///
50 | /// if set to true, pin is set to high state.
51 | public void Write(bool state)
52 | {
53 | connection.SetPinStatus(pin, state);
54 | }
55 |
56 | #endregion
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/Pi.IO.Components/Expanders/Mcp23008/Mcp23008Pin.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Expanders.Mcp23008
2 | {
3 | public enum Mcp23008Pin
4 | {
5 | Pin0 = 0x0001,
6 | Pin1 = 0x0002,
7 | Pin2 = 0x0004,
8 | Pin3 = 0x0008,
9 | Pin4 = 0x0010,
10 | Pin5 = 0x0020,
11 | Pin6 = 0x0040,
12 | Pin7 = 0x0080
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/Pi.IO.Components/Expanders/Mcp23008/Mcp23008PinDirection.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Expanders.Mcp23008
2 | {
3 | public enum Mcp23008PinDirection
4 | {
5 | Input,
6 | Output
7 | }
8 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Expanders/Mcp23008/Mcp23008PinExtensionMethods.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Expanders.Mcp23008
2 | {
3 | ///
4 | /// Provides extension methods for MCP23008 pins.
5 | ///
6 | public static class Mcp23008PinExtensionMethods
7 | {
8 | #region Methods
9 |
10 | ///
11 | /// Creates an output binary pin.
12 | ///
13 | /// The connection.
14 | /// The pin.
15 | /// The resistor.
16 | /// The polarity.
17 | /// The pin.
18 | public static Mcp23008OutputBinaryPin Out(this Mcp23008I2cConnection connection, Mcp23008Pin pin, Mcp23008PinResistor resistor = Mcp23008PinResistor.None, Mcp23008PinPolarity polarity = Mcp23008PinPolarity.Normal)
19 | {
20 | return new Mcp23008OutputBinaryPin(connection, pin, resistor, polarity);
21 | }
22 |
23 | ///
24 | /// Creates an input binary pin.
25 | ///
26 | /// The connection.
27 | /// The pin.
28 | /// The resistor.
29 | /// The polarity.
30 | /// The pin.
31 | public static Mcp23008InputBinaryPin In(this Mcp23008I2cConnection connection, Mcp23008Pin pin, Mcp23008PinResistor resistor = Mcp23008PinResistor.None, Mcp23008PinPolarity polarity = Mcp23008PinPolarity.Normal)
32 | {
33 | return new Mcp23008InputBinaryPin(connection, pin, resistor, polarity);
34 | }
35 |
36 | #endregion
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/Pi.IO.Components/Expanders/Mcp23008/Mcp23008PinPolarity.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Expanders.Mcp23008
2 | {
3 | public enum Mcp23008PinPolarity
4 | {
5 | Normal,
6 | Inverted
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/Pi.IO.Components/Expanders/Mcp23008/Mcp23008PinResistor.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Expanders.Mcp23008
2 | {
3 | public enum Mcp23008PinResistor
4 | {
5 | None,
6 | PullUp
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/Pi.IO.Components/Expanders/Mcp23017/Mcp23017InputBinaryPin.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 |
5 | #endregion
6 |
7 | namespace Pi.IO.Components.Expanders.Mcp23017
8 | {
9 | ///
10 | /// Represents a binary intput pin on a MCP23017 I/O expander.
11 | ///
12 | public class Mcp23017InputBinaryPin : IInputBinaryPin
13 | {
14 | #region Fields
15 |
16 | private readonly Mcp23017I2cConnection connection;
17 | private readonly Mcp23017Pin pin;
18 |
19 | ///
20 | /// The default timeout (5 seconds).
21 | ///
22 | public static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(5);
23 |
24 | #endregion
25 |
26 | #region Instance Management
27 |
28 | ///
29 | /// Initializes a new instance of the class.
30 | ///
31 | /// The connection.
32 | /// The pin.
33 | /// The resistor.
34 | /// The polarity.
35 | public Mcp23017InputBinaryPin(Mcp23017I2cConnection connection, Mcp23017Pin pin,
36 | Mcp23017PinResistor resistor = Mcp23017PinResistor.None,
37 | Mcp23017PinPolarity polarity = Mcp23017PinPolarity.Normal)
38 | {
39 | this.connection = connection;
40 | this.pin = pin;
41 |
42 | connection.SetDirection(pin, Mcp23017PinDirection.Input);
43 | connection.SetResistor(pin, resistor);
44 | connection.SetPolarity(pin, polarity);
45 | }
46 |
47 | ///
48 | /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
49 | ///
50 | public void Dispose(){}
51 |
52 | #endregion
53 |
54 | #region Methods
55 |
56 | ///
57 | /// Reads the state of the pin.
58 | ///
59 | ///
60 | /// true if the pin is in high state; otherwise, false.
61 | ///
62 | public bool Read()
63 | {
64 | return connection.GetPinStatus(pin);
65 | }
66 |
67 | ///
68 | /// Waits for the specified pin to be in the specified state.
69 | ///
70 | /// if set to true waits for the pin to be up. Default value is true.
71 | /// The timeout. Default value is .
72 | /// If timeout is set to , a default timeout is used instead.
73 | public void Wait(bool waitForUp = true, TimeSpan timeout = new TimeSpan())
74 | {
75 | var startWait = DateTime.UtcNow;
76 | if (timeout == TimeSpan.Zero)
77 | timeout = DefaultTimeout;
78 |
79 | while (Read() != waitForUp)
80 | {
81 | if (DateTime.UtcNow - startWait >= timeout)
82 | throw new TimeoutException("A timeout occurred while waiting for pin status to change");
83 | }
84 | }
85 |
86 | #endregion
87 | }
88 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Expanders/Mcp23017/Mcp23017OutputBinaryPin.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Pi.IO.Components.Expanders.Mcp23017
4 | {
5 | ///
6 | /// Represents a binary output pin on a MCP23017 I/O expander.
7 | ///
8 | public class Mcp23017OutputBinaryPin : IOutputBinaryPin
9 | {
10 | #region Properties
11 |
12 | private readonly Mcp23017I2cConnection connection;
13 | private readonly Mcp23017Pin pin;
14 |
15 | #endregion
16 |
17 | #region Instance Management
18 |
19 | ///
20 | /// Initializes a new instance of the class.
21 | ///
22 | /// The connection.
23 | /// The pin.
24 | /// The resistor.
25 | /// The polarity.
26 | public Mcp23017OutputBinaryPin(Mcp23017I2cConnection connection, Mcp23017Pin pin,
27 | Mcp23017PinResistor resistor = Mcp23017PinResistor.None,
28 | Mcp23017PinPolarity polarity = Mcp23017PinPolarity.Normal)
29 | {
30 | this.connection = connection;
31 | this.pin = pin;
32 |
33 | connection.SetDirection(pin, Mcp23017PinDirection.Output);
34 | connection.SetResistor(pin, resistor);
35 | connection.SetPolarity(pin, polarity);
36 | }
37 |
38 | ///
39 | /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
40 | ///
41 | public void Dispose(){}
42 |
43 | #endregion
44 |
45 | #region Methods
46 |
47 | ///
48 | /// Writes the value of the pin.
49 | ///
50 | /// if set to true, pin is set to high state.
51 | public void Write(bool state)
52 | {
53 | connection.SetPinStatus(pin, state);
54 | }
55 |
56 | #endregion
57 | }
58 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Expanders/Mcp23017/Mcp23017Pin.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Expanders.Mcp23017
2 | {
3 | public enum Mcp23017Pin
4 | {
5 | A0 = 0x0001,
6 | A1 = 0x0002,
7 | A2 = 0x0004,
8 | A3 = 0x0008,
9 | A4 = 0x0010,
10 | A5 = 0x0020,
11 | A6 = 0x0040,
12 | A7 = 0x0080,
13 |
14 | B0 = 0x0101,
15 | B1 = 0x0102,
16 | B2 = 0x0104,
17 | B3 = 0x0108,
18 | B4 = 0x0110,
19 | B5 = 0x0120,
20 | B6 = 0x0140,
21 | B7 = 0x0180,
22 | }
23 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Expanders/Mcp23017/Mcp23017PinDirection.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Expanders.Mcp23017
2 | {
3 | public enum Mcp23017PinDirection
4 | {
5 | Input,
6 | Output
7 | }
8 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Expanders/Mcp23017/Mcp23017PinExtensionMethods.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Expanders.Mcp23017
2 | {
3 | ///
4 | /// Provides extension methods for MCP23017 pins.
5 | ///
6 | public static class Mcp23017PinExtensionMethods
7 | {
8 | #region Methods
9 |
10 | ///
11 | /// Creates an output binary pin.
12 | ///
13 | /// The connection.
14 | /// The pin.
15 | /// The resistor.
16 | /// The polarity.
17 | /// The pin.
18 | public static Mcp23017OutputBinaryPin Out(this Mcp23017I2cConnection connection, Mcp23017Pin pin, Mcp23017PinResistor resistor = Mcp23017PinResistor.None, Mcp23017PinPolarity polarity = Mcp23017PinPolarity.Normal)
19 | {
20 | return new Mcp23017OutputBinaryPin(connection, pin, resistor, polarity);
21 | }
22 |
23 | ///
24 | /// Creates an input binary pin.
25 | ///
26 | /// The connection.
27 | /// The pin.
28 | /// The resistor.
29 | /// The polarity.
30 | /// The pin.
31 | public static Mcp23017InputBinaryPin In(this Mcp23017I2cConnection connection, Mcp23017Pin pin, Mcp23017PinResistor resistor = Mcp23017PinResistor.None, Mcp23017PinPolarity polarity = Mcp23017PinPolarity.Normal)
32 | {
33 | return new Mcp23017InputBinaryPin(connection, pin, resistor, polarity);
34 | }
35 |
36 | #endregion
37 | }
38 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Expanders/Mcp23017/Mcp23017PinPolarity.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Expanders.Mcp23017
2 | {
3 | public enum Mcp23017PinPolarity
4 | {
5 | Normal,
6 | Inverted
7 | }
8 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Expanders/Mcp23017/Mcp23017PinResistor.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Expanders.Mcp23017
2 | {
3 | public enum Mcp23017PinResistor
4 | {
5 | None,
6 | PullUp
7 | }
8 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Expanders/Pcf8574/Pcf8574InputBinaryPin.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 |
5 | #endregion
6 |
7 | namespace Pi.IO.Components.Expanders.Pcf8574
8 | {
9 | ///
10 | /// Represents a binary intput pin on a PCF8574 I/O expander.
11 | ///
12 | public class Pcf8574InputBinaryPin : IInputBinaryPin
13 | {
14 | #region Fields
15 |
16 | private readonly Pcf8574I2cConnection connection;
17 | private readonly Pcf8574Pin pin;
18 |
19 | ///
20 | /// The default timeout (5 seconds).
21 | ///
22 | public static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(5);
23 |
24 | #endregion
25 |
26 | #region Instance Management
27 |
28 | ///
29 | /// Initializes a new instance of the class.
30 | ///
31 | /// The connection.
32 | /// The pin.
33 | public Pcf8574InputBinaryPin(Pcf8574I2cConnection connection, Pcf8574Pin pin)
34 | {
35 | this.connection = connection;
36 | this.pin = pin;
37 |
38 | connection.SetInputPin(pin, true);
39 | }
40 |
41 | ///
42 | /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
43 | ///
44 | public void Dispose(){}
45 |
46 | #endregion
47 |
48 | #region Methods
49 |
50 | ///
51 | /// Reads the state of the pin.
52 | ///
53 | ///
54 | /// true if the pin is in high state; otherwise, false.
55 | ///
56 | public bool Read()
57 | {
58 | return connection.GetPinStatus(pin);
59 | }
60 |
61 | ///
62 | /// Waits for the specified pin to be in the specified state.
63 | ///
64 | /// if set to true waits for the pin to be up. Default value is true.
65 | /// The timeout. Default value is .
66 | /// If timeout is set to , a default timeout is used instead.
67 | public void Wait(bool waitForUp = true, TimeSpan timeout = new TimeSpan())
68 | {
69 | var startWait = DateTime.UtcNow;
70 | if (timeout == TimeSpan.Zero)
71 | timeout = DefaultTimeout;
72 |
73 | while (Read() != waitForUp)
74 | {
75 | if (DateTime.UtcNow - startWait >= timeout)
76 | throw new TimeoutException("A timeout occurred while waiting for pin status to change");
77 | }
78 | }
79 |
80 | #endregion
81 | }
82 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Expanders/Pcf8574/Pcf8574OutputBinaryPin.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 |
5 | #endregion
6 |
7 | namespace Pi.IO.Components.Expanders.Pcf8574
8 | {
9 | ///
10 | /// Represents a binary output pin on a MCP23017 I/O expander.
11 | ///
12 | public class Pcf8574OutputBinaryPin : IOutputBinaryPin
13 | {
14 | #region Properties
15 |
16 | private readonly Pcf8574I2cConnection connection;
17 | private readonly Pcf8574Pin pin;
18 |
19 | #endregion
20 |
21 | #region Instance Management
22 |
23 | ///
24 | /// Initializes a new instance of the class.
25 | ///
26 | /// The connection.
27 | /// The pin.
28 | public Pcf8574OutputBinaryPin(Pcf8574I2cConnection connection, Pcf8574Pin pin)
29 | {
30 | this.connection = connection;
31 | this.pin = pin;
32 |
33 | connection.SetInputPin(pin, false);
34 | }
35 |
36 | ///
37 | /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
38 | ///
39 | public void Dispose(){}
40 |
41 | #endregion
42 |
43 | #region Methods
44 |
45 | ///
46 | /// Writes the value of the pin.
47 | ///
48 | /// if set to true, pin is set to high state.
49 | public void Write(bool state)
50 | {
51 | connection.SetPinStatus(pin, state);
52 | }
53 |
54 | #endregion
55 | }
56 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Expanders/Pcf8574/Pcf8574Pin.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Expanders.Pcf8574
2 | {
3 | public enum Pcf8574Pin
4 | {
5 | P0 = 0x01,
6 | P1 = 0x02,
7 | P2 = 0x04,
8 | P3 = 0x08,
9 | P4 = 0x10,
10 | P5 = 0x20,
11 | P6 = 0x40,
12 | P7 = 0x80
13 | }
14 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Expanders/Pcf8574/Pcf8574PinExtensionMethods.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Expanders.Pcf8574
2 | {
3 | ///
4 | /// Provides extension methods for PCF8574 pins.
5 | ///
6 | public static class Pcf8574PinExtensionMethods
7 | {
8 | #region Methods
9 |
10 | ///
11 | /// Creates an output binary pin.
12 | ///
13 | /// The connection.
14 | /// The pin.
15 | /// The pin.
16 | public static Pcf8574OutputBinaryPin Out(this Pcf8574I2cConnection connection, Pcf8574Pin pin)
17 | {
18 | return new Pcf8574OutputBinaryPin(connection, pin);
19 | }
20 |
21 | ///
22 | /// Creates an input binary pin.
23 | ///
24 | /// The connection.
25 | /// The pin.
26 | /// The pin.
27 | public static Pcf8574InputBinaryPin In(this Pcf8574I2cConnection connection, Pcf8574Pin pin)
28 | {
29 | return new Pcf8574InputBinaryPin(connection, pin);
30 | }
31 |
32 | #endregion
33 | }
34 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Leds/BiColor24Bargraph/BiColor24Bargraph.cs:
--------------------------------------------------------------------------------
1 | //Copyright (c) 2016 Logic Ethos Ltd
2 | //
3 | //Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4 | //The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
5 | //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
6 |
7 | using System;
8 | using Pi.Timers;
9 | using Pi.IO.Components.Controllers.HT16K33;
10 | using Pi.IO.InterIntegratedCircuit;
11 |
12 |
13 | namespace Pi.IO.Components.Leds.BiColor24Bargraph
14 | {
15 | public class BiColor24Bargraph : HT16K33Connection
16 | {
17 | public enum LEDState
18 | {
19 | Off,
20 | Red,
21 | Green,
22 | Yellow
23 | }
24 | ///
25 | /// Initializes a new instance of the class.
26 | ///
27 | /// I2c Connection.
28 | public BiColor24Bargraph (I2cDeviceConnection connection) : base (connection,6)
29 | {
30 | }
31 |
32 | ///
33 | /// Sets the led (0 to 23)
34 | ///
35 | /// Led no.
36 | /// State.
37 | public void SetLed(uint ledNo, LEDState state)
38 | {
39 |
40 | if (ledNo > 23) throw new Exception("led must be between 0 and 23");
41 |
42 | long r,c;
43 | r = Math.DivRem(ledNo,4,out c) * 2;
44 | if (ledNo >= 12) c += 4;
45 |
46 | if (r > 4) r -= 6;
47 |
48 | switch (state)
49 | {
50 | case LEDState.Off:
51 | base.SetLed((uint)r,(uint)c, false);
52 | base.SetLed((uint)r + 1,(uint)c, false);
53 | break;
54 | case LEDState.Red:
55 | base.SetLed((uint)r,(uint)c, true);
56 | base.SetLed((uint)r + 1,(uint)c, false);
57 | break;
58 | case LEDState.Yellow:
59 | base.SetLed((uint)r,(uint)c, true);
60 | base.SetLed((uint)r + 1,(uint)c, true);
61 | break;
62 | case LEDState.Green:
63 | base.SetLed((uint)r,(uint)c, false);
64 | base.SetLed((uint)r + 1,(uint)c, true);
65 | break;
66 | }
67 |
68 | }
69 | }
70 | }
71 |
72 |
73 |
74 |
75 |
--------------------------------------------------------------------------------
/Pi.IO.Components/Pi.IO.Components.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 | 0.0.1-preview1
6 | true
7 | NU1701
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/Pi.IO.Components/Sensors/Distance/HcSr04/HcSr04Connection.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 | using Pi.Timers;
5 | using UnitsNet;
6 |
7 | #endregion
8 |
9 | namespace Pi.IO.Components.Sensors.Distance.HcSr04
10 | {
11 | ///
12 | /// Represents a connection to HC-SR04 distance sensor.
13 | ///
14 | ///
15 | /// for hardware specification and
16 | /// for implementation details.
17 | ///
18 | public class HcSr04Connection : IDisposable
19 | {
20 | #region Fields
21 |
22 | private static readonly TimeSpan triggerTime = TimeSpanUtility.FromMicroseconds(10);
23 | private static readonly TimeSpan echoUpTimeout = TimeSpan.FromMilliseconds(500);
24 |
25 | private readonly IOutputBinaryPin triggerPin;
26 | private readonly IInputBinaryPin echoPin;
27 |
28 | #endregion
29 |
30 | #region Instance Management
31 |
32 | ///
33 | /// Initializes a new instance of the class.
34 | ///
35 | /// The trigger pin.
36 | /// The echo pin.
37 | public HcSr04Connection(IOutputBinaryPin triggerPin, IInputBinaryPin echoPin)
38 | {
39 | this.triggerPin = triggerPin;
40 | this.echoPin = echoPin;
41 |
42 | Timeout = DefaultTimeout;
43 |
44 | try
45 | {
46 | GetDistance();
47 | } catch {}
48 | }
49 |
50 | ///
51 | /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
52 | ///
53 | void IDisposable.Dispose()
54 | {
55 | Close();
56 | }
57 |
58 | #endregion
59 |
60 | #region Properties
61 |
62 | ///
63 | /// The default timeout (50ms).
64 | ///
65 | /// Maximum time (if no obstacle) is 38ms.
66 | public static readonly TimeSpan DefaultTimeout = TimeSpan.FromMilliseconds(50);
67 |
68 | ///
69 | /// Gets or sets the timeout for distance measure.
70 | ///
71 | ///
72 | /// The timeout.
73 | ///
74 | public TimeSpan Timeout { get; set; }
75 |
76 | #endregion
77 |
78 | #region Methods
79 |
80 | ///
81 | /// Gets the distance.
82 | ///
83 | /// The distance.
84 | public Length GetDistance()
85 | {
86 | triggerPin.Write(true);
87 | Timer.Sleep(triggerTime);
88 | triggerPin.Write(false);
89 |
90 | var upTime = echoPin.Time(true, echoUpTimeout, Timeout);
91 | return Units.Velocity.Sound.ToDistance(upTime) / 2;
92 | }
93 |
94 | ///
95 | /// Closes the connection.
96 | ///
97 | public void Close()
98 | {
99 | triggerPin.Dispose();
100 | echoPin.Dispose();
101 | }
102 |
103 | #endregion
104 | }
105 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Sensors/Distance/HcSr04/Units.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using UnitsNet;
3 |
4 | namespace Pi.IO.Components.Sensors.Distance.HcSr04
5 | {
6 | internal static class Units
7 | {
8 | ///
9 | /// Velocity related conversions
10 | ///
11 | public static class Velocity
12 | {
13 | ///
14 | /// Sound velocity related conversions
15 | ///
16 | public static class Sound
17 | {
18 | #region Methods
19 |
20 | ///
21 | /// Converts a time to a distance.
22 | ///
23 | /// The time.
24 | /// The distance travelled by sound in one second, in meters.
25 | public static Length ToDistance(TimeSpan time)
26 | {
27 | if (time < TimeSpan.Zero)
28 | return Length.FromMeters(double.MinValue);
29 |
30 | return Length.FromMeters(time.TotalMilliseconds * 340 / 1000);
31 | }
32 |
33 | #endregion
34 | }
35 | }
36 | }
37 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Sensors/Light/BH1750Connection.cs:
--------------------------------------------------------------------------------
1 | using Pi.IO.InterIntegratedCircuit;
2 | using Pi.Timers;
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Linq;
6 | using System.Text;
7 |
8 | namespace Pi.IO.Components.Sensors.Light
9 | {
10 | namespace RPI.Sensor.Sensors.Light
11 | {
12 | public class BH1750Connection
13 | {
14 | public I2cDeviceConnection Connection { get; set; }
15 | public BH1750Connection(I2cDeviceConnection connection)
16 | {
17 | Connection = connection;
18 | }
19 |
20 | public void SetOff()
21 | {
22 | Connection.Write(0x00);
23 | }
24 | public void SetOn()
25 | {
26 | Connection.Write(0x01);
27 | }
28 | public void Reset()
29 | {
30 | Connection.Write(0x07);
31 | }
32 |
33 | public double GetData()
34 | {
35 | Connection.Write(0x10);
36 | HighResolutionTimer.Sleep(TimeSpanUtility.FromMicroseconds(150 * 1000));
37 | byte[] readBuf = Connection.Read(2);
38 |
39 | var valf = readBuf[0] << 8;
40 | valf |= readBuf[1];
41 | return valf / 1.2 * (69 / 69) / 1;
42 |
43 | // var valf = ((readBuf[0] << 8) | readBuf[1]) / 1.2;
44 | // return valf;
45 |
46 | // return Math.Round(valf / (2 * 1.2), 2);
47 |
48 | }
49 |
50 | }
51 | }
52 |
53 | }
54 |
--------------------------------------------------------------------------------
/Pi.IO.Components/Sensors/Pressure/Bmp085/Bmp085Data.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Sensors.Pressure.Bmp085
2 | {
3 | ///
4 | /// Represents data from a .
5 | ///
6 | public struct Bmp085Data
7 | {
8 | public UnitsNet.Temperature Temperature;
9 | public UnitsNet.Pressure Pressure;
10 | }
11 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Sensors/Pressure/Bmp085/Bmp085I2cConnectionExtensionMethods.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 | using UnitsNet;
5 |
6 | #endregion
7 |
8 | namespace Pi.IO.Components.Sensors.Pressure.Bmp085
9 | {
10 | ///
11 | /// Provides extension methods for .
12 | ///
13 | public static class Bmp085I2cConnectionExtensionMethods
14 | {
15 | #region Methods
16 |
17 | ///
18 | /// Gets the sea-level pressure.
19 | ///
20 | /// The BMP085 connection.
21 | /// The current altitude.
22 | /// The pressure.
23 | public static UnitsNet.Pressure GetSealevelPressure(this Bmp085I2cConnection connection, Length currentAltitude)
24 | {
25 | var pressure = connection.GetPressure();
26 | return UnitsNet.Pressure.FromPascals(pressure.Pascals / Math.Pow(1.0 - currentAltitude.Meters/44330, 5.255));
27 | }
28 |
29 | ///
30 | /// Gets the altitude.
31 | ///
32 | /// The BMP085 connection.
33 | /// The sealevel pressure.
34 | /// The altitude
35 | public static Length GetAltitude(this Bmp085I2cConnection connection, UnitsNet.Pressure sealevelPressure)
36 | {
37 | var pressure = connection.GetPressure();
38 | return Length.FromMeters(44330 * (1.0 - Math.Pow(pressure.Pascals / sealevelPressure.Pascals, 1 / 5.255)));
39 | }
40 |
41 | #endregion
42 | }
43 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Sensors/Pressure/Bmp085/Bmp085Precision.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Sensors.Pressure.Bmp085
2 | {
3 | public enum Bmp085Precision
4 | {
5 | Low = 0,
6 | Standard = 1,
7 | High = 2,
8 | Highest = 3
9 | }
10 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Sensors/ResistiveDivider.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using UnitsNet;
3 |
4 | namespace Pi.IO.Components.Sensors
5 | {
6 | public static class ResistiveDivider
7 | {
8 | ///
9 | /// Gets the conversion function for the upper resistor of a voltage divider.
10 | ///
11 | /// The lower resistor value.
12 | ///
13 | /// The function.
14 | ///
15 | public static Func ForUpperResistor(ElectricResistance lowerResistorValue)
16 | {
17 | return v => v.Relative != 0
18 | ? lowerResistorValue * (double)((1 - v.Relative) / v.Relative)
19 | : ElectricResistance.FromOhms(double.MaxValue);
20 | }
21 |
22 | ///
23 | /// Gets the conversion function for the lower resistor of a voltage divider.
24 | ///
25 | /// The upper resistor value.
26 | ///
27 | /// The function.
28 | ///
29 | public static Func ForLowerResistor(ElectricResistance upperResistorValue)
30 | {
31 | return v => v.Relative != 1
32 | ? upperResistorValue * (double)(v.Relative / (1 - v.Relative))
33 | : ElectricResistance.FromOhms(double.MaxValue);
34 | }
35 | }
36 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Sensors/Temperature/Dht/Dht11Connection.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 | using UnitsNet;
5 |
6 | #endregion
7 |
8 | namespace Pi.IO.Components.Sensors.Temperature.Dht
9 | {
10 | ///
11 | /// Represents a connection to a DHT11 sensor.
12 | ///
13 | public class Dht11Connection : DhtConnection
14 | {
15 | #region Instance Management
16 |
17 | ///
18 | /// Initializes a new instance of the class.
19 | ///
20 | /// The pin.
21 | /// if set to true, DHT is automatically started. Default value is true.
22 | public Dht11Connection(IInputOutputBinaryPin pin, bool autoStart = true) : base(pin, autoStart) { }
23 |
24 | #endregion
25 |
26 | #region Protected Methods
27 |
28 | protected override TimeSpan DefaultSamplingInterval
29 | {
30 | get { return TimeSpan.FromSeconds(1); }
31 | }
32 |
33 | protected override TimeSpan WakeupInterval
34 | {
35 | get { return TimeSpan.FromMilliseconds(18); }
36 | }
37 |
38 | protected override DhtData GetDhtData(int temperatureValue, int humidityValue)
39 | {
40 | return new DhtData
41 | {
42 | RelativeHumidity = Ratio.FromPercent(humidityValue/256d),
43 | Temperature = UnitsNet.Temperature.FromDegreesCelsius(temperatureValue/256d)
44 | };
45 | }
46 |
47 | #endregion
48 | }
49 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Sensors/Temperature/Dht/Dht22Connection.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 | using UnitsNet;
5 |
6 | #endregion
7 |
8 | namespace Pi.IO.Components.Sensors.Temperature.Dht
9 | {
10 | ///
11 | /// Represents a connection to a DHT22 sensor.
12 | ///
13 | public class Dht22Connection : DhtConnection
14 | {
15 | #region Instance Management
16 |
17 | ///
18 | /// Initializes a new instance of the class.
19 | ///
20 | /// The pin.
21 | /// if set to true, DHT is automatically started. Default value is true.
22 | public Dht22Connection(IInputOutputBinaryPin pin, bool autoStart = true) : base(pin, autoStart) { }
23 |
24 | #endregion
25 |
26 | #region Protected Methods
27 |
28 | protected override TimeSpan DefaultSamplingInterval
29 | {
30 | get { return TimeSpan.FromSeconds(2); }
31 | }
32 |
33 | protected override TimeSpan WakeupInterval
34 | {
35 | get { return TimeSpan.FromMilliseconds(1); }
36 | }
37 |
38 | protected override DhtData GetDhtData(int temperatureValue, int humidityValue)
39 | {
40 | return new DhtData
41 | {
42 | RelativeHumidity = Ratio.FromPercent(humidityValue/10d),
43 | Temperature = UnitsNet.Temperature.FromDegreesCelsius(temperatureValue/10d)
44 | };
45 | }
46 |
47 | #endregion
48 | }
49 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Sensors/Temperature/Dht/DhtData.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.Components.Sensors.Temperature.Dht
2 | {
3 | public class DhtData
4 | {
5 | public int AttemptCount;
6 | public UnitsNet.Temperature Temperature;
7 | public UnitsNet.Ratio RelativeHumidity;
8 | }
9 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Sensors/Temperature/Dht/InvalidChecksumException.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Globalization;
3 |
4 | namespace Pi.IO.Components.Sensors.Temperature.Dht
5 | {
6 | public class InvalidChecksumException : Exception
7 | {
8 | private readonly long expectedValue;
9 | private readonly long actualValue;
10 |
11 | public InvalidChecksumException(long expectedValue, long actualValue) : base(GetMessage(null, expectedValue, actualValue))
12 | {
13 | this.expectedValue = expectedValue;
14 | this.actualValue = actualValue;
15 | }
16 |
17 | public InvalidChecksumException(string message, long expectedValue, long actualValue) : base(GetMessage(message, expectedValue, actualValue))
18 | {
19 | this.expectedValue = expectedValue;
20 | this.actualValue = actualValue;
21 | }
22 |
23 | public InvalidChecksumException(string message, Exception innerException, long expectedValue, long actualValue) : base(GetMessage(message, expectedValue, actualValue), innerException)
24 | {
25 | this.expectedValue = expectedValue;
26 | this.actualValue = actualValue;
27 | }
28 |
29 | public long ExpectedValue
30 | {
31 | get { return expectedValue; }
32 | }
33 |
34 | public long ActualValue
35 | {
36 | get { return actualValue; }
37 | }
38 |
39 | private static string GetMessage(string message, long expectedValue, long actualValue)
40 | {
41 | var valueMessage = string.Format(CultureInfo.InvariantCulture, "Expected {0}, found {1}", expectedValue, actualValue);
42 | return !string.IsNullOrEmpty(message)
43 | ? message + ". " + valueMessage
44 | : valueMessage;
45 | }
46 | }
47 | }
--------------------------------------------------------------------------------
/Pi.IO.Components/Sensors/Temperature/Tmp36/Tmp36Connection.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 | using UnitsNet;
5 |
6 | #endregion
7 |
8 | namespace Pi.IO.Components.Sensors.Temperature.Tmp36
9 | {
10 | ///
11 | /// Represents a connection to a TMP36 temperature sensor.
12 | ///
13 | /// See .
14 | public class Tmp36Connection : IDisposable
15 | {
16 | #region Fields
17 |
18 | private readonly IInputAnalogPin inputPin;
19 | private readonly ElectricPotential referenceVoltage;
20 |
21 | #endregion
22 |
23 | #region Instance Management
24 |
25 | ///
26 | /// Initializes a new instance of the class.
27 | ///
28 | /// The input pin.
29 | /// The reference voltage.
30 | public Tmp36Connection(IInputAnalogPin inputPin, ElectricPotential referenceVoltage)
31 | {
32 | this.inputPin = inputPin;
33 | this.referenceVoltage = referenceVoltage;
34 | }
35 |
36 | ///
37 | /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
38 | ///
39 | void IDisposable.Dispose()
40 | {
41 | Close();
42 | }
43 |
44 | #endregion
45 |
46 | #region Methods
47 |
48 | ///
49 | /// Gets the temperature.
50 | ///
51 | /// The temperature.
52 | public UnitsNet.Temperature GetTemperature()
53 | {
54 | var voltage = referenceVoltage * (double)inputPin.Read().Relative;
55 | return UnitsNet.Temperature.FromDegreesCelsius(voltage.Volts * 100 - 50);
56 | }
57 |
58 | ///
59 | /// Closes this instance.
60 | ///
61 | public void Close()
62 | {
63 | inputPin.Dispose();
64 | }
65 |
66 | #endregion
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/Pi.IO.Components/Sensors/VariableResistiveDividerConnection.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 | using UnitsNet;
5 |
6 | #endregion
7 |
8 | namespace Pi.IO.Components.Sensors
9 | {
10 | ///
11 | /// Represents a connection to an analog value coming from a resistive voltage divider
12 | ///
13 | public class VariableResistiveDividerConnection : IDisposable
14 | {
15 | #region Fields
16 |
17 | private readonly IInputAnalogPin analogPin;
18 | private readonly Func resistorEvalFunc;
19 |
20 | #endregion
21 |
22 | #region Instance Management
23 |
24 | ///
25 | /// Initializes a new instance of the class.
26 | ///
27 | /// The analog pin.
28 | /// The resistor eval function.
29 | /// Methods from should be used.
30 | public VariableResistiveDividerConnection(IInputAnalogPin analogPin, Func resistorEvalFunc)
31 | {
32 | this.analogPin = analogPin;
33 | this.resistorEvalFunc = resistorEvalFunc;
34 | }
35 |
36 | ///
37 | /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
38 | ///
39 | void IDisposable.Dispose()
40 | {
41 | Close();
42 | }
43 |
44 | #endregion
45 |
46 | #region Methods
47 |
48 | ///
49 | /// Gets the electric resistance.
50 | ///
51 | /// The resistance value.
52 | public ElectricResistance GetResistance()
53 | {
54 | var value = analogPin.Read();
55 | return resistorEvalFunc(value);
56 | }
57 |
58 | ///
59 | /// Closes this instance.
60 | ///
61 | public void Close()
62 | {
63 | analogPin.Dispose();
64 | }
65 |
66 | #endregion
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/Pi.IO.GeneralPurpose/Behaviors/BlinkBehavior.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System.Collections.Generic;
4 |
5 | #endregion
6 |
7 | namespace Pi.IO.GeneralPurpose.Behaviors
8 | {
9 | ///
10 | /// Represents a simple blink behavior.
11 | ///
12 | public class BlinkBehavior : PinsBehavior
13 | {
14 | #region Instance Management
15 |
16 | ///
17 | /// Initializes a new instance of the class.
18 | ///
19 | /// The configurations.
20 | public BlinkBehavior(IEnumerable configurations) : base(configurations){}
21 |
22 | #endregion
23 |
24 | #region Properties
25 |
26 | ///
27 | /// Gets or sets the number of times the behavior may blink.
28 | ///
29 | ///
30 | /// The number of times the behavior may blink.
31 | ///
32 | public int Count { get; set; }
33 |
34 | #endregion
35 |
36 | #region Protected Methods
37 |
38 | ///
39 | /// Gets the first step.
40 | ///
41 | ///
42 | /// The first step.
43 | ///
44 | protected override int GetFirstStep()
45 | {
46 | return 1;
47 | }
48 |
49 | ///
50 | /// Processes the step.
51 | ///
52 | /// The step.
53 | protected override void ProcessStep(int step)
54 | {
55 | foreach (var configuration in Configurations)
56 | Connection.Toggle(configuration);
57 | }
58 |
59 | ///
60 | /// Tries to get the next step.
61 | ///
62 | /// The step.
63 | ///
64 | /// true if the behavior may continue; otherwise behavior will be stopped.
65 | ///
66 | protected override bool TryGetNextStep(ref int step)
67 | {
68 | step++;
69 | return step <= Count*2;
70 | }
71 |
72 | #endregion
73 | }
74 | }
--------------------------------------------------------------------------------
/Pi.IO.GeneralPurpose/Behaviors/PinsBehaviorExtensionMethods.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.GeneralPurpose.Behaviors
2 | {
3 | ///
4 | /// Provides extension methods for .
5 | ///
6 | public static class PinsBehaviorExtensionMethods
7 | {
8 | #region Methods
9 |
10 | ///
11 | /// Starts the specified behavior on the connection.
12 | ///
13 | /// The connection.
14 | /// The behavior.
15 | public static void Start(this GpioConnection connection, PinsBehavior behavior)
16 | {
17 | foreach (var configuration in behavior.Configurations)
18 | {
19 | if (!connection.Contains(configuration))
20 | connection.Add(configuration);
21 | }
22 |
23 | behavior.Start(connection);
24 | }
25 |
26 | ///
27 | /// Stops the specified behavior.
28 | ///
29 | /// The connection.
30 | /// The behavior.
31 | public static void Stop(this GpioConnection connection, PinsBehavior behavior)
32 | {
33 | behavior.Stop();
34 | }
35 |
36 | #endregion
37 | }
38 | }
--------------------------------------------------------------------------------
/Pi.IO.GeneralPurpose/Configuration/GpioConnectionConfigurationSection.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System.Configuration;
4 |
5 | #endregion
6 |
7 | namespace Pi.IO.GeneralPurpose.Configuration
8 | {
9 | ///
10 | /// Represents the configuration of the GPIO connection.
11 | ///
12 | public class GpioConnectionConfigurationSection : ConfigurationSection
13 | {
14 | #region Constants
15 |
16 | ///
17 | /// The default poll interval, in milliseconds.
18 | ///
19 | public const decimal DefaultPollInterval = 50.0m;
20 |
21 | #endregion
22 |
23 | #region Properties
24 |
25 | ///
26 | /// Gets or sets the name of the driver type.
27 | ///
28 | ///
29 | /// The name of the driver type.
30 | ///
31 | [ConfigurationProperty("driver")]
32 | public string DriverTypeName
33 | {
34 | get { return (string) this["driver"]; }
35 | set { this["driver"] = value; }
36 | }
37 |
38 | ///
39 | /// Gets or sets the board connector revision.
40 | ///
41 | ///
42 | /// The board revision, 0 for automatic detection, 1 for model B rev1; 2 for model B rev2 and model A, 3 for model B+, A+ and higher.
43 | ///
44 | [ConfigurationProperty("boardConnectorRevision", DefaultValue = 0)]
45 | public int BoardConnectorRevision
46 | {
47 | get { return (int)this["boardConnectorRevision"]; }
48 | set { this["boardConnectorRevision"] = value; }
49 | }
50 |
51 | ///
52 | /// Gets or sets the poll interval, in milliseconds.
53 | ///
54 | ///
55 | /// The poll interval, in millisecond.
56 | ///
57 | ///
58 | /// Default value is 50ms.
59 | /// Values lower than 1ms may be specified on Raspberry Pi using decimal notation.
60 | ///
61 | [ConfigurationProperty("pollInterval", DefaultValue = "50")]
62 | public decimal PollInterval
63 | {
64 | get { return (decimal)this["pollInterval"]; }
65 | set { this["pollInterval"] = value; }
66 | }
67 |
68 | #endregion
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/Pi.IO.GeneralPurpose/ConnectedPin.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 | using System.Collections.Generic;
5 |
6 | #endregion
7 |
8 | namespace Pi.IO.GeneralPurpose
9 | {
10 | ///
11 | /// Represents a connected pin.
12 | ///
13 | public class ConnectedPin
14 | {
15 | #region Fields
16 |
17 | private readonly GpioConnection connection;
18 | private readonly HashSet> events = new HashSet>();
19 |
20 | #endregion
21 |
22 | #region Instance Management
23 |
24 | internal ConnectedPin(GpioConnection connection, PinConfiguration pinConfiguration)
25 | {
26 | this.connection = connection;
27 | Configuration = pinConfiguration;
28 | }
29 |
30 | #endregion
31 |
32 | #region Properties
33 |
34 | ///
35 | /// Gets the configuration.
36 | ///
37 | public PinConfiguration Configuration { get; private set; }
38 |
39 | ///
40 | /// Gets or sets a value indicating whether this is enabled.
41 | ///
42 | ///
43 | /// true if enabled; otherwise, false.
44 | ///
45 | public bool Enabled
46 | {
47 | get { return connection[Configuration]; }
48 | set { connection[Configuration] = value; }
49 | }
50 |
51 | #endregion
52 |
53 | #region Methods
54 |
55 | ///
56 | /// Toggles this pin.
57 | ///
58 | public void Toggle()
59 | {
60 | connection.Toggle(Configuration);
61 | }
62 |
63 | ///
64 | /// Blinks the pin.
65 | ///
66 | /// The blink duration.
67 | public void Blink(TimeSpan duration = new TimeSpan())
68 | {
69 | connection.Blink(Configuration, duration);
70 | }
71 |
72 | #endregion
73 |
74 | #region Events
75 |
76 | ///
77 | /// Occurs when pin status changed.
78 | ///
79 | public event EventHandler StatusChanged
80 | {
81 | add
82 | {
83 | if (events.Count == 0)
84 | connection.PinStatusChanged += ConnectionPinStatusChanged;
85 | events.Add(value);
86 | }
87 | remove
88 | {
89 | events.Remove(value);
90 | if (events.Count == 0)
91 | connection.PinStatusChanged -= ConnectionPinStatusChanged;
92 | }
93 | }
94 |
95 | #endregion
96 |
97 | #region Private Helpers
98 |
99 | private void ConnectionPinStatusChanged(object sender, PinStatusEventArgs pinStatusEventArgs)
100 | {
101 | if (pinStatusEventArgs.Configuration.Pin != Configuration.Pin)
102 | return;
103 |
104 | foreach (var eventHandler in events)
105 | eventHandler(sender, pinStatusEventArgs);
106 | }
107 |
108 | #endregion
109 | }
110 | }
--------------------------------------------------------------------------------
/Pi.IO.GeneralPurpose/ConnectedPins.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System.Collections;
4 | using System.Collections.Generic;
5 | using System.Linq;
6 |
7 | #endregion
8 |
9 | namespace Pi.IO.GeneralPurpose
10 | {
11 | ///
12 | /// Represents connected pins.
13 | ///
14 | public class ConnectedPins : IEnumerable
15 | {
16 | #region Fields
17 |
18 | private readonly GpioConnection connection;
19 |
20 | #endregion
21 |
22 | #region Instance Management
23 |
24 | internal ConnectedPins(GpioConnection connection)
25 | {
26 | this.connection = connection;
27 | }
28 |
29 | #endregion
30 |
31 | #region Properties
32 |
33 | ///
34 | /// Gets the status of the specified pin.
35 | ///
36 | public ConnectedPin this[ProcessorPin pin]
37 | {
38 | get { return new ConnectedPin(connection, connection.GetConfiguration(pin)); }
39 | }
40 |
41 | ///
42 | /// Gets the status of the specified pin.
43 | ///
44 | public ConnectedPin this[string name]
45 | {
46 | get { return new ConnectedPin(connection, connection.GetConfiguration(name)); }
47 | }
48 |
49 | ///
50 | /// Gets the status of the specified pin.
51 | ///
52 | public ConnectedPin this[ConnectorPin pin]
53 | {
54 | get { return this[pin.ToProcessor()]; }
55 | }
56 |
57 | ///
58 | /// Gets the status of the specified pin.
59 | ///
60 | public ConnectedPin this[PinConfiguration pin]
61 | {
62 | get { return new ConnectedPin(connection, pin); }
63 | }
64 |
65 | #endregion
66 |
67 | #region Methods
68 |
69 | ///
70 | /// Returns an enumerator that iterates through a collection.
71 | ///
72 | ///
73 | /// An object that can be used to iterate through the collection.
74 | ///
75 | IEnumerator IEnumerable.GetEnumerator()
76 | {
77 | return GetEnumerator();
78 | }
79 |
80 | ///
81 | /// Gets the enumerator.
82 | ///
83 | /// The enumerator.
84 | public IEnumerator GetEnumerator()
85 | {
86 | return connection.Configurations.Select(c => new ConnectedPin(connection, c)).GetEnumerator();
87 | }
88 |
89 | #endregion
90 | }
91 | }
--------------------------------------------------------------------------------
/Pi.IO.GeneralPurpose/FileGpioHandle.cs:
--------------------------------------------------------------------------------
1 | using System.IO;
2 |
3 | namespace Pi.IO.GeneralPurpose
4 | {
5 | ///
6 | /// Represents a handle on a GPIO file
7 | ///
8 | public class FileGpioHandle
9 | {
10 | ///
11 | /// Gets or sets the gpio path.
12 | ///
13 | ///
14 | /// The gpio path.
15 | ///
16 | public string GpioPath { get; set; }
17 |
18 | ///
19 | /// Gets or sets the gpio stream.
20 | ///
21 | ///
22 | /// The gpio stream.
23 | ///
24 | public Stream GpioStream { get; set; }
25 | }
26 | }
--------------------------------------------------------------------------------
/Pi.IO.GeneralPurpose/GpioConnectionDriverCapabilities.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Pi.IO.GeneralPurpose
4 | {
5 | ///
6 | /// Represents capabilities of a driver.
7 | ///
8 | [Flags]
9 | public enum GpioConnectionDriverCapabilities
10 | {
11 | ///
12 | /// No advanced capability.
13 | ///
14 | None = 0,
15 |
16 | ///
17 | /// The driver can set pin resistor
18 | ///
19 | CanSetPinResistor = 1,
20 |
21 | ///
22 | /// The driver can set pin detected edges
23 | ///
24 | CanSetPinDetectedEdges = 2,
25 |
26 | ///
27 | /// The driver can change pin direction rapidly.
28 | ///
29 | CanChangePinDirectionRapidly = 4,
30 |
31 | ///
32 | /// The driver can work on third-party computers (not only Raspberry Pi)
33 | ///
34 | CanWorkOnThirdPartyComputers = 8
35 | }
36 | }
--------------------------------------------------------------------------------
/Pi.IO.GeneralPurpose/GpioConnectionDriverExtensionMethods.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 |
5 | #endregion
6 |
7 | namespace Pi.IO.GeneralPurpose
8 | {
9 | ///
10 | /// Provides extension methods for .
11 | ///
12 | public static class GpioConnectionDriverExtensionMethods
13 | {
14 | #region Methods
15 |
16 | ///
17 | /// Waits for a pin to reach the specified state, then measures the time it remains in this state.
18 | ///
19 | /// The driver.
20 | /// The measure pin.
21 | /// if set to true, wait for the pin to be up.
22 | /// The first phase timeout.
23 | /// The second phase timeout.
24 | ///
25 | /// The time the pin remains up.
26 | ///
27 | public static decimal Time(this IGpioConnectionDriver driver, ProcessorPin pin, bool waitForUp = true, TimeSpan phase1Timeout = new TimeSpan(), TimeSpan phase2Timeout = new TimeSpan())
28 | {
29 | driver.Wait(pin, waitForUp, phase1Timeout);
30 |
31 | var waitDown = DateTime.Now.Ticks;
32 | driver.Wait(pin, !waitForUp, phase2Timeout);
33 |
34 | return (DateTime.Now.Ticks - waitDown)/10000m;
35 | }
36 |
37 | #endregion
38 | }
39 | }
--------------------------------------------------------------------------------
/Pi.IO.GeneralPurpose/GpioInputBinaryPin.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Pi.IO.GeneralPurpose
4 | {
5 | ///
6 | /// Represents a GPIO input binary pin.
7 | ///
8 | public class GpioInputBinaryPin : IInputBinaryPin
9 | {
10 | #region Fields
11 |
12 | private readonly IGpioConnectionDriver driver;
13 | private readonly ProcessorPin pin;
14 |
15 | #endregion
16 |
17 | #region Instance Management
18 |
19 | ///
20 | /// Initializes a new instance of the class.
21 | ///
22 | /// The driver.
23 | /// The pin.
24 | /// The resistor.
25 | public GpioInputBinaryPin(IGpioConnectionDriver driver, ProcessorPin pin, PinResistor resistor = PinResistor.None)
26 | {
27 | this.driver = driver;
28 | this.pin = pin;
29 |
30 | driver.Allocate(pin, PinDirection.Input);
31 | if ((driver.GetCapabilities() & GpioConnectionDriverCapabilities.CanSetPinResistor) > 0)
32 | driver.SetPinResistor(pin, resistor);
33 | if ((driver.GetCapabilities() & GpioConnectionDriverCapabilities.CanSetPinDetectedEdges) > 0)
34 | driver.SetPinDetectedEdges(pin, PinDetectedEdges.Both);
35 | }
36 |
37 | ///
38 | /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
39 | ///
40 | public void Dispose()
41 | {
42 | driver.Release(pin);
43 | }
44 |
45 | #endregion
46 |
47 | #region Methods
48 |
49 | ///
50 | /// Reads the state of the pin.
51 | ///
52 | ///
53 | /// true if the pin is in high state; otherwise, false.
54 | ///
55 | public bool Read()
56 | {
57 | return driver.Read(pin);
58 | }
59 |
60 | ///
61 | /// Waits for the specified pin to be in the specified state.
62 | ///
63 | /// if set to true waits for the pin to be up. Default value is true.
64 | /// The timeout. Default value is .
65 | /// If timeout is set to , a default timeout is used instead.
66 | public void Wait(bool waitForUp = true, TimeSpan timeout = new TimeSpan())
67 | {
68 | driver.Wait(pin, waitForUp, timeout);
69 | }
70 |
71 | #endregion
72 | }
73 | }
--------------------------------------------------------------------------------
/Pi.IO.GeneralPurpose/GpioOutputBinaryPin.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.GeneralPurpose
2 | {
3 | ///
4 | /// Represents an output pin on GPIO interface.
5 | ///
6 | public class GpioOutputBinaryPin : IOutputBinaryPin
7 | {
8 | #region Fields
9 |
10 | private readonly IGpioConnectionDriver driver;
11 | private readonly ProcessorPin pin;
12 |
13 | #endregion
14 |
15 | #region Instance Management
16 |
17 | ///
18 | /// Initializes a new instance of the class.
19 | ///
20 | /// The driver.
21 | /// The pin.
22 | /// The resistor.
23 | public GpioOutputBinaryPin(IGpioConnectionDriver driver, ProcessorPin pin, PinResistor resistor = PinResistor.None)
24 | {
25 | this.driver = driver;
26 | this.pin = pin;
27 |
28 | driver.Allocate(pin, PinDirection.Output);
29 | if ((driver.GetCapabilities() & GpioConnectionDriverCapabilities.CanSetPinResistor) > 0)
30 | driver.SetPinResistor(pin, resistor);
31 | }
32 |
33 | #endregion
34 |
35 | #region Methods
36 |
37 | ///
38 | /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
39 | ///
40 | public void Dispose()
41 | {
42 | driver.Release(pin);
43 | }
44 |
45 | ///
46 | /// Writes the specified state.
47 | ///
48 | /// The pin state.
49 | public void Write(bool state)
50 | {
51 | driver.Write(pin, state);
52 | }
53 |
54 | #endregion
55 | }
56 | }
--------------------------------------------------------------------------------
/Pi.IO.GeneralPurpose/IGpioConnectionDriver.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Pi.IO.GeneralPurpose
4 | {
5 | ///
6 | /// Provides an interface for connection drivers.
7 | ///
8 | public interface IGpioConnectionDriver
9 | {
10 | #region Methods
11 |
12 | ///
13 | /// Gets driver capabilities.
14 | ///
15 | GpioConnectionDriverCapabilities GetCapabilities();
16 |
17 | ///
18 | /// Allocates the specified pin.
19 | ///
20 | /// The pin.
21 | /// The direction.
22 | void Allocate(ProcessorPin pin, PinDirection direction);
23 |
24 | ///
25 | /// Sets the pin resistor.
26 | ///
27 | /// The pin.
28 | /// The resistor.
29 | void SetPinResistor(ProcessorPin pin, PinResistor resistor);
30 |
31 | ///
32 | /// Sets the detected edges on an input pin.
33 | ///
34 | /// The pin.
35 | /// The edges.
36 | /// By default, both edges may be detected on input pins.
37 | void SetPinDetectedEdges(ProcessorPin pin, PinDetectedEdges edges);
38 |
39 | ///
40 | /// Waits for the specified pin to be in the specified state.
41 | ///
42 | /// The pin.
43 | /// if set to true waits for the pin to be up. Default value is true.
44 | /// The timeout. Default value is .
45 | /// If timeout is set to , a default timeout is used instead.
46 | void Wait(ProcessorPin pin, bool waitForUp = true, TimeSpan timeout = new TimeSpan());
47 |
48 | ///
49 | /// Releases the specified pin.
50 | ///
51 | /// The pin.
52 | void Release(ProcessorPin pin);
53 |
54 | ///
55 | /// Modified the status of a pin.
56 | ///
57 | /// The pin.
58 | /// The pin status.
59 | void Write(ProcessorPin pin, bool value);
60 |
61 | ///
62 | /// Reads the status of the specified pin.
63 | ///
64 | /// The pin.
65 | /// The pin status.
66 | bool Read(ProcessorPin pin);
67 |
68 | ///
69 | /// Reads the status of the specified pins.
70 | ///
71 | /// The pins.
72 | /// The pins status.
73 | ProcessorPins Read(ProcessorPins pins);
74 |
75 | #endregion
76 | }
77 | }
--------------------------------------------------------------------------------
/Pi.IO.GeneralPurpose/InputPinConfiguration.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.GeneralPurpose
2 | {
3 | ///
4 | /// Represents configuration of an input pin.
5 | ///
6 | public class InputPinConfiguration : PinConfiguration
7 | {
8 | #region Instance Management
9 |
10 | ///
11 | /// Initializes a new instance of the class.
12 | ///
13 | /// The pin.
14 | public InputPinConfiguration(ProcessorPin pin) : base(pin){}
15 |
16 | #endregion
17 |
18 | #region Properties
19 |
20 | ///
21 | /// Gets the direction.
22 | ///
23 | public override PinDirection Direction
24 | {
25 | get { return PinDirection.Input; }
26 | }
27 |
28 | ///
29 | /// Gets or sets the resistor.
30 | ///
31 | ///
32 | /// The resistor.
33 | ///
34 | public PinResistor Resistor { get; set; }
35 |
36 | #endregion
37 | }
38 | }
--------------------------------------------------------------------------------
/Pi.IO.GeneralPurpose/OutputPinConfiguration.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.GeneralPurpose
2 | {
3 | ///
4 | /// Represents the configuration of an output pin.
5 | ///
6 | public class OutputPinConfiguration : PinConfiguration
7 | {
8 | #region Instance Management
9 |
10 | ///
11 | /// Initializes a new instance of the class.
12 | ///
13 | /// The pin.
14 | public OutputPinConfiguration(ProcessorPin pin) : base(pin){}
15 |
16 | #endregion
17 |
18 | #region Properties
19 |
20 | ///
21 | /// Gets or sets a value indicating whether this is enabled on connection.
22 | ///
23 | ///
24 | /// true if enabled; otherwise, false.
25 | ///
26 | public bool Enabled { get; set; }
27 |
28 | ///
29 | /// Gets the direction.
30 | ///
31 | public override PinDirection Direction
32 | {
33 | get { return PinDirection.Output; }
34 | }
35 |
36 | #endregion
37 | }
38 | }
--------------------------------------------------------------------------------
/Pi.IO.GeneralPurpose/Pi.IO.GeneralPurpose.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 | 0.0.1-preview1
6 | true
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/Pi.IO.GeneralPurpose/PinConfiguration.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 |
5 | #endregion
6 |
7 | namespace Pi.IO.GeneralPurpose
8 | {
9 | ///
10 | /// Represents the configuration of a pin.
11 | ///
12 | public abstract class PinConfiguration
13 | {
14 | #region Instance Management
15 |
16 | ///
17 | /// Initializes a new instance of the class.
18 | ///
19 | /// The pin.
20 | protected PinConfiguration(ProcessorPin pin)
21 | {
22 | Pin = pin;
23 | }
24 |
25 | #endregion
26 |
27 | #region Properties
28 |
29 | ///
30 | /// Gets the pin.
31 | ///
32 | public ProcessorPin Pin { get; private set; }
33 |
34 | ///
35 | /// Gets the direction.
36 | ///
37 | public abstract PinDirection Direction { get; }
38 |
39 | ///
40 | /// Gets or sets the name.
41 | ///
42 | ///
43 | /// The name.
44 | ///
45 | public string Name { get; set; }
46 |
47 | ///
48 | /// Gets or sets a value indicating whether this is reversed.
49 | ///
50 | ///
51 | /// true if reversed; otherwise, false.
52 | ///
53 | /// If set to true, pin value will be enabled when no signal is present, and disabled when a signal is present.
54 | public bool Reversed { get; set; }
55 |
56 | ///
57 | /// Gets or sets the status changed action.
58 | ///
59 | ///
60 | /// The status changed action.
61 | ///
62 | public Action StatusChangedAction { get; set; }
63 |
64 | #endregion
65 |
66 | #region Internal Methods
67 |
68 | internal bool GetEffective(bool value)
69 | {
70 | return Reversed ? !value : value;
71 | }
72 |
73 | #endregion
74 | }
75 | }
--------------------------------------------------------------------------------
/Pi.IO.GeneralPurpose/PinDetectedEdges.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 |
5 | #endregion
6 |
7 | namespace Pi.IO.GeneralPurpose
8 | {
9 | ///
10 | /// Represents detected edges.
11 | ///
12 | [Flags]
13 | public enum PinDetectedEdges
14 | {
15 | ///
16 | /// No changes are detected.
17 | ///
18 | None = 0,
19 |
20 | ///
21 | /// Rising edge changes are detected.
22 | ///
23 | Rising = 1,
24 |
25 | ///
26 | /// Falling edge changes are detected.
27 | ///
28 | Falling = 2,
29 |
30 | ///
31 | /// Both changes are detected.
32 | ///
33 | Both = Rising | Falling
34 | }
35 | }
--------------------------------------------------------------------------------
/Pi.IO.GeneralPurpose/PinDirection.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.GeneralPurpose
2 | {
3 | ///
4 | /// Represents the direction of a pin.
5 | ///
6 | public enum PinDirection
7 | {
8 | ///
9 | /// Pin is an input pin.
10 | ///
11 | Input,
12 |
13 | ///
14 | /// Pin is an output pin.
15 | ///
16 | Output
17 | }
18 | }
--------------------------------------------------------------------------------
/Pi.IO.GeneralPurpose/PinResistor.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.GeneralPurpose
2 | {
3 | ///
4 | /// Represents the resistor enabled on an input.
5 | ///
6 | public enum PinResistor
7 | {
8 | ///
9 | /// No resistor is enabled on the input.
10 | ///
11 | None,
12 |
13 | ///
14 | /// A pull-down resistor is enabled.
15 | ///
16 | PullDown,
17 |
18 | ///
19 | /// A pull-up resistor is enabled.
20 | ///
21 | PullUp
22 | }
23 | }
--------------------------------------------------------------------------------
/Pi.IO.GeneralPurpose/PinStatusEventArgs.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 |
5 | #endregion
6 |
7 | namespace Pi.IO.GeneralPurpose
8 | {
9 | ///
10 | /// Represents event arguments related to pin status.
11 | ///
12 | public class PinStatusEventArgs : EventArgs
13 | {
14 | #region Properties
15 |
16 | ///
17 | /// Gets the configuration.
18 | ///
19 | public PinConfiguration Configuration { get; internal set; }
20 |
21 | ///
22 | /// Gets a value indicating whether this is enabled.
23 | ///
24 | ///
25 | /// true if enabled; otherwise, false.
26 | ///
27 | public bool Enabled { get; internal set; }
28 |
29 | #endregion
30 | }
31 | }
--------------------------------------------------------------------------------
/Pi.IO.GeneralPurpose/ProcessorPinExtensionMethods.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Linq;
6 |
7 | #endregion
8 |
9 | namespace Pi.IO.GeneralPurpose
10 | {
11 | ///
12 | /// Provides extension methods for and objects.
13 | ///
14 | public static class ProcessorPinExtensionMethods
15 | {
16 | #region Methods
17 |
18 | ///
19 | /// Enumerates the specified pins.
20 | ///
21 | /// The pins.
22 | /// The pins.
23 | public static IEnumerable Enumerate(this ProcessorPins pins)
24 | {
25 | return ((Enum.GetValues(typeof (ProcessorPin)) as ProcessorPin[]) ?? new ProcessorPin[0])
26 | .Distinct()
27 | .Where(p => (pins & (ProcessorPins) ((uint) 1 << (int) p)) != ProcessorPins.None)
28 | .ToArray();
29 | }
30 |
31 | #endregion
32 | }
33 | }
--------------------------------------------------------------------------------
/Pi.IO.GeneralPurpose/SwitchInputPinConfiguration.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.GeneralPurpose
2 | {
3 | ///
4 | /// Represents the configuration of an input pin acting as a switch.
5 | ///
6 | public class SwitchInputPinConfiguration : InputPinConfiguration
7 | {
8 | #region Instance Management
9 |
10 | ///
11 | /// Initializes a new instance of the class.
12 | ///
13 | /// The pin.
14 | public SwitchInputPinConfiguration(ProcessorPin pin) : base(pin){}
15 |
16 | internal SwitchInputPinConfiguration(InputPinConfiguration pin) : base(pin.Pin)
17 | {
18 | Reversed = pin.Reversed;
19 | Name = pin.Name;
20 | }
21 |
22 | #endregion
23 |
24 | #region Properties
25 |
26 | ///
27 | /// Gets the direction.
28 | ///
29 | public override PinDirection Direction
30 | {
31 | get { return PinDirection.Input; }
32 | }
33 |
34 | ///
35 | /// Gets or sets a value indicating whether this is enabled.
36 | ///
37 | ///
38 | /// true if enabled; otherwise, false.
39 | ///
40 | public bool Enabled { get; set; }
41 |
42 | #endregion
43 | }
44 | }
--------------------------------------------------------------------------------
/Pi.IO.InterIntegratedCircuit/I2cAction.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.InterIntegratedCircuit
2 | {
3 | using System;
4 |
5 | public abstract class I2cAction
6 | {
7 | protected I2cAction(byte[] buffer)
8 | {
9 | if (buffer == null)
10 | {
11 | throw new ArgumentNullException("buffer");
12 | }
13 |
14 | Buffer = buffer;
15 | }
16 |
17 | public byte[] Buffer { get; private set; }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Pi.IO.InterIntegratedCircuit/I2cDeviceConnection.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.InterIntegratedCircuit
2 | {
3 | using System;
4 |
5 | ///
6 | /// Represents a connection to the I2C device.
7 | ///
8 | public class I2cDeviceConnection
9 | {
10 | #region Fields
11 |
12 | private readonly I2cDriver driver;
13 | private readonly int deviceAddress;
14 |
15 | #endregion
16 |
17 | #region Instance Management
18 |
19 | internal I2cDeviceConnection(I2cDriver driver, int deviceAddress)
20 | {
21 | this.driver = driver;
22 | this.deviceAddress = deviceAddress;
23 | }
24 |
25 | #endregion
26 |
27 | #region Properties
28 |
29 | ///
30 | /// Gets the device address.
31 | ///
32 | ///
33 | /// The device address.
34 | ///
35 | public int DeviceAddress
36 | {
37 | get { return deviceAddress; }
38 | }
39 |
40 |
41 | #endregion
42 |
43 | #region Methods
44 |
45 | ///
46 | /// Executes the specified transaction.
47 | ///
48 | /// The transaction.
49 | public void Execute(I2cTransaction transaction)
50 | {
51 | if (transaction == null)
52 | {
53 | throw new ArgumentNullException("transaction");
54 | }
55 |
56 | driver.Execute(deviceAddress, transaction);
57 | }
58 |
59 | ///
60 | /// Writes the specified buffer.
61 | ///
62 | /// The buffer.
63 | public void Write(params byte[] buffer)
64 | {
65 | Execute(new I2cTransaction(new I2cWriteAction(buffer)));
66 | }
67 |
68 | ///
69 | /// Writes the specified byte.
70 | ///
71 | /// The value.
72 | public void WriteByte(byte value)
73 | {
74 | Execute(new I2cTransaction(new I2cWriteAction(value)));
75 | }
76 |
77 | ///
78 | /// Reads the specified number of bytes.
79 | ///
80 | /// The byte count.
81 | /// The buffer.
82 | public byte[] Read(int byteCount)
83 | {
84 | var readAction = new I2cReadAction(new byte[byteCount]);
85 | Execute(new I2cTransaction(readAction));
86 |
87 | return readAction.Buffer;
88 | }
89 |
90 | ///
91 | /// Reads a byte.
92 | ///
93 | /// The byte.
94 | public byte ReadByte()
95 | {
96 | return Read(1)[0];
97 | }
98 |
99 | #endregion
100 | }
101 | }
--------------------------------------------------------------------------------
/Pi.IO.InterIntegratedCircuit/I2cReadAction.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.InterIntegratedCircuit
2 | {
3 | ///
4 | /// Defines an I2C read action.
5 | ///
6 | public class I2cReadAction : I2cAction
7 | {
8 | ///
9 | /// Initializes a new instance of the class.
10 | ///
11 | /// The buffer which should be used to store the received data.
12 | public I2cReadAction(params byte[] buffer)
13 | : base(buffer)
14 | {
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/Pi.IO.InterIntegratedCircuit/I2cTransaction.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.InterIntegratedCircuit
2 | {
3 | using System;
4 |
5 | ///
6 | /// Defines an I2C data transaction.
7 | ///
8 | public class I2cTransaction
9 | {
10 | ///
11 | /// Initializes a new instance of the class.
12 | ///
13 | /// The actions which should be performed within the transaction.
14 | public I2cTransaction(params I2cAction[] actions)
15 | {
16 | if (actions == null)
17 | {
18 | throw new ArgumentNullException("actions");
19 | }
20 |
21 | Actions = actions;
22 | }
23 |
24 | ///
25 | /// Gets the actions.
26 | ///
27 | public I2cAction[] Actions { get; private set; }
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/Pi.IO.InterIntegratedCircuit/I2cWriteAction.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.InterIntegratedCircuit
2 | {
3 | ///
4 | /// Defines an I2C write action.
5 | ///
6 | public class I2cWriteAction : I2cAction
7 | {
8 | ///
9 | /// Initializes a new instance of the class.
10 | ///
11 | /// The buffer with data which should be written.
12 | public I2cWriteAction(params byte[] buffer)
13 | : base(buffer)
14 | {
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/Pi.IO.InterIntegratedCircuit/Interop.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 | using System.Runtime.InteropServices;
5 |
6 | #endregion
7 |
8 | namespace Pi.IO.InterIntegratedCircuit
9 | {
10 | internal static class Interop
11 | {
12 | #region BCM2835
13 |
14 | #region Constants
15 |
16 | public const uint BCM2835_PERI_BASE = 0x20000000;
17 | public const uint BCM2835_GPIO_BASE = (BCM2835_PERI_BASE + 0x200000);
18 | public const uint BCM2835_BSC0_BASE = (BCM2835_PERI_BASE + 0x205000);
19 | public const uint BCM2835_BSC1_BASE = (BCM2835_PERI_BASE + 0x804000);
20 |
21 | public const uint BCM2836_PERI_BASE = 0x3F000000;
22 | public const uint BCM2836_GPIO_BASE = (BCM2836_PERI_BASE + 0x200000);
23 | public const uint BCM2836_BSC0_BASE = (BCM2836_PERI_BASE + 0x205000);
24 | public const uint BCM2836_BSC1_BASE = (BCM2836_PERI_BASE + 0x804000);
25 |
26 | public const uint BCM2835_BLOCK_SIZE = (4*1024);
27 |
28 | public const uint BCM2835_BSC_C = 0x0000;
29 | public const uint BCM2835_BSC_S = 0x0004;
30 | public const uint BCM2835_BSC_DLEN = 0x0008;
31 | public const uint BCM2835_BSC_A = 0x000c;
32 | public const uint BCM2835_BSC_FIFO = 0x0010;
33 | public const uint BCM2835_BSC_DIV = 0x0014;
34 |
35 | public const uint BCM2835_BSC_C_CLEAR_1 = 0x00000020;
36 | public const uint BCM2835_BSC_C_CLEAR_2 = 0x00000010;
37 | public const uint BCM2835_BSC_C_I2CEN = 0x00008000;
38 | public const uint BCM2835_BSC_C_ST = 0x00000080;
39 | public const uint BCM2835_BSC_C_READ = 0x00000001;
40 |
41 | public const uint BCM2835_BSC_S_CLKT = 0x00000200;
42 | public const uint BCM2835_BSC_S_ERR = 0x00000100;
43 | public const uint BCM2835_BSC_S_DONE = 0x00000002;
44 | public const uint BCM2835_BSC_S_TXD = 0x00000010;
45 | public const uint BCM2835_BSC_S_RXD = 0x00000020;
46 |
47 | public const uint BCM2835_BSC_FIFO_SIZE = 16;
48 |
49 | public const uint BCM2835_CORE_CLK_HZ = 250000000;
50 |
51 | public const uint BCM2835_GPIO_FSEL_INPT = 0;
52 | public const uint BCM2835_GPIO_FSEL_ALT0 = 4;
53 | public const uint BCM2835_GPIO_FSEL_MASK = 7;
54 |
55 | public const uint BCM2835_GPFSEL0 = 0x0000;
56 |
57 | #endregion
58 |
59 | #endregion
60 |
61 | #region Libc
62 |
63 | #region Constants
64 |
65 | public const int O_RDWR = 2;
66 | public const int O_SYNC = 10000;
67 |
68 | public const int PROT_READ = 1;
69 | public const int PROT_WRITE = 2;
70 |
71 | public const int MAP_SHARED = 1;
72 | public const int MAP_FAILED = -1;
73 |
74 | #endregion
75 |
76 | #region Methods
77 |
78 | [DllImport("libc.so.6", EntryPoint = "open")]
79 | public static extern IntPtr open(string fileName, int mode);
80 |
81 | [DllImport("libc.so.6", EntryPoint = "close")]
82 | public static extern void close(IntPtr file);
83 |
84 | [DllImport("libc.so.6", EntryPoint = "mmap")]
85 | public static extern IntPtr mmap(IntPtr address, uint size, int protect, int flags, IntPtr file, uint offset);
86 |
87 | [DllImport("libc.so.6", EntryPoint = "munmap")]
88 | public static extern IntPtr munmap(IntPtr address, uint size);
89 |
90 | #endregion
91 |
92 | #endregion
93 | }
94 | }
--------------------------------------------------------------------------------
/Pi.IO.InterIntegratedCircuit/Pi.IO.InterIntegratedCircuit.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 | 0.0.1-preview1
6 | true
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/Pi.IO.Interop/EnumTypes/MemoryFlags.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Pi.IO.Interop
4 | {
5 | [Flags]
6 | public enum MemoryFlags
7 | {
8 | None = 0,
9 | Shared = 1
10 | }
11 | }
--------------------------------------------------------------------------------
/Pi.IO.Interop/EnumTypes/MemoryProtection.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Pi.IO.Interop
4 | {
5 | [Flags]
6 | public enum MemoryProtection
7 | {
8 | None = 0,
9 | Read = 1,
10 | Write = 2,
11 | ReadWrite = Read | Write
12 | }
13 | }
--------------------------------------------------------------------------------
/Pi.IO.Interop/EnumTypes/UnixFileMode.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Pi.IO.Interop
4 | {
5 | ///
6 | /// File access mode
7 | ///
8 | [Flags]
9 | public enum UnixFileMode
10 | {
11 | ///
12 | /// The file will be opened with read-only access.
13 | ///
14 | ReadOnly = 1,
15 | ///
16 | /// The file will be opened with read/write access.
17 | ///
18 | ReadWrite = 2,
19 | ///
20 | /// When possible, the file is opened in nonblocking mode.
21 | ///
22 | NonBlocking = 4,
23 | ///
24 | /// The file is opened for synchronous I/O.
25 | ///
26 | Synchronized = 10000
27 | }
28 | }
--------------------------------------------------------------------------------
/Pi.IO.Interop/ErrNum.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.InteropServices;
3 |
4 | namespace Pi.IO.Interop
5 | {
6 | public static class ErrNum
7 | {
8 | #region libc imports
9 | [DllImport("libc", EntryPoint = "strerror", SetLastError = true)]
10 | private static extern IntPtr strerror(int errnum);
11 | #endregion
12 |
13 | #region Methods
14 | public static void ThrowOnPInvokeError(this int result, string message = null)
15 | where TException : Exception, new()
16 | {
17 | if (result >= 0) {
18 | return;
19 | }
20 |
21 | var type = typeof(TException);
22 | var constructorInfo = type.GetConstructor(new[] { typeof(string) });
23 | if (ReferenceEquals(constructorInfo, null)) {
24 | throw new TException();
25 | }
26 |
27 | var err = Marshal.GetLastWin32Error();
28 | var messagePtr = strerror(err);
29 |
30 | var strErrorMessage = (messagePtr != IntPtr.Zero)
31 | ? Marshal.PtrToStringAuto(messagePtr)
32 | : "unknown";
33 |
34 | var exceptionMessage = (message == null)
35 | ? string.Format("Error {0}: {1}", err, strErrorMessage)
36 | : string.Format(message, result, err, strErrorMessage);
37 |
38 | throw (TException)constructorInfo.Invoke(new object[] { exceptionMessage });
39 | }
40 | #endregion
41 | }
42 | }
--------------------------------------------------------------------------------
/Pi.IO.Interop/Exceptions/MemoryMapFailedException.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.Serialization;
3 |
4 | namespace Pi.IO.Interop
5 | {
6 | [Serializable]
7 | public class MemoryMapFailedException : Exception {
8 | public MemoryMapFailedException() {}
9 | public MemoryMapFailedException(string message) : base(message) {}
10 | public MemoryMapFailedException(string message, Exception innerException) : base(message, innerException) {}
11 | protected MemoryMapFailedException(SerializationInfo info, StreamingContext context) : base(info, context) {}
12 | }
13 | }
--------------------------------------------------------------------------------
/Pi.IO.Interop/Exceptions/MemoryUnmapFailedException.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.Serialization;
3 |
4 | namespace Pi.IO.Interop
5 | {
6 | [Serializable]
7 | public class MemoryUnmapFailedException : Exception {
8 | public MemoryUnmapFailedException() {}
9 | public MemoryUnmapFailedException(string message) : base(message) {}
10 | public MemoryUnmapFailedException(string message, Exception innerException) : base(message, innerException) {}
11 | protected MemoryUnmapFailedException(SerializationInfo info, StreamingContext context) : base(info, context) {}
12 | }
13 | }
--------------------------------------------------------------------------------
/Pi.IO.Interop/IControlDevice.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Pi.IO.Interop
4 | {
5 | ///
6 | /// A Linux I/O control device.
7 | ///
8 | public interface IControlDevice : IDisposable
9 | {
10 | ///
11 | /// The function manipulates the underlying device parameters of special files. In particular, many operating characteristics of character special files (e.g. terminals) may be controlled with ioctl requests.
12 | ///
13 | /// A device-dependent request code.
14 | /// The data to be transmitted.
15 | /// Usually, on success zero is returned. A few ioctls use the return value as an output parameter and return a nonnegative value on success. On error, -1 is returned, and errno is set appropriately.
16 | int Control(UInt32 request, ref UInt32 data);
17 |
18 | ///
19 | /// The function manipulates the underlying device parameters of special files. In particular, many operating characteristics of character special files (e.g. terminals) may be controlled with ioctl requests.
20 | ///
21 | /// A device-dependent request code.
22 | /// The data to be transmitted.
23 | /// Usually, on success zero is returned. A few ioctls use the return value as an output parameter and return a nonnegative value on success. On error, -1 is returned, and errno is set appropriately.
24 | int Control(UInt32 request, ref byte data);
25 |
26 | ///
27 | /// The function manipulates the underlying device parameters of special files. In particular, many operating characteristics of character special files (e.g. terminals) may be controlled with ioctl requests.
28 | ///
29 | /// A device-dependent request code.
30 | /// An untyped pointer to memory that contains the command/request data.
31 | ///
32 | int Control(UInt32 request, IntPtr data);
33 | }
34 | }
--------------------------------------------------------------------------------
/Pi.IO.Interop/IFile.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Pi.IO.Interop
4 | {
5 | ///
6 | /// A file resource that is controlled by the underling operation system.
7 | ///
8 | public interface IFile : IDisposable {
9 | ///
10 | /// The file descriptor
11 | ///
12 | int Descriptor { get; }
13 |
14 | ///
15 | /// The pathname to the file
16 | ///
17 | string Filename { get; }
18 | }
19 | }
--------------------------------------------------------------------------------
/Pi.IO.Interop/IMemory.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 |
4 | namespace Pi.IO.Interop
5 | {
6 | ///
7 | /// Managed/Unmanaged memory that can be used for P/Invoke operations.
8 | ///
9 | public interface IMemory : IDisposable, IEnumerable {
10 | ///
11 | /// Pointer to the memory address.
12 | ///
13 | IntPtr Pointer { get; }
14 |
15 | ///
16 | /// Size in bytes
17 | ///
18 | int Length { get; }
19 |
20 | ///
21 | /// Indexer, which will allow client code to use [] notation on the class instance itself.
22 | ///
23 | /// Offset to memory
24 | /// Byte at/from the specified position .
25 | byte this[int index] { get; set; }
26 |
27 | ///
28 | /// Writes at .
29 | ///
30 | /// Offset
31 | /// Data that shall be written.
32 | void Write(int offset, byte data);
33 |
34 | ///
35 | /// Reads a byte at .
36 | ///
37 | /// Offset
38 | /// The data.
39 | byte Read(int offset);
40 |
41 | ///
42 | /// Copies the bytes from to the memory.
43 | ///
44 | /// Source byte array.
45 | /// Copies the data starting from .
46 | /// Copies the data starting at to the memory.
47 | /// Copies bytes.
48 | void Copy(byte[] source, int sourceIndex, int destinationIndex, int length);
49 |
50 | ///
51 | /// Copies data from the memory to the supplied byte array.
52 | ///
53 | /// Copies the data starting from .
54 | /// Destination byte array.
55 | /// Copies the data starting at to the destination byte array.
56 | /// Copies bytes.
57 | void Copy(int sourceIndex, byte[] destination, int destinationIndex, int length);
58 | }
59 | }
--------------------------------------------------------------------------------
/Pi.IO.Interop/MemoryMap.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.InteropServices;
3 |
4 | namespace Pi.IO.Interop
5 | {
6 | public static class MemoryMap
7 | {
8 | #region Fields
9 | private static readonly IntPtr FAILED = new IntPtr(-1);
10 | #endregion
11 |
12 | #region Libc imports
13 | [DllImport("libc.so.6", EntryPoint = "mmap")]
14 | private static extern IntPtr mmap(IntPtr address, UIntPtr size, int protect, int flags, int file, UIntPtr offset);
15 |
16 | [DllImport("libc.so.6", EntryPoint = "munmap")]
17 | private static extern IntPtr munmap(IntPtr address, UIntPtr size);
18 | #endregion
19 |
20 | #region Methods
21 | public static IntPtr Create(IntPtr address, ulong size, MemoryProtection protection, MemoryFlags memoryflags, int fileDescriptor, ulong offset) {
22 | var result = mmap(address, new UIntPtr(size), (int) protection, (int) memoryflags, fileDescriptor, new UIntPtr(offset));
23 | ThrowOnError(result);
24 | return result;
25 | }
26 |
27 | public static IntPtr Create(IntPtr address, uint size, MemoryProtection protection, MemoryFlags memoryflags, int fileDescriptor, uint offset) {
28 | var result = mmap(address, new UIntPtr(size), (int)protection, (int)memoryflags, fileDescriptor, new UIntPtr(offset));
29 | ThrowOnError(result);
30 | return result;
31 | }
32 |
33 | public static void Close(IntPtr address, ulong size) {
34 | var result = munmap(address, new UIntPtr(size));
35 | ThrowOnError(result);
36 | }
37 |
38 | public static void Close(IntPtr address, uint size) {
39 | var result = munmap(address, new UIntPtr(size));
40 | ThrowOnError(result);
41 | }
42 | #endregion
43 |
44 | #region Private Helpers
45 | private static void ThrowOnError(IntPtr result)
46 | where TException: Exception, new()
47 | {
48 | if (result == FAILED) {
49 | throw new TException();
50 | }
51 | }
52 | #endregion
53 | }
54 | }
--------------------------------------------------------------------------------
/Pi.IO.Interop/Pi.IO.Interop.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 | 0.0.1-preview1
6 | true
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/Pi.IO.SerialPeripheralInterface/Endianness.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO.SerialPeripheralInterface
2 | {
3 | ///
4 | /// Represents the endianness of a SPI communication.
5 | ///
6 | public enum Endianness
7 | {
8 | ///
9 | /// The communication is little endian.
10 | ///
11 | LittleEndian,
12 |
13 | ///
14 | /// The communication is big endian.
15 | ///
16 | BigEndian
17 | }
18 | }
--------------------------------------------------------------------------------
/Pi.IO.SerialPeripheralInterface/EnumTypes/SpiMode.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Pi.IO.SerialPeripheralInterface
4 | {
5 | ///
6 | /// SPI mode
7 | ///
8 | [Flags]
9 | public enum SpiMode : uint
10 | {
11 | ///
12 | /// Clock phase, if set CPHA=1, otherwise CPHA=0.
13 | ///
14 | ClockPhase = Interop.SPI_CPHA,
15 |
16 | ///
17 | /// Clock polarity, if set CPOL=1, otherwise CPOL=0.
18 | ///
19 | ClockPolarity = Interop.SPI_CPOL,
20 |
21 | ///
22 | /// Chip select is a high signal.
23 | ///
24 | ChipSelectActiveHigh = Interop.SPI_CS_HIGH,
25 |
26 | ///
27 | /// The least significant bit comes first.
28 | ///
29 | LeastSignificantBitFirst = Interop.SPI_LSB_FIRST,
30 |
31 | ///
32 | /// Special 3-wire configuration.
33 | ///
34 | ThreeWire = Interop.SPI_3WIRE,
35 | ///
36 | /// Three-wire serial buses
37 | ///
38 | SlaveInOutShared = Interop.SPI_3WIRE,
39 | ///
40 | /// Loopback
41 | ///
42 | Loopback = Interop.SPI_LOOP,
43 | ///
44 | /// Send no chip select signal.
45 | ///
46 | NoChipSelect = Interop.SPI_NO_CS,
47 | ///
48 | /// Slave pulls low to pause.
49 | ///
50 | Ready = Interop.SPI_READY,
51 | ///
52 | /// Slave pulls low to pause.
53 | ///
54 | SlavePullsLowToPause = Interop.SPI_READY,
55 |
56 | ///
57 | /// CPOL=0, CPHA=0
58 | ///
59 | Mode0 = Interop.SPI_MODE_0,
60 | ///
61 | /// CPOL=0, CPHA=1
62 | ///
63 | Mode1 = Interop.SPI_MODE_1,
64 | ///
65 | /// CPOL =1, CPHA=0
66 | ///
67 | Mode2 = Interop.SPI_MODE_2,
68 | ///
69 | /// CPOL=1, CPHA=1
70 | ///
71 | Mode3 = Interop.SPI_MODE_3
72 | }
73 | }
--------------------------------------------------------------------------------
/Pi.IO.SerialPeripheralInterface/EnumTypes/SpiTransferMode.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Pi.IO.SerialPeripheralInterface
4 | {
5 | ///
6 | /// Selects if data should be read, written or both.
7 | ///
8 | [Flags]
9 | public enum SpiTransferMode
10 | {
11 | ///
12 | /// Write data to the chip.
13 | ///
14 | Write = 1,
15 |
16 | ///
17 | /// Read data from the chip.
18 | ///
19 | Read = 2,
20 |
21 | ///
22 | /// Write and read data simultaneously.
23 | ///
24 | ReadWrite = 3
25 | }
26 | }
--------------------------------------------------------------------------------
/Pi.IO.SerialPeripheralInterface/Exceptions/ReadonlyTransferBufferException.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.Serialization;
3 |
4 | namespace Pi.IO.SerialPeripheralInterface
5 | {
6 | #pragma warning disable 1591
7 | [Serializable]
8 | public class ReadOnlyTransferBufferException : Exception
9 | {
10 | public ReadOnlyTransferBufferException() {}
11 | public ReadOnlyTransferBufferException(string message) : base(message) {}
12 | public ReadOnlyTransferBufferException(string message, Exception innerException) : base(message, innerException) {}
13 | protected ReadOnlyTransferBufferException(SerializationInfo info, StreamingContext context) : base(info, context) {}
14 | }
15 | #pragma warning restore 1591
16 | }
--------------------------------------------------------------------------------
/Pi.IO.SerialPeripheralInterface/Exceptions/SendSpiMessageException.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.Serialization;
3 |
4 | namespace Pi.IO.SerialPeripheralInterface
5 | {
6 | #pragma warning disable 1591
7 | [Serializable]
8 | public class SendSpiMessageException : Exception {
9 | public SendSpiMessageException() {}
10 | public SendSpiMessageException(string message) : base(message) {}
11 | public SendSpiMessageException(string message, Exception innerException) : base(message, innerException) {}
12 | protected SendSpiMessageException(SerializationInfo info, StreamingContext context) : base(info, context) {}
13 | }
14 | #pragma warning restore 1591
15 | }
--------------------------------------------------------------------------------
/Pi.IO.SerialPeripheralInterface/Exceptions/SetBitsPerWordException.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.Serialization;
3 |
4 | namespace Pi.IO.SerialPeripheralInterface
5 | {
6 | #pragma warning disable 1591
7 | [Serializable]
8 | public class SetBitsPerWordException : Exception {
9 | public SetBitsPerWordException() {}
10 | public SetBitsPerWordException(string message) : base(message) {}
11 | public SetBitsPerWordException(string message, Exception innerException) : base(message, innerException) {}
12 | protected SetBitsPerWordException(SerializationInfo info, StreamingContext context) : base(info, context) {}
13 | }
14 | #pragma warning restore 1591
15 | }
--------------------------------------------------------------------------------
/Pi.IO.SerialPeripheralInterface/Exceptions/SetMaxSpeedException.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.Serialization;
3 |
4 | namespace Pi.IO.SerialPeripheralInterface
5 | {
6 | #pragma warning disable 1591
7 | [Serializable]
8 | public class SetMaxSpeedException : Exception {
9 | public SetMaxSpeedException() {}
10 | public SetMaxSpeedException(string message) : base(message) {}
11 | public SetMaxSpeedException(string message, Exception innerException) : base(message, innerException) {}
12 | protected SetMaxSpeedException(SerializationInfo info, StreamingContext context) : base(info, context) {}
13 | }
14 | #pragma warning restore 1591
15 | }
--------------------------------------------------------------------------------
/Pi.IO.SerialPeripheralInterface/Exceptions/SetSpiModeException.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.Serialization;
3 |
4 | namespace Pi.IO.SerialPeripheralInterface
5 | {
6 | #pragma warning disable 1591
7 | [Serializable]
8 | public class SetSpiModeException : Exception {
9 | public SetSpiModeException() {}
10 | public SetSpiModeException(string message) : base(message) {}
11 | public SetSpiModeException(string message, Exception innerException) : base(message, innerException) {}
12 | protected SetSpiModeException(SerializationInfo info, StreamingContext context) : base(info, context) {}
13 | }
14 | #pragma warning restore 1591
15 | }
--------------------------------------------------------------------------------
/Pi.IO.SerialPeripheralInterface/Exceptions/WriteOnlyTransferBufferException.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.Serialization;
3 |
4 | namespace Pi.IO.SerialPeripheralInterface
5 | {
6 | #pragma warning disable 1591
7 | [Serializable]
8 | public class WriteOnlyTransferBufferException : Exception
9 | {
10 | public WriteOnlyTransferBufferException() {}
11 | public WriteOnlyTransferBufferException(string message) : base(message) {}
12 | public WriteOnlyTransferBufferException(string message, Exception innerException) : base(message, innerException) {}
13 | protected WriteOnlyTransferBufferException(SerializationInfo info, StreamingContext context) : base(info, context) {}
14 | }
15 | #pragma warning restore 1591
16 | }
--------------------------------------------------------------------------------
/Pi.IO.SerialPeripheralInterface/ISpiControlDevice.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Pi.IO.Interop;
3 |
4 | namespace Pi.IO.SerialPeripheralInterface
5 | {
6 | ///
7 | /// A Linux I/O control device that additionally can send/receive SPI data structures.
8 | ///
9 | public interface ISpiControlDevice : IControlDevice
10 | {
11 | ///
12 | /// The function manipulates the underlying device parameters of special files. In particular, many operating characteristics of character special files (e.g. terminals) may be controlled with ioctl requests.
13 | ///
14 | /// A device-dependent request code.
15 | /// The SPI control data to be transmitted.
16 | /// Usually, on success zero is returned. A few ioctls use the return value as an output parameter and return a nonnegative value on success. On error, -1 is returned, and errno is set appropriately.
17 | int Control(UInt32 request, ref SpiTransferControlStructure data);
18 |
19 | ///
20 | /// The function manipulates the underlying device parameters of special files. In particular, many operating characteristics of character special files (e.g. terminals) may be controlled with ioctl requests.
21 | ///
22 | /// A device-dependent request code.
23 | /// The SPI control data structures to be transmitted.
24 | /// Usually, on success zero is returned. A few ioctls use the return value as an output parameter and return a nonnegative value on success. On error, -1 is returned, and errno is set appropriately.
25 | int Control(UInt32 request, SpiTransferControlStructure[] data);
26 | }
27 | }
--------------------------------------------------------------------------------
/Pi.IO.SerialPeripheralInterface/ISpiTransferBuffer.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 | using Pi.IO.Interop;
5 |
6 | #endregion
7 |
8 | namespace Pi.IO.SerialPeripheralInterface
9 | {
10 | ///
11 | /// A transfer buffer used to read from / write to the SPI bus.
12 | ///
13 | public interface ISpiTransferBuffer : IDisposable
14 | {
15 | #region Properties
16 |
17 | ///
18 | /// Temporary override of the device's wordsize
19 | ///
20 | ///
21 | /// The bits per word.
22 | ///
23 | byte BitsPerWord { get; set; }
24 |
25 | ///
26 | /// Temporary override of the device's bitrate (in Hz)
27 | ///
28 | ///
29 | /// The speed.
30 | ///
31 | UInt32 Speed { get; set; }
32 |
33 | ///
34 | /// If nonzero, how long to delay (in µ seconds) after the last bit transfer before optionally deselecting the device before the next transfer.
35 | ///
36 | ///
37 | /// The delay.
38 | ///
39 | UInt16 Delay { get; set; }
40 |
41 | ///
42 | /// Set to true to deselect device before starting the next transfer.
43 | ///
44 | ///
45 | /// true if device is delected before starting next transfer; otherwise, false.
46 | ///
47 | bool ChipSelectChange { get; set; }
48 |
49 | ///
50 | /// Pad.
51 | ///
52 | ///
53 | /// The pad.
54 | ///
55 | UInt32 Pad { get; set; }
56 |
57 | ///
58 | /// Specifies if the transfer shall read and/or write.
59 | ///
60 | ///
61 | /// The transfer mode.
62 | ///
63 | SpiTransferMode TransferMode { get; }
64 |
65 | ///
66 | /// Length of and buffers, in bytes
67 | ///
68 | ///
69 | /// The length.
70 | ///
71 | int Length { get; }
72 |
73 | ///
74 | /// Holds pointer to userspace buffer with transmit data, or null. If no data is provided, zeroes are shifted out
75 | ///
76 | ///
77 | /// The tx.
78 | ///
79 | IMemory Tx { get; }
80 |
81 | ///
82 | /// Holds pointer to userspace buffer for receive data, or null
83 | ///
84 | ///
85 | /// The rx.
86 | ///
87 | IMemory Rx { get; }
88 |
89 | ///
90 | /// The IOCTL structure that contains control information for a single SPI transfer
91 | ///
92 | ///
93 | /// The control structure.
94 | ///
95 | SpiTransferControlStructure ControlStructure { get; }
96 |
97 | #endregion
98 |
99 | }
100 | }
--------------------------------------------------------------------------------
/Pi.IO.SerialPeripheralInterface/ISpiTransferBufferCollection.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 | using System.Collections.Generic;
5 |
6 | #endregion
7 |
8 | namespace Pi.IO.SerialPeripheralInterface
9 | {
10 | ///
11 | /// A collection of transfer buffers that can be used to read from / write to the SPI bus.
12 | ///
13 | public interface ISpiTransferBufferCollection : IDisposable, IEnumerable
14 | {
15 | #region Properties
16 |
17 | ///
18 | /// Number of structures.
19 | ///
20 | int Length { get; }
21 |
22 | ///
23 | /// Can be used to request a specific from the collection.
24 | ///
25 | /// Index
26 | /// The requested
27 | ISpiTransferBuffer this[int index] { get; }
28 |
29 | #endregion
30 |
31 | #region Methods
32 |
33 | ///
34 | /// A method that returns a specific from the collection.
35 | ///
36 | /// Index
37 | /// The requested
38 | ISpiTransferBuffer Get(int index);
39 |
40 | #endregion
41 | }
42 | }
--------------------------------------------------------------------------------
/Pi.IO.SerialPeripheralInterface/Interop/Interop.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.InteropServices;
3 |
4 | namespace Pi.IO.SerialPeripheralInterface
5 | {
6 | // ReSharper disable InconsistentNaming
7 | internal static class Interop
8 | {
9 | public const UInt32 SPI_CPHA = 0x01;
10 | public const UInt32 SPI_CPOL = 0x02;
11 |
12 | public const UInt32 SPI_MODE_0 = (0 | 0);
13 | public const UInt32 SPI_MODE_1 = (0 | SPI_CPHA);
14 | public const UInt32 SPI_MODE_2 = (SPI_CPOL | 0);
15 | public const UInt32 SPI_MODE_3 = (SPI_CPOL | SPI_CPHA);
16 |
17 | public const UInt32 SPI_CS_HIGH = 0x04;
18 | public const UInt32 SPI_LSB_FIRST = 0x08;
19 | public const UInt32 SPI_3WIRE = 0x10;
20 |
21 | public const UInt32 SPI_LOOP = 0x20;
22 | public const UInt32 SPI_NO_CS = 0x40;
23 | public const UInt32 SPI_READY = 0x80;
24 |
25 | public const UInt32 SPI_IOC_MESSAGE_BASE = 0x40006b00;
26 | public const int SPI_IOC_MESSAGE_NUMBER_SHIFT = 16;
27 |
28 | private static readonly int transferMessageSize = Marshal.SizeOf(typeof(SpiTransferControlStructure));
29 |
30 | internal static UInt32 GetSpiMessageRequest(int numberOfMessages) {
31 | var size = unchecked((UInt32)(transferMessageSize * numberOfMessages));
32 | return SPI_IOC_MESSAGE_BASE | (size << SPI_IOC_MESSAGE_NUMBER_SHIFT);
33 | }
34 | }
35 |
36 | // ReSharper restore InconsistentNaming
37 | }
--------------------------------------------------------------------------------
/Pi.IO.SerialPeripheralInterface/Interop/SpiTransferControlStructure.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 | using System.Runtime.InteropServices;
5 |
6 | #endregion
7 |
8 | namespace Pi.IO.SerialPeripheralInterface
9 | {
10 | ///
11 | /// A IOCTL structure that describes a single SPI transfer
12 | ///
13 | [StructLayout(LayoutKind.Sequential, Pack = 0)]
14 | public struct SpiTransferControlStructure
15 | {
16 | #region Properties
17 |
18 | ///
19 | /// Holds pointer to userspace buffer with transmit data, or 0. If no data is provided, zeroes are shifted out
20 | ///
21 | public UInt64 Tx;
22 |
23 | ///
24 | /// Holds pointer to userspace buffer for receive data, or 0
25 | ///
26 | public UInt64 Rx;
27 |
28 | ///
29 | /// Length of and buffers, in bytes
30 | ///
31 | public UInt32 Length;
32 |
33 | ///
34 | /// Temporary override of the device's bitrate (in Hz)
35 | ///
36 | public UInt32 Speed;
37 |
38 | ///
39 | /// If nonzero, how long to delay (in µ seconds) after the last bit transfer before optionally deselecting the device before the next transfer
40 | ///
41 | public UInt16 Delay;
42 |
43 | ///
44 | /// Temporary override of the device's wordsize
45 | ///
46 | public Byte BitsPerWord;
47 |
48 | ///
49 | /// Set to true to deselect device before starting the next transfer
50 | ///
51 | public Byte ChipSelectChange;
52 |
53 | ///
54 | /// Pad
55 | ///
56 | public UInt32 Pad;
57 |
58 | #endregion
59 | }
60 | }
--------------------------------------------------------------------------------
/Pi.IO.SerialPeripheralInterface/Pi.IO.SerialPeripheralInterface.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 | 0.0.1-preview1
6 | true
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/Pi.IO.SerialPeripheralInterface/SpiConnectionSettings.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Pi.IO.SerialPeripheralInterface
4 | {
5 | ///
6 | /// SPI connection parameters
7 | ///
8 | public class SpiConnectionSettings
9 | {
10 | #region Fields
11 | private uint maxSpeed = 5000000;
12 | private ushort delay;
13 | private byte bitsPerWord = 8;
14 | #endregion
15 |
16 | #region Properties
17 | ///
18 | /// Clock speed in Hz
19 | ///
20 | public UInt32 MaxSpeed {
21 | get { return maxSpeed; }
22 | set { maxSpeed = value; }
23 | }
24 |
25 | ///
26 | /// If nonzero, how long to delay (in µ seconds) after the last bit transfer before optionally deselecting the device before the next transfer
27 | ///
28 | public UInt16 Delay {
29 | get { return delay; }
30 | set { delay = value; }
31 | }
32 |
33 | ///
34 | /// The device's word size
35 | ///
36 | public byte BitsPerWord {
37 | get { return bitsPerWord; }
38 | set { bitsPerWord = value; }
39 | }
40 |
41 | ///
42 | /// SPI mode
43 | ///
44 | public SpiMode Mode { get; set; }
45 |
46 | #endregion
47 | }
48 | }
--------------------------------------------------------------------------------
/Pi.IO.SerialPeripheralInterface/SpiControlDevice.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.InteropServices;
3 | using Pi.IO.Interop;
4 |
5 | namespace Pi.IO.SerialPeripheralInterface
6 | {
7 | ///
8 | /// A Linux I/O control device that additionally can send/receive SPI data structures.
9 | ///
10 | public class SpiControlDevice : ControlDevice, ISpiControlDevice
11 | {
12 | #region Libc imports
13 | [DllImport("libc", EntryPoint = "ioctl", SetLastError = true)]
14 | private static extern int ioctl(int descriptor, UInt32 request, ref SpiTransferControlStructure data);
15 |
16 | [DllImport("libc", EntryPoint = "ioctl", SetLastError = true)]
17 | private static extern int ioctl(int descriptor, UInt32 request, SpiTransferControlStructure[] data);
18 | #endregion
19 |
20 | #region Instance Management
21 | ///
22 | /// Initializes a new instance of the class.
23 | ///
24 | /// A opened special file that can be controlled using ioctl-system calls.
25 | /// will be disposed if the user calls Dispose on this instance.
26 | public SpiControlDevice(IFile file)
27 | :base(file)
28 | {}
29 |
30 | ///
31 | /// Initializes a new instance of the class.
32 | ///
33 | /// A opened special file that can be controlled using ioctl-system calls.
34 | /// If true the supplied will be disposed if the user calls Dispose on this instance.
35 | public SpiControlDevice(IFile file, bool disposeFile)
36 | :base(file, disposeFile){}
37 | #endregion
38 |
39 | #region Methods
40 | ///
41 | /// The function manipulates the underlying device parameters of special files. In particular, many operating characteristics of character special files (e.g. terminals) may be controlled with ioctl requests.
42 | ///
43 | /// A device-dependent request code.
44 | /// The data to be transmitted.
45 | /// Usually, on success zero is returned. A few ioctls use the return value as an output parameter and return a nonnegative value on success. On error, -1 is returned, and errno is set appropriately.
46 | public int Control(UInt32 request, ref SpiTransferControlStructure data) {
47 | var result = ioctl(file.Descriptor, request, ref data);
48 | return result;
49 | }
50 |
51 | ///
52 | /// The function manipulates the underlying device parameters of special files. In particular, many operating characteristics of character special files (e.g. terminals) may be controlled with ioctl requests.
53 | ///
54 | /// A device-dependent request code.
55 | /// The SPI control data structures to be transmitted.
56 | /// Usually, on success zero is returned. A few ioctls use the return value as an output parameter and return a nonnegative value on success. On error, -1 is returned, and errno is set appropriately.
57 | public int Control(UInt32 request, SpiTransferControlStructure[] data) {
58 | var result = ioctl(file.Descriptor, request, data);
59 | return result;
60 | }
61 | #endregion
62 | }
63 | }
--------------------------------------------------------------------------------
/Pi.IO.SerialPeripheralInterface/SpiSlaveSelectionContext.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 |
5 | #endregion
6 |
7 | namespace Pi.IO.SerialPeripheralInterface
8 | {
9 | ///
10 | /// Represents a SPI slave selection context.
11 | ///
12 | public class SpiSlaveSelectionContext : IDisposable
13 | {
14 | #region Fields
15 |
16 | private readonly SpiConnection connection;
17 |
18 | #endregion
19 |
20 | #region Instance Management
21 |
22 | internal SpiSlaveSelectionContext(SpiConnection connection)
23 | {
24 | this.connection = connection;
25 | }
26 |
27 | ///
28 | /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
29 | ///
30 | void IDisposable.Dispose()
31 | {
32 | connection.DeselectSlave();
33 | }
34 |
35 | #endregion
36 | }
37 | }
--------------------------------------------------------------------------------
/Pi.IO/AnalogValue.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO
2 | {
3 | ///
4 | /// Represents an analog value.
5 | ///
6 | public class AnalogValue
7 | {
8 | private decimal value;
9 | private decimal range;
10 |
11 | ///
12 | /// Initializes a new instance of the class.
13 | ///
14 | /// The total range (ie. maximum value).
15 | /// The value.
16 | public AnalogValue(decimal value, decimal range = 1)
17 | {
18 | this.range = range;
19 | this.value = value;
20 | }
21 |
22 | ///
23 | /// Gets or sets the discrete value.
24 | ///
25 | ///
26 | /// The discrete value.
27 | ///
28 | public decimal Value
29 | {
30 | get { return value; }
31 | set { this.value = value; }
32 | }
33 |
34 | ///
35 | /// Gets or sets the total range.
36 | ///
37 | ///
38 | /// The total range, ie. the maximum value.
39 | ///
40 | public decimal Range
41 | {
42 | get { return range; }
43 | set { range = value; }
44 | }
45 |
46 | ///
47 | /// Gets the relative value.
48 | ///
49 | ///
50 | /// The relative value.
51 | ///
52 | public decimal Relative
53 | {
54 | get { return value / range; }
55 | }
56 | }
57 | }
--------------------------------------------------------------------------------
/Pi.IO/BinaryPinExtensionMethods.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 |
5 | #endregion
6 |
7 | namespace Pi.IO
8 | {
9 | ///
10 | /// Provides extension methods for binary pins.
11 | ///
12 | public static class BinaryPinExtensionMethods
13 | {
14 | #region Methods
15 |
16 | ///
17 | /// Waits for a pin to reach the specified state, then measures the time it remains in this state.
18 | ///
19 | /// The measure pin.
20 | /// if set to true, wait for the pin to be up.
21 | /// The first phase timeout.
22 | /// The second phase timeout.
23 | ///
24 | /// The time the pin remains up, in milliseconds.
25 | ///
26 | public static TimeSpan Time(this IInputBinaryPin pin, bool waitForUp = true, TimeSpan phase1Timeout = new TimeSpan(), TimeSpan phase2Timeout = new TimeSpan())
27 | {
28 | pin.Wait(waitForUp, phase1Timeout);
29 |
30 | var waitDown = DateTime.UtcNow;
31 | pin.Wait(!waitForUp, phase2Timeout);
32 |
33 | return DateTime.UtcNow - waitDown;
34 | }
35 |
36 | #endregion
37 | }
38 | }
--------------------------------------------------------------------------------
/Pi.IO/ByteExtensionMethods.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Linq;
6 | using System.Text;
7 |
8 | #endregion
9 |
10 | namespace Pi.IO
11 | {
12 | ///
13 | /// Provides extension methods for byte and byte arrays.
14 | ///
15 | public static class ByteExtensionMethods
16 | {
17 | #region Methods
18 |
19 | ///
20 | /// Converts a byte array/enumerable to a bit string.
21 | ///
22 | /// bytes to be converted.
23 | /// A bit string
24 | public static string ToBitString(this IEnumerable bytes)
25 | {
26 | var sb = new StringBuilder(255);
27 | foreach (var value in bytes.Select(@byte => Convert.ToString(@byte, 2)))
28 | {
29 | if (value.Length < 8)
30 | {
31 | sb.Append(new string('0', 8 - value.Length));
32 | }
33 | sb.Append(value);
34 | }
35 | return sb.ToString();
36 | }
37 |
38 | #endregion
39 | }
40 | }
--------------------------------------------------------------------------------
/Pi.IO/IInputAnalogPin.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 |
5 | #endregion
6 |
7 | namespace Pi.IO
8 | {
9 | ///
10 | /// Provides an interface for input, analog pin.
11 | ///
12 | public interface IInputAnalogPin : IDisposable
13 | {
14 | #region Methods
15 |
16 | ///
17 | /// Reads the value of the pin.
18 | ///
19 | /// The value.
20 | AnalogValue Read();
21 |
22 | #endregion
23 | }
24 | }
--------------------------------------------------------------------------------
/Pi.IO/IInputBinaryPin.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 |
5 | #endregion
6 |
7 | namespace Pi.IO
8 | {
9 | ///
10 | /// Provides an interface for input, binary pins.
11 | ///
12 | public interface IInputBinaryPin : IDisposable
13 | {
14 | #region Methods
15 |
16 | ///
17 | /// Reads the state of the pin.
18 | ///
19 | /// true if the pin is in high state; otherwise, false.
20 | bool Read();
21 |
22 | ///
23 | /// Waits for the specified pin to be in the specified state.
24 | ///
25 | /// if set to true waits for the pin to be up. Default value is true.
26 | /// The timeout. Default value is .
27 | /// If timeout is set to , a default timeout is used instead.
28 | void Wait(bool waitForUp = true, TimeSpan timeout = new TimeSpan());
29 |
30 | #endregion
31 | }
32 | }
--------------------------------------------------------------------------------
/Pi.IO/IInputOutputBinaryPin.cs:
--------------------------------------------------------------------------------
1 | namespace Pi.IO
2 | {
3 | ///
4 | /// Provides an interface for bidirectional binary pins.
5 | ///
6 | public interface IInputOutputBinaryPin : IInputBinaryPin, IOutputBinaryPin
7 | {
8 | ///
9 | /// Prepares the pin to act as an input.
10 | ///
11 | void AsInput();
12 |
13 | ///
14 | /// Prepares the pin to act as an output.
15 | ///
16 | void AsOutput();
17 | }
18 | }
--------------------------------------------------------------------------------
/Pi.IO/IOutputAnalogPin.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 |
5 | #endregion
6 |
7 | namespace Pi.IO
8 | {
9 | ///
10 | /// Provides an interface for output, analog pin.
11 | ///
12 | public interface IOutputAnalogPin : IDisposable
13 | {
14 | #region Methods
15 |
16 | ///
17 | /// Writes the specified value to the pin.
18 | ///
19 | /// The value.
20 | void Write(AnalogValue value);
21 |
22 | #endregion
23 | }
24 | }
--------------------------------------------------------------------------------
/Pi.IO/IOutputBinaryPin.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 |
5 | #endregion
6 |
7 | namespace Pi.IO
8 | {
9 | ///
10 | /// Provides an interface for output, binary pins.
11 | ///
12 | public interface IOutputBinaryPin : IDisposable
13 | {
14 | #region Methods
15 |
16 | ///
17 | /// Writes the value of the pin.
18 | ///
19 | /// if set to true, pin is set to high state.
20 | void Write(bool state);
21 |
22 | #endregion
23 | }
24 | }
--------------------------------------------------------------------------------
/Pi.IO/Pi.IO.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 | 0.0.1-preview1
6 | true
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/Pi.IO/StringExtensionMethods.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 | using System.Linq;
5 |
6 | #endregion
7 |
8 | namespace Pi.IO
9 | {
10 | ///
11 | /// Provides extension methods for strings.
12 | ///
13 | public static class StringExtensionMethods
14 | {
15 | #region Methods
16 |
17 | ///
18 | /// Converts a bit string in MSBF order (most significant bit first) to a byte array.
19 | ///
20 | /// A bit string (e.g. "00101111").
21 | /// If true the bit string will be prefixed with '0' if it is not divisible by 8.
22 | /// An array starting with the most significant byte.
23 | public static byte[] BitStringToArray(this string bitString, bool prefixWithZero)
24 | {
25 | var requiredPrefixBits = bitString.Length%8;
26 | var @string = (requiredPrefixBits > 0 && prefixWithZero)
27 | ? new string('0', requiredPrefixBits) + bitString
28 | : bitString;
29 |
30 | return Enumerable
31 | .Range(0, @string.Length/8)
32 | .Select(pos => Convert.ToByte(@string.Substring(pos*8, 8), 2))
33 | .ToArray();
34 | }
35 |
36 | #endregion
37 | }
38 | }
--------------------------------------------------------------------------------
/Pi.System/ConnectorPinout.cs:
--------------------------------------------------------------------------------
1 | namespace Pi
2 | {
3 | ///
4 | /// The Raspberry Pi connector pinout revision.
5 | ///
6 | public enum ConnectorPinout
7 | {
8 | ///
9 | /// Connector pinout is unknown.
10 | ///
11 | Unknown,
12 |
13 | ///
14 | /// The first revision, as of Model B rev1.
15 | ///
16 | Rev1,
17 |
18 | ///
19 | /// The second revision, as of Model B rev2.
20 | ///
21 | Rev2,
22 |
23 | ///
24 | /// The third revision, as of Model B+.
25 | ///
26 | Plus,
27 | }
28 | }
--------------------------------------------------------------------------------
/Pi.System/Model.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.ComponentModel;
3 |
4 | namespace Pi
5 | {
6 | ///
7 | /// The Rasperry Pi model.
8 | ///
9 | public enum Model
10 | {
11 | ///
12 | /// Unknown model.
13 | ///
14 | Unknown,
15 |
16 | ///
17 | /// Model A.
18 | ///
19 | A,
20 |
21 | ///
22 | /// Model A+.
23 | ///
24 | APlus,
25 |
26 | ///
27 | /// Model B rev1.
28 | ///
29 | BRev1,
30 |
31 | ///
32 | /// Model B rev2.
33 | ///
34 | BRev2,
35 |
36 | ///
37 | /// Model B+.
38 | ///
39 | BPlus,
40 |
41 | ///
42 | /// Compute module.
43 | ///
44 | ComputeModule,
45 |
46 | ///
47 | /// Pi 2 Model B.
48 | ///
49 | B2,
50 |
51 | ///
52 | /// Pi Zero.
53 | ///
54 | Zero,
55 |
56 | ///
57 | /// Pi 3 Model B.
58 | ///
59 | B3
60 | }
61 |
62 | ///
63 | /// Provides extension methods for .
64 | ///
65 | public static class ModelExtensionMethods
66 | {
67 | ///
68 | /// Gets the model display name.
69 | ///
70 | /// The model.
71 | /// The display name, if known; otherwise, null.
72 | public static string GetDisplayName(this Model model)
73 | {
74 | switch (model)
75 | {
76 | case Model.Unknown:
77 | return null;
78 | case Model.A:
79 | return "Raspberry Pi Model A";
80 | case Model.APlus:
81 | return "Raspberry Pi Model A+";
82 | case Model.BRev1:
83 | return "Raspberry Pi Model B rev1";
84 | case Model.BRev2:
85 | return "Raspberry Pi Model B rev2";
86 | case Model.BPlus:
87 | return "Raspberry Pi Model B+";
88 | case Model.ComputeModule:
89 | return "Raspberry Pi Compute Module";
90 | case Model.B2:
91 | return "Raspberry Pi 2 Model B";
92 | case Model.Zero:
93 | return "Raspberry Pi Zero";
94 | case Model.B3:
95 | return "Raspberry Pi 3 Model B";
96 |
97 | default:
98 | throw new ArgumentOutOfRangeException("model");
99 | }
100 | }
101 | }
102 | }
--------------------------------------------------------------------------------
/Pi.System/Pi.System.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 | 0.0.1-preview1
6 | true
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/Pi.System/Processor.cs:
--------------------------------------------------------------------------------
1 | namespace Pi
2 | {
3 | ///
4 | /// The Raspberry Pi processor.
5 | ///
6 | public enum Processor
7 | {
8 | ///
9 | /// Processor is unknown.
10 | ///
11 | Unknown,
12 |
13 | ///
14 | /// Processor is a BCM2708.
15 | ///
16 | Bcm2708,
17 |
18 | ///
19 | /// Processor is a BCM2709.
20 | ///
21 | Bcm2709,
22 |
23 | ///
24 | /// Processor is a BCM2835.
25 | ///
26 | Bcm2835
27 | }
28 | }
--------------------------------------------------------------------------------
/Pi.System/Timers/HighResolutionTimer.cs:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Petermarcu/Pi/bf6c6234c19819095aa773cd997dc9dec5eea71e/Pi.System/Timers/HighResolutionTimer.cs
--------------------------------------------------------------------------------
/Pi.System/Timers/ITimer.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 |
5 | #endregion
6 |
7 | namespace Pi.Timers
8 | {
9 | ///
10 | /// Provides an interface for a timer.
11 | ///
12 | public interface ITimer
13 | {
14 | #region Properties
15 |
16 | ///
17 | /// Gets or sets the interval.
18 | ///
19 | ///
20 | /// The interval.
21 | ///
22 | TimeSpan Interval { get; set; }
23 |
24 | ///
25 | /// Gets or sets the action.
26 | ///
27 | ///
28 | /// The action.
29 | ///
30 | Action Action { get; set; }
31 |
32 | #endregion
33 |
34 | #region Methods
35 |
36 | ///
37 | /// Starts this instance.
38 | ///
39 | /// The delay before the first occurence.
40 | void Start(TimeSpan startDelay);
41 |
42 | ///
43 | /// Stops this instance.
44 | ///
45 | void Stop();
46 |
47 | #endregion
48 | }
49 | }
--------------------------------------------------------------------------------
/Pi.System/Timers/Interop.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 | using System.Runtime.InteropServices;
5 |
6 | #endregion
7 |
8 | namespace Pi.Timers
9 | {
10 | internal static class Interop
11 | {
12 | #region Constants
13 |
14 | public static int CLOCK_MONOTONIC_RAW = 4;
15 |
16 | #endregion
17 |
18 | #region Classes
19 |
20 | public struct timespec
21 | {
22 | public IntPtr tv_sec; /* seconds */
23 | public IntPtr tv_nsec; /* nanoseconds */
24 | }
25 |
26 | #endregion
27 |
28 | #region Methods
29 |
30 | [DllImport("libc.so.6")]
31 | public static extern int nanosleep(ref timespec req, ref timespec rem);
32 |
33 | #endregion
34 | }
35 | }
--------------------------------------------------------------------------------
/Pi.System/Timers/StandardTimer.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 |
5 | #endregion
6 |
7 | namespace Pi.Timers
8 | {
9 | ///
10 | /// Represents a timer.
11 | ///
12 | public class StandardTimer : ITimer
13 | {
14 | #region Fields
15 |
16 | private TimeSpan interval;
17 | private Action action;
18 |
19 | private bool isStarted;
20 | private System.Threading.Timer timer;
21 |
22 | #endregion
23 |
24 | #region Properties
25 |
26 | ///
27 | /// Gets or sets the interval, in milliseconds.
28 | ///
29 | ///
30 | /// The interval, in milliseconds.
31 | ///
32 | public TimeSpan Interval
33 | {
34 | get { return interval; }
35 | set
36 | {
37 | interval = value;
38 | if (isStarted)
39 | Start(TimeSpan.Zero);
40 | }
41 | }
42 |
43 | ///
44 | /// Gets or sets the action.
45 | ///
46 | ///
47 | /// The action.
48 | ///
49 | public Action Action
50 | {
51 | get { return action; }
52 | set
53 | {
54 | if (value == null)
55 | Stop();
56 |
57 | action = value;
58 | }
59 | }
60 |
61 | #endregion
62 |
63 | #region Methods
64 |
65 | ///
66 | /// Starts this instance.
67 | ///
68 | /// The delay before the first occurence, in milliseconds.
69 | public void Start(TimeSpan startDelay)
70 | {
71 | lock (this)
72 | {
73 | if (!isStarted && interval.TotalMilliseconds >= 1)
74 | {
75 | isStarted = true;
76 | timer = new System.Threading.Timer(OnElapsed, null, startDelay, interval);
77 | }
78 | else
79 | Stop();
80 | }
81 | }
82 |
83 | ///
84 | /// Stops this instance.
85 | ///
86 | public void Stop()
87 | {
88 | lock (this)
89 | {
90 | if (isStarted)
91 | {
92 | isStarted = false;
93 | timer.Dispose();
94 | timer = null;
95 | }
96 | }
97 | }
98 |
99 | #endregion
100 |
101 | #region Private Helpers
102 |
103 | private void NoOp(){}
104 |
105 | private void OnElapsed(object state)
106 | {
107 | (Action ?? NoOp)();
108 | }
109 |
110 | #endregion
111 | }
112 | }
--------------------------------------------------------------------------------
/Pi.System/Timers/TimeSpanUtility.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Pi.Timers
4 | {
5 | ///
6 | /// Provides utilities for .
7 | ///
8 | public static class TimeSpanUtility
9 | {
10 | ///
11 | /// Creates a timespan from a number of microseconds.
12 | ///
13 | /// The microseconds.
14 | ///
15 | public static TimeSpan FromMicroseconds(double microseconds)
16 | {
17 | return TimeSpan.FromTicks((long)(microseconds/10));
18 | }
19 | }
20 | }
--------------------------------------------------------------------------------
/Pi.System/Timers/Timer.cs:
--------------------------------------------------------------------------------
1 | #region References
2 |
3 | using System;
4 | using System.Threading;
5 |
6 | #endregion
7 |
8 | namespace Pi.Timers
9 | {
10 | ///
11 | /// Provides access to timing features.
12 | ///
13 | public static class Timer
14 | {
15 | #region Methods
16 |
17 | ///
18 | /// Creates a timer.
19 | ///
20 | /// The timer.
21 | ///
22 | /// The created timer is the most suitable for the current platform.
23 | ///
24 | public static ITimer Create()
25 | {
26 | return Board.Current.IsRaspberryPi
27 | ? (ITimer) new HighResolutionTimer()
28 | : new StandardTimer();
29 | }
30 |
31 | ///
32 | /// Sleeps during the specified time.
33 | ///
34 | /// The time.
35 | public static void Sleep(TimeSpan time)
36 | {
37 | if (time.TotalMilliseconds < 0)
38 | return;
39 |
40 | if (Board.Current.IsRaspberryPi)
41 | HighResolutionTimer.Sleep(time);
42 | else
43 | Thread.Sleep(time);
44 | }
45 |
46 | #endregion
47 | }
48 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Pi
2 | Libraries for use with the Raspberry Pi
3 |
4 | ## Instructions
5 |
6 | These instructions are for .NET Core 2.0. In order to use it with Visual Studio, you need at least Visual Studio 2017 15.3.
7 |
8 | - Clone the repo
9 | - `dotnet publish -r linux-arm` from the root of the repo.
10 | - Copy the contents of the publish folder underneath `bin\Debug\netcoreapp2.0\linux-arm\publish\` to the Raspberry Pi.
11 | - Install the pre-reqs.
12 | - Example on Raspbian `sudo apt-get install libc6 libcurl3 libgcc1 libgssapi-krb5-2 libicu-dev liblttng-ust0 libssl-dev libstdc++6 libunwind8 libuuid1 zlib1g`
13 | - `chmod +x IotSample` on the IotSample file in the root of the app.
14 | - `sudo ./IotSample`
15 |
16 | Note: Make sure you have enabled GPIO and SPI. You can do this by running `raspi-config` on the Pi.
17 |
18 | This project was created based on the [raspberry-sharp](https://github.com/raspberry-sharp) project. This was initially forked off to make it easier to consume it in more places than Mono as well as add Raspberry Pi 3 support.
19 |
--------------------------------------------------------------------------------