예제 #1
0
        static void Main(string[] args)
        {
            try
            {
                var connection = new SerialConnection("COM5", SerialBaudRate.Bps_57600);
                var session    = new ArduinoSession(connection, timeOut: 250);

                Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs e)
                {
                    e.Cancel = true;
                    running  = false;
                };

                IFirmataProtocol firmata = (IFirmataProtocol)session;

                int led1 = 12;
                int led2 = 11;
                int led3 = 10;

                firmata.SetDigitalPinMode(led1, PinMode.DigitalOutput);
                firmata.SetDigitalPinMode(led2, PinMode.DigitalOutput);
                firmata.SetDigitalPinMode(led3, PinMode.DigitalOutput);

                while (running)
                {
                    // led 1
                    Console.WriteLine("Turn on LED 1");
                    firmata.SetDigitalPin(led1, true);
                    firmata.SetDigitalPin(led2, false);
                    firmata.SetDigitalPin(led3, false);
                    Thread.Sleep(1000); // sleep

                    // led 2
                    Console.WriteLine("Turn on LED 2");
                    firmata.SetDigitalPin(led1, false);
                    firmata.SetDigitalPin(led2, true);
                    firmata.SetDigitalPin(led3, false);
                    Thread.Sleep(1000);

                    // led 3
                    Console.WriteLine("Turn on LED 3");
                    firmata.SetDigitalPin(led1, false);
                    firmata.SetDigitalPin(led2, false);
                    firmata.SetDigitalPin(led3, true);
                    Thread.Sleep(1000);
                }
                // turn off LEDs
                firmata.SetDigitalPin(led1, false);
                firmata.SetDigitalPin(led2, false);
                firmata.SetDigitalPin(led3, false);

                connection.Close();
            }
            catch (Exception err)
            {
                Console.WriteLine(err);
            }
            Console.WriteLine("Program exit. Press ENTER to close.");
            Console.ReadLine();
        }
예제 #2
0
        public static void SerialRead(this ArduinoSession session, HW_SERIAL hw, bool continuously = true, int?maxBytesToRead = null)
        {
            var command = new byte[14];

            command[0] = Utility.SysExStart;
            command[1] = SERIAL_MESSAGE;
            command[2] = (byte)(SERIAL_READ | (int)hw);          //SERIAL_READ  //OR with port (0x31 = SERIAL_READ | HW_SERIAL1)
            command[3] = continuously ? (byte)0x00 : (byte)0x01; //SERIAL_READ_MODE   0x00 => read continuously, 0x01 => stop reading
            if (maxBytesToRead.HasValue)
            {
                if (maxBytesToRead.Value >= 32767)
                {
                    throw new ArgumentOutOfRangeException(nameof(maxBytesToRead), "不能大于32767");
                }

                var bytes = maxBytesToRead.Value.encode32BitSignedInteger();
                command[4] = bytes[0];
                command[5] = bytes[1];
                command[6] = Utility.SysExEnd;
            }
            else
            {
                command[4] = Utility.SysExEnd;
            }

            session.Write(command, 0, maxBytesToRead.HasValue ? 6 : 4);
        }
예제 #3
0
        public void CreateSessionWithClosedConnection()
        {
            var connection = new MockSerialConnection();
            var session    = new ArduinoSession(connection);

            Assert.AreEqual(true, connection.IsOpen);
        }
        public void TestMethod1()
        {
            var x = new ArduinoSession(new MockSerialConnection());

            var tracker = x.CreateAnalogStateMonitor();
            
        }
예제 #5
0
        public static void Request_EEPROM_Get(this ArduinoSession session, int index, int length)
        {
            if (length <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(length), "length 必须大于0");
            }

            var indexBytes  = index.encode32BitSignedInteger();
            var lengthBytes = length.encode32BitSignedInteger();
            var command     = new[]
            {
                Utility.SysExStart,
                EEPROM_DATA,
                EEPROM_GET,
                indexBytes[0],  //4  num steps, bits 0-6
                indexBytes[1],  //5  num steps, bits 7-13
                indexBytes[2],  //6  num steps, bits 14-20
                indexBytes[3],  //7  num steps, bits 21-27
                indexBytes[4],  //8  num steps, bits 28-32
                lengthBytes[0], //4  num steps, bits 0-6
                lengthBytes[1], //5  num steps, bits 7-13
                lengthBytes[2], //6  num steps, bits 14-20
                lengthBytes[3], //7  num steps, bits 21-27
                lengthBytes[4], //8  num steps, bits 28-32
                Utility.SysExEnd
            };

            session.Write(command, 0, command.Length);
        }
예제 #6
0
        private void btnExecute_Click(object sender, EventArgs e)
        {
            try
            {
                var connection = new SerialConnection("COM5", SerialBaudRate.Bps_57600);
                var session    = new ArduinoSession(connection, timeOut: 250);

                IFirmataProtocol firmata = (IFirmataProtocol)session;

                int redPin   = 9;
                int greenPin = 10;
                int bluePin  = 11;

                firmata.SetDigitalPinMode(redPin, PinMode.PwmOutput);
                firmata.SetDigitalPinMode(greenPin, PinMode.PwmOutput);
                firmata.SetDigitalPinMode(bluePin, PinMode.PwmOutput);

                firmata.SetDigitalPin(redPin, redVal);
                firmata.SetDigitalPin(greenPin, greenVal);
                firmata.SetDigitalPin(bluePin, blueVal);

                connection.Close();
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }
예제 #7
0
        public static void Request_EEPROM_Put(this ArduinoSession session, int index, byte[] bytes)
        {
            if (bytes == null || bytes.Length <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(bytes), "bytes 不能为空且长度必须大于0");
            }

            var indexBytes    = index.encode32BitSignedInteger();
            var encoder7Bytes = ByteArrayExtensions.Encoder7Bit(bytes);
            var command       = new List <byte>
            {
                Utility.SysExStart,
                EEPROM_DATA,
                EEPROM_PUT,
                indexBytes[0], //4  num steps, bits 0-6
                indexBytes[1], //5  num steps, bits 7-13
                indexBytes[2], //6  num steps, bits 14-20
                indexBytes[3], //7  num steps, bits 21-27
                indexBytes[4], //8  num steps, bits 28-32
                //(byte)white,
                //Utility.SysExEnd
            };

            command.AddRange(encoder7Bytes);

            command.Add(Utility.SysExEnd);

            session.Write(command.ToArray(), 0, command.Count);
        }
예제 #8
0
        public void TimeOut_SetNegative()
        {
            var connection = new MockSerialConnection();
            var session    = new ArduinoSession(connection);

            session.TimeOut = -2;
        }
예제 #9
0
 /// <summary>
 /// Writes a string to the serial output data stream.
 /// </summary>
 /// <param name="value">A string to be written</param>
 public static void Write(this ArduinoSession session, string value = null)
 {
     if (!string.IsNullOrEmpty(value))
     {
         session.Connection.Write(value);
     }
 }
예제 #10
0
        public MainViewModel()
        {
            var connection = new SerialConnection("COM3", SerialBaudRate.Bps_115200);
            var session    = new ArduinoSession(connection);

            session.CreateReceivedStringMonitor().Subscribe(this);
        }
예제 #11
0
        /// <summary>
        /// 根据从其零位置开始的步数将组中的每个步进器设置到所需位置。位置被指定为32位带符号的长整数。
        /// 步进运动将被协调,以便所有人都同时到达其所需位置。根据位置变化和步进器的最大速度,此移动的持续时间取决于哪个步进器将花费最长的时间。
        /// </summary>
        /// <param name="session"></param>
        /// <param name="deviceNumber"></param>
        /// <param name="stepsNum"></param>
        public static void MultiStepperMoveTo(this ArduinoSession session, int groupNumber, int stepsNum)
        {
            if (groupNumber < 0 || groupNumber > 4)
            {
                throw new ArgumentOutOfRangeException(nameof(groupNumber), "Group number must be between 0 and 4.");
            }

            var bytes = stepsNum.encode32BitSignedInteger();

            var command = new[]
            {
                Utility.SysExStart,
                ACCELSTEPPER_DATA, //ACCELSTEPPER_DATA(0x62)
                MULTISTEPPER_TO,   //multi to command(0x21)         //MULTISTEPPER_TO
                (byte)groupNumber, //group number(0-4)
                bytes[0],          //4  num steps, bits 0-6
                bytes[1],          //5  num steps, bits 7-13
                bytes[2],          //6  num steps, bits 14-20
                bytes[3],          //7  num steps, bits 21-27
                bytes[4],          //8  num steps, bits 28-32
                Utility.SysExEnd
            };

            session.Write(command, 0, command.Length);
        }
예제 #12
0
        private IStringProtocol CreateSerialSession(ISerialConnection connection, int timeout = -1)
        {
            var session = new ArduinoSession(connection);

            session.TimeOut          = timeout;
            session.MessageReceived += (o, e) =>
            {
                Assert.Fail("MessageReceived event triggered");
            };
            session.AnalogStateReceived += (o, e) =>
            {
                Assert.Fail("AnalogStateReceived event triggered");
            };
            session.DigitalStateReceived += (o, e) =>
            {
                Assert.Fail("DigitalStateReceived event triggered");
            };
            session.I2CReplyReceived += (o, e) =>
            {
                Assert.Fail("I2CReplyReceived event triggered");
            };
            session.StringReceived += (o, e) =>
            {
                Console.WriteLine("Received: '{0}'", e.Text);
            };
            return(session);
        }
예제 #13
0
        /// <summary>
        /// 启动步进电机(绝对移动)
        /// 根据从零位置开始的步数将步进器移动到所需位置。位置指定为32位带符号的长整数。
        /// </summary>
        /// <param name="session"></param>
        public static void StepperMoveTo(this ArduinoSession session, int deviceNumber, int stepsNum)
        {
            if (deviceNumber < 0 || deviceNumber > 9)
            {
                throw new ArgumentOutOfRangeException(nameof(deviceNumber), "Device number must be between 0 and 9.");
            }

            var bytes = stepsNum.encode32BitSignedInteger();

            var command = new[]
            {
                Utility.SysExStart,
                ACCELSTEPPER_DATA,  //ACCELSTEPPER_DATA(0x62)
                ACCELSTEPPER_TO,    //to command(0x03)       //ACCELSTEPPER_TO
                (byte)deviceNumber, //device number(0-9) (Supports up to 10 motors)
                bytes[0],           //4  num steps, bits 0-6
                bytes[1],           //5  num steps, bits 7-13
                bytes[2],           //6  num steps, bits 14-20
                bytes[3],           //7  num steps, bits 21-27
                bytes[4],           //8  num steps, bits 28-32
                Utility.SysExEnd
            };

            session.Write(command, 0, command.Length);
        }
예제 #14
0
        /// <summary>
        /// 可以将使用上述stepper configuration命令创建的Stepper实例添加到multiStepper组。可以通过单个命令向组发送设备/位置列表,并且将协调它们的移动以同时开始和结束。请注意,multiStepper不支持加速或减速。
        /// </summary>
        /// <param name="session"></param>
        /// <param name="groupNumber"></param>
        /// <param name="deviceNumbers"></param>
        public static void MultiStepperConfiguration(this ArduinoSession session, int groupNumber, params int[] deviceNumbers)
        {
            if (groupNumber < 0 || groupNumber > 4)
            {
                throw new ArgumentOutOfRangeException(nameof(groupNumber), "Group number must be between 0 and 4.");
            }
            if (deviceNumbers == null)
            {
                throw new ArgumentNullException(nameof(deviceNumbers));
            }
            if (deviceNumbers.Length <= 2)
            {
                throw new ArgumentOutOfRangeException(nameof(deviceNumbers), "驱动器数量必须大于等于2位");
            }
            foreach (var deviceNumber in deviceNumbers)
            {
                if (deviceNumber < 0 || deviceNumber > 9)
                {
                    throw new ArgumentOutOfRangeException(nameof(deviceNumber), "Device number must be between 0 and 9.");
                }
            }

            var command = new List <byte>
            {
                Utility.SysExStart,
                ACCELSTEPPER_DATA,   //ACCELSTEPPER_DATA(0x62)
                MULTISTEPPER_CONFIG, //config command(0x00 = config)      //ACCELSTEPPER_CONFIG
                (byte)groupNumber,   //device number(0-9) (Supports up to 10 motors)
                //Utility.SysExEnd
            };

            command.AddRange(deviceNumbers.Select(f => (byte)f));
            command.Add(Utility.SysExEnd);
            session.Write(command.ToArray(), 0, command.Count);
        }
예제 #15
0
 /// <summary>
 /// Asynchronously gets a summary of the party system's capabilities.
 /// </summary>
 /// <returns>The system's capabilities</returns>
 public static async Task <BoardCapability> GetBoardCapabilityAsync(this ArduinoSession session)
 {
     session.RequestBoardCapability();
     //return await Task.Run(() =>
     //    (BoardCapability)((FirmataMessage)session.GetMessageFromQueue(new FirmataMessage(MessageType.CapabilityResponse))).Value);
     return(await Task.Run(() => session.GetMessageFromQueue <BoardCapability>().Value).ConfigureAwait(false));
 }
예제 #16
0
 /// <summary>
 /// Asynchronously gets the channel-to-pin mappings of the party system's analog lines.
 /// </summary>
 /// <returns>The channel-to-pin mappings</returns>
 public static async Task <BoardAnalogMapping> GetBoardAnalogMappingAsync(this ArduinoSession session)
 {
     session.RequestBoardAnalogMapping();
     //return await Task.Run(() =>
     //    (BoardAnalogMapping)((FirmataMessage)session.GetMessageFromQueue(new FirmataMessage(MessageType.AnalogMappingResponse))).Value);
     return(await Task.Run(() => session.GetMessageFromQueue <BoardAnalogMapping>().Value).ConfigureAwait(false));
 }
예제 #17
0
 /// <summary>
 /// Asynchronously gets the firmware signature of the party system.
 /// </summary>
 /// <returns>The firmware signature</returns>
 public static async Task <Firmware> GetFirmwareAsync(this ArduinoSession session)
 {
     session.RequestFirmware();
     //return await Task.Run(() =>
     //    (Firmware)((FirmataMessage)session.GetMessageFromQueue(new FirmataMessage(MessageType.FirmwareResponse))).Value);
     return(await Task.Run(() => session.GetMessageFromQueue <Firmware>().Value).ConfigureAwait(false));
 }
예제 #18
0
 /// <summary>
 /// Asynchronously gets the protocol version implemented on the party system.
 /// </summary>
 /// <returns>The implemented protocol version</returns>
 public static async Task <ProtocolVersion> GetProtocolVersionAsync(this ArduinoSession session)
 {
     session.RequestProtocolVersion();
     //return await Task.Run(() =>
     //    (ProtocolVersion)((FirmataMessage)session.GetMessageFromQueue(new FirmataMessage(MessageType.ProtocolVersion))).Value);
     return(await Task.Run(() => session.GetMessageFromQueue <ProtocolVersion>().Value).ConfigureAwait(false));
 }
예제 #19
0
        public void Dispose()
        {
            var connection = new MockSerialConnection();
            var session    = new ArduinoSession(connection);

            session.Dispose();
        }
예제 #20
0
        private static void I2CRead(this ArduinoSession session, bool continuous, int slaveAddress, int slaveRegister = -1, int bytesToRead = 0)
        {
            if (slaveAddress < 0 || slaveAddress > 0x3FF)
            {
                throw new ArgumentOutOfRangeException(nameof(slaveAddress), Messages.ArgumentEx_I2cAddressRange);
            }

            if (bytesToRead < 0 || bytesToRead > 0x3FFF)
            {
                throw new ArgumentOutOfRangeException(nameof(bytesToRead), Messages.ArgumentEx_ValueRange0_16383);
            }

            byte[] command = new byte[(slaveRegister == -1 ? 7 : 9)];
            command[0] = Utility.SysExStart;
            command[1] = 0x76;
            command[2] = (byte)(slaveAddress & 0x7F);
            command[3] = (byte)(((slaveAddress >> 7) & 0x07) | (slaveAddress < 128 ? (continuous ? 0x10 : 0x08) : (continuous ? 0x30 : 0x28)));

            if (slaveRegister != -1)
            {
                command[4] = (byte)(slaveRegister & 0x7F);
                command[5] = (byte)(slaveRegister >> 7);
                command[6] = (byte)(bytesToRead & 0x7F);
                command[7] = (byte)(bytesToRead >> 7);
            }
            else
            {
                command[4] = (byte)(bytesToRead & 0x7F);
                command[5] = (byte)(bytesToRead >> 7);
            }

            command[command.Length - 1] = Utility.SysExEnd;

            session.Write(command, 0, command.Length);
        }
예제 #21
0
        public void FirmataSetup(String porta)
        {
            try
            {
                if (arduino != null)
                {
                    arduino.Clear();
                    arduino.Dispose();
                }

                connection = new EnhancedSerialConnection(porta, SerialBaudRate.Bps_9600);
                arduino    = new ArduinoSession(connection);

                _COMStatusLabel.Text = porta;
                _MessageLabel.Text   = "Connected.";

                Ready = true;
            }
            catch (Exception e)
            {
                _COMStatusLabel.Text = porta;
                _MessageLabel.Text   = e.Message;

                Ready = false;
            }
        }
예제 #22
0
        public const byte ENCODER_DATA = 0x61; // ENCODER_DATA(0x61)
        public static void 附加编码器(this ArduinoSession session, int encoderNumber, int encoderPinA, int encoderPinB)
        {
            if (encoderNumber < 0 || encoderNumber > 5)
            {
                throw new ArgumentOutOfRangeException(nameof(encoderNumber), "Encoder number must be between 0 and 5.");
            }
            if (encoderPinA < 0 || encoderPinA > 127)
            {
                throw new ArgumentOutOfRangeException(nameof(encoderPinA), "Pin number must be between 0 and 127.");
            }
            if (encoderPinB < 0 || encoderPinB > 127)
            {
                throw new ArgumentOutOfRangeException(nameof(encoderPinB), "Pin number must be between 0 and 127.");
            }

            var command = new[]
            {
                Utility.SysExStart,
                ENCODER_DATA,        //ENCODER_DATA(0x61)
                (byte)0x00,          //ENCODER_ATTACH(0x00)
                (byte)encoderNumber, //encoder #                  ([0 - MAX_ENCODERS-1])
                (byte)encoderPinA,   //4 pin A #(first pin)
                (byte)encoderPinB,   //5 pin B #(second pin)
                Utility.SysExEnd
            };

            session.Write(command, 0, command.Length);
        }
예제 #23
0
 public void ClearSession()
 {
     var connection = new MockSerialConnection();
     var session = new ArduinoSession(connection);
     session.Clear();
     session.Dispose();
 }
예제 #24
0
 /// <summary>
 /// Gets byte data from the party system, read from the given memory address and register.
 /// </summary>
 /// <param name="slaveAddress">The slave's memory address and register</param>
 /// <param name="slaveRegister">The slave's register</param>
 /// <param name="bytesToRead">Number of bytes to read</param>
 /// <returns>An <see cref="I2CReply"/> object holding the data read</returns>
 public static I2CReply GetI2CReply(this ArduinoSession session, int slaveAddress, int slaveRegister, int bytesToRead)
 {
     session.ReadI2COnce(slaveAddress, slaveRegister, bytesToRead);
     //_awaitedMessagesQueue.Enqueue(new FirmataMessage(MessageType.I2CReply));
     //return (I2CReply)((FirmataMessage)GetMessageFromQueue(new FirmataMessage(MessageType.I2CReply))).Value;
     return(session.GetMessageFromQueue <I2CReply>().Value);
 }
예제 #25
0
 public void TimeOutReached()
 {
     var connection = new MockSerialConnection();
     var session = new ArduinoSession(connection);
     session.TimeOut = 1;
     // TODO: verder uitwerken.
 }
예제 #26
0
 public void CreateSessionWithOpenConnection()
 {
     var connection = new MockSerialConnection();
     connection.Open();
     var session = new ArduinoSession(connection);
     Assert.AreEqual(true, connection.IsOpen);
 }
예제 #27
0
파일: Program.cs 프로젝트: skyhoshi/Arduino
        private static void DisplayPortCapabilities()
        {
            using (var session = new ArduinoSession(new EnhancedSerialConnection("COM4", SerialBaudRate.Bps_57600)))
            {
                session.StringReceived += (object sender, StringEventArgs eventArgs) =>
                {
                    Console.WriteLine(eventArgs.Text);
                };

                BoardCapability cap = session.GetBoardCapability();
                Console.WriteLine();
                Console.WriteLine("Board Capability:");

                foreach (var pin in cap.Pins)
                {
                    Console.WriteLine("Pin {0}: Input: {1}, Output: {2}, Analog: {3}, Analog-Res: {4}, PWM: {5}, PWM-Res: {6}, Servo: {7}, Servo-Res: {8}, Serial: {9}, Encoder: {10}, Input-pullup: {11}",
                                      pin.PinNumber,
                                      pin.DigitalInput,
                                      pin.DigitalOutput,
                                      pin.Analog,
                                      pin.AnalogResolution,
                                      pin.Pwm,
                                      pin.PwmResolution,
                                      pin.Servo,
                                      pin.ServoResolution,
                                      pin.Serial,
                                      pin.Encoder,
                                      pin.InputPullup);
                }
            }
        }
예제 #28
0
        static public ArduinoDeviceManager Connect(String nodeID, String port, SerialBaudRate bps, int timeOut, Action <ADMMessage, ArduinoDeviceManager> listener)
        {
            if (String.IsNullOrEmpty(nodeID))
            {
                throw new Exception("ArduinoDeviceManager::Connect ... nodeID cannot be empty or null");
            }
            ISerialConnection connection = new XBeeFirmataSerialConnection(nodeID, port, bps);

            if (connection != null)
            {
                var session = new ArduinoSession(connection, timeOut);
                try
                {
                    var mgr = new ArduinoDeviceManager(session, listener, port, nodeID);
                    mgr.Connection = connection;
                    return(mgr);
                }
                catch (Exception e)
                {
                    if (connection.IsOpen)
                    {
                        connection.Close();
                    }
                    throw e;
                }
            }

            return(null);
        }
예제 #29
0
        public void TimeOutReached()
        {
            var connection = new MockSerialConnection();
            var session    = new ArduinoSession(connection);

            session.TimeOut = 1;
            // TODO: verder uitwerken.
        }
예제 #30
0
 public void TimeOut_GetAndSet()
 {
     var connection = new MockSerialConnection();
     var session = new ArduinoSession(connection);
     Assert.AreEqual(-1, session.TimeOut);
     session.TimeOut = 7;
     Assert.AreEqual(7, session.TimeOut);
 }
예제 #31
0
 /// <summary>
 /// Asynchronously gets byte data from the party system, read from the given memory address and register.
 /// </summary>
 /// <param name="slaveAddress">The slave's memory address</param>
 /// <param name="slaveRegister">The slave's register</param>
 /// <param name="bytesToRead">Number of bytes to read</param>
 /// <returns>An awaitable <see cref="Task{I2cReply}"/> holding the data read</returns>
 public static async Task <I2CReply> GetI2CReplyAsync(this ArduinoSession session, int slaveAddress, int slaveRegister, int bytesToRead)
 {
     session.ReadI2COnce(slaveAddress, slaveRegister, bytesToRead);
     //_awaitedMessagesQueue.Enqueue(new FirmataMessage(MessageType.I2CReply));
     //return await Task.Run(() =>
     //    (I2CReply)((FirmataMessage)GetMessageFromQueue(new FirmataMessage(MessageType.I2CReply))).Value);
     return(await Task.Run(() => session.GetMessageFromQueue <I2CReply>().Value).ConfigureAwait(false));
 }
예제 #32
0
 public DigitalOutputPin(int pinNumber, ArduinoSession session) : base(pinNumber, session)
 {
     if (IsCorrectPinType())
     {
         return;
     }
     _s.SetDigitalPinMode(_pinNumber, PinMode.DigitalOutput);
 }
예제 #33
0
        /// <summary>
        /// Reads a specified number of characters asynchronous.
        /// </summary>
        /// <param name="length">The number of characters to be read (default is 1)</param>
        /// <returns>An awaitable <see cref="Task{String}"/> returning the string read</returns>
        public static async Task <string> ReadAsync(this ArduinoSession session, int length = 1)
        {
            if (length < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(length), Messages.ArgumentEx_PositiveValue);
            }

            return(await Task.Run(() => session.messageHeader.GetStringFromQueue(StringRequest.CreateReadRequest(length))));
        }
예제 #34
0
        private static void I2CSlaveRead(this ArduinoSession session, bool continuous, int slaveAddress, int slaveRegister = -1, int bytesToRead = 0)
        {
            if (slaveRegister < 0 || slaveRegister > 0x3FFF)
            {
                throw new ArgumentOutOfRangeException(nameof(slaveRegister), Messages.ArgumentEx_ValueRange0_16383);
            }

            I2CRead(session, continuous, slaveAddress, slaveRegister, bytesToRead);
        }
예제 #35
0
        private void TimeTest()
        {
            var session = new ArduinoSession(new SerialConnection("COM3", SerialBaudRate.Bps_57600)) {TimeOut = 1000};
            session.MessageReceived += session_OnMessageReceived;

            var firmata = (II2CProtocol)session;

            var x = firmata.GetI2CReply(0x68, 7);

            Console.WriteLine();
            Console.WriteLine("{0} bytes received.", x.Data.Length);

            
            Console.WriteLine("Starting");



            session.Dispose();
        }
예제 #36
0
 private II2CProtocol CreateFirmataSession(ISerialConnection connection, int timeout = -1)
 {
     var session = new ArduinoSession(connection);
     session.TimeOut = timeout;
     session.MessageReceived += (o, e) =>
     {
         _messagesReceived.Enqueue(e.Value);
     };
     return session;
 }
예제 #37
0
        public void GetFirmware()
        {
            const int majorVersion = 3;
            const int minorVersion = 7;
            const string Name = "Arduino Firmata";

            var connection = new MockSerialConnection();
            var session = new ArduinoSession(connection);

            connection.EnqueueRequestAndResponse(new byte[] { 0xF0, 0x79, 0xF7 }, new byte[] { 0xF0, 0x79, majorVersion, minorVersion });
            connection.EnqueueResponse(Name.To14BitIso());
            connection.EnqueueResponse(0xF7);

            Firmware firmware = session.GetFirmware();
            Assert.AreEqual(firmware.MajorVersion, majorVersion);
            Assert.AreEqual(firmware.MinorVersion, minorVersion);
            Assert.AreEqual(firmware.Name, Name);
        }
예제 #38
0
        static void SimpelTest()
        {
            var connection = new EnhancedSerialConnection("COM6", SerialBaudRate.Bps_57600);
            var session = new ArduinoSession(connection, timeOut: 250);
            IFirmataProtocol firmata = session;

            firmata.AnalogStateReceived += session_OnAnalogStateReceived;
            firmata.DigitalStateReceived += session_OnDigitalStateReceived;

            Firmware firm = firmata.GetFirmware();
            Console.WriteLine();
            Console.WriteLine("Firmware: {0} {1}.{2}", firm.Name, firm.MajorVersion, firm.MinorVersion);
            Console.WriteLine();

            ProtocolVersion version = firmata.GetProtocolVersion();
            Console.WriteLine();
            Console.WriteLine("Protocol version: {0}.{1}", version.Major, version.Minor);
            Console.WriteLine();

            BoardCapability caps = firmata.GetBoardCapability();
            Console.WriteLine();
            Console.WriteLine("Board Capabilities:");

            foreach (var pincap in caps.PinCapabilities)
            {
                Console.WriteLine("Pin {0}: Input: {1}, Output: {2}, Analog: {3}, Analog-Res: {4}, PWM: {5}, PWM-Res: {6}, Servo: {7}, Servo-Res: {8}",
                    pincap.PinNumber, pincap.DigitalInput, pincap.DigitalOutput, pincap.Analog, pincap.AnalogResolution, pincap.Pwm, pincap.PwmResolution,
                    pincap.Servo, pincap.ServoResolution);
            }
            Console.WriteLine();

            var analogMapping = firmata.GetBoardAnalogMapping();
            Console.WriteLine("Analog channel mappings:");

            foreach (var mapping in analogMapping.PinMappings)
            {
                Console.WriteLine("Channel {0} is mapped to pin {1}.", mapping.Channel, mapping.PinNumber);
            }

            firmata.ResetBoard();

            Console.WriteLine();
            Console.WriteLine("Digital port states:");

            for (int x = 0; x < 20; x++)
            {
                var pinState = firmata.GetPinState(x);

                Console.WriteLine("Pin {0}: Mode = {1}, Value = {2}", x, pinState.Mode, pinState.Value);
            }
            Console.WriteLine();

            firmata.SetDigitalPort(0, 0x04);
            firmata.SetDigitalPort(1, 0xff);
            firmata.SetDigitalPinMode(10, PinMode.DigitalOutput);
            firmata.SetDigitalPinMode(11, PinMode.ServoControl);
            firmata.SetDigitalPin(11, 90);
            Thread.Sleep(500);
            int hi = 0;

            for (int a = 0; a <= 179; a += 1)
            {
                firmata.SetDigitalPin(11, a);
                Thread.Sleep(100);
                firmata.SetDigitalPort(1, hi);
                hi ^= 4;
                Console.Write("{0};", a);
            }
            Console.WriteLine();
            Console.WriteLine();

            firmata.SetDigitalPinMode(6, PinMode.DigitalInput);

            //firmata.SetDigitalPortState(2, 255);
            //firmata.SetDigitalPortState(3, 255);

            firmata.SetSamplingInterval(500);
            firmata.SetAnalogReportMode(0, false);

            firmata.SetDigitalReportMode(0, true);
            firmata.SetDigitalReportMode(1, true);
            firmata.SetDigitalReportMode(2, true);

            for (int x = 0; x < 20; x++)
            {
                PinState state = firmata.GetPinState(x);
                Console.WriteLine("Digital {1} pin {0}: {2}", x, state.Mode, state.Value);
            }
            Console.WriteLine();



            Console.ReadLine();
            firmata.SetAnalogReportMode(0, false);
            firmata.SetDigitalReportMode(0, false);
            firmata.SetDigitalReportMode(1, false);
            firmata.SetDigitalReportMode(2, false);
            Console.WriteLine("Ready.");
        }
예제 #39
0
 public void ArduinoSession_Constructor_NullArgument()
 {
     var session = new ArduinoSession(null);
 }
예제 #40
0
 public void TimeOut_SetNegative()
 {
     var connection = new MockSerialConnection();
     var session = new ArduinoSession(connection);
     session.TimeOut = -2;
 }
예제 #41
0
 public void Dispose_OnOpenConnection()
 {
     var connection = new MockSerialConnection();
     connection.Open();
     var session = new ArduinoSession(connection);
     session.Dispose();
 }