Esempio n. 1
0
        /// <summary>
        /// Reads bytes from device with passed address.
        /// </summary>
        /// <param name="address">The address.</param>
        /// <param name="count">The count.</param>
        /// <returns>
        /// The read bytes.
        /// </returns>
        /// <exception cref="IOException">Thrown if the address could not be accessed or read.</exception>
        public byte[] ReadBytes(int address, int count)
        {
            byte[] buf = new byte[count];

            // int res= I2CNativeLib.ReadBytes(busHandle, address, buf, buf.Length);
            int ret = I2CNativeLib.Ioctl(this.busHandle, I2CNativeLib.I2CSlave, address);

            if (ret < 0)
            {
                throw new IOException(string.Format("Error accessing address '{0}'", address /*, UnixMarshal.GetErrorDescription(Stdlib.GetLastError())*/));
            }

            int n = I2CNativeLib.Read(this.busHandle, buf, buf.Length);

            if (n <= 0)
            {
                throw new IOException(string.Format("Error reading from address '{0}': I2C transaction failed", address));
            }

            if (n < count)
            {
                Array.Resize(ref buf, n);
            }

            return(buf);
        }
Esempio n. 2
0
        /// <summary>
        /// Writes array of bytes.
        /// </summary>
        /// <param name="address">Address of a destination device</param>
        /// <param name="bytes">The bytes.</param>
        /// <exception cref="IOException">Thrown when address cannot be accessed or data cannot be written.</exception>
        /// <remarks>
        /// Do not write more than 3 bytes at once, RPi drivers don't support this currently.
        /// </remarks>
        public void WriteBytes(int address, byte[] bytes)
        {
            int ret = I2CNativeLib.Ioctl(this.busHandle, I2CNativeLib.I2CSlave, address);

            if (ret < 0)
            {
                throw new IOException(string.Format("Error accessing address '{0}'", address /*, UnixMarshal.GetErrorDescription(Stdlib.GetLastError())*/));
            }

            ret = I2CNativeLib.Write(this.busHandle, bytes, bytes.Length);

            if (ret < 0)
            {
                throw new IOException(string.Format("Error writing to address '{0}': I2C transaction failed", address));
            }
        }