本文介绍了C#-NetDuino-串行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好

我需要一些代码帮助,因为我一直在重新排列它并添加内容并使用try,catch,但是无论我尝试什么,我都无法使串行与Netduino上的伺服/PWM一起使用.

此代码将写入Netduino,并且Netduino将对串行作出响应,但是一旦冻结,它就会冻结.

请任何帮助将不胜感激.

谢谢

问候
米切尔

代码:

Hello

I need some help with my code because i keep re-arranging it and adding stuff and using try, catch but no matter what i try i cannot get the serial to work with a servo / PWM on Netduino.

This code writes to the Netduino and the Netduino responds on serial but as soon as the while begins it freezes.

Please any help would be appreciated.

Thanks

Regards
Mitchell

CODE:

using System;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.Netduino;
using System.IO;
using System.Text;
using System.IO.Ports;

namespace mrinc
{
    public class Program
    {
        static SerialPort port = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
        static PWM servo = new PWM(Pins.GPIO_PIN_D5);
        static int[] range = new int[2];
        static byte[] buffer = new byte[32];
        public static void Main()
        {
            initializeSerial();
            initializeServo();
            s = "M.R. Inc*******";
            port.Write(Encoding.UTF8.GetBytes(s), 0, s.Length);
            while (true)
            {
                int count = 0;
                try { count = port.Read(buffer, 0, buffer.Length); }
                catch (Exception) { }
                if (count > 0)
                {
                    char[] c = Encoding.UTF8.GetChars(buffer);
                    if (c[0] == '1')
                    {
                        setServo(0);
                    }
                    if(c[0] == '0')
                    {
                        setServo(90);
                    }
                }
            }
            private static long map(long x, long in_min, long in_max, long out_min, long out_max)
        {
            return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
        }
        private static void setServo(int value)
        {
            try
            {
                servo.SetPulse(20000, (uint)map((long)value, 0, 180, range[0], range[1]));
            }
            catch (Exception)
            { }
        }
        private static void initializeServo()
        {
            range[0] = 1000;
            range[1] = 2000;
            servo.SetDutyCycle(0);
            setServo(90);
        }
        private static void initializeSerial()
        {
            port.ReadTimeout = 0;
            port.Open();
        }

推荐答案


这篇关于C#-NetDuino-串行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 01:41