터미널에 아래 명령어를 한 줄씩 입력합니다.

$ sudo sh -c 'echo "deb http://packages.ros.org/ros/ubuntu $(lsb_release -sc) main" > /etc/apt/sources.list.d/ros-latest.list'
$ sudo apt install curl
$ curl -s https://raw.githubusercontent.com/ros/rosdistro/master/ros.asc | sudo apt-key add -
$ sudo apt update
$ sudo apt install ros-melodic-desktop-full
$ echo "source /opt/ros/melodic/setup.bash" >> ~/.bashrc
$ source ~/.bashrc

 

그 후 $ roscore를 해서 아래 사진과 같다면 melodic설치완료입니다.

 

 

workspace 만들기

$ mkdir -p ~/catkin_ws/src
$ cd ~/catkin_ws/
$ catkin_make

 

만약 catkin_make에서 package가 없다는 오류가 날 경우

$ sudo apt-get install ros-melodic-[설치할 pakage]

홈페이지 링크 : https://2021nipa.elice.io/explore

 

2021 NIPA AI 온라인 교육 | 엘리스: 코딩, 엘리스에서 시작하세요!

실습중심 온라인 코딩교육, 엘리스! 개인 및 기업 디지털 트랜스포메이션(DT) 교육, 대학 데이터 사이언스 교육은 엘리스로 시작하세요.

2021nipa.elice.io

교육과정 혜택

1. 수강생 교육비 전액 지원

2. 기본/응용과정 각각 이수증 발급

3. 인공지능 전문가 자격증 취득 지원

 

교육과정은 아래 사진과 같아요. 이론과 실습을 공부한 후 프로젝트까지!

 

페이스북을 통해 관심있던 ai수업을 교육비 전액 지원한다는 게시물을 보고 빠르게 신청했습니다.

강의로 먼저 개념을 설명해주시고 실습을 통해 바로 적용해볼수있다는 것이 정말좋았습니다. 반복적으로 실습을 하다보니까 이해가 바로바로 되더라구요! 제가 이해가 좀 느린편이기도하고 설명을 듣고 한번에 이해하기가 힘들어서 질문도 많이했는데 그때마다 엄청빨리 답변을 주셔서 좋았어요. 앞에서 설명을 들은것중에 이해가 안돼서 질문을하니까 예시를 들어가면서 되게 친절하게 답변을 해주셨어요. 많이물어봐서 귀찮으셨을텐데 답해주셔서 정말 감사했습니다ㅠㅠ

 

아래 사진처럼 실습에 대한 해설강의도 올려주셔서 이해하는데 문제가 없었어요!

 

 

강의를 다 듣고나면 프로젝트로 실무적용을 해볼수있어요!

 

 

처음에 ai를 공부했을때 Udacity를 봤는데 영어라서 너무 이해하기가 힘들더라구요.. 그런데 같은 내용을 한글강의로 듣기도했고 비전공자도 이해할수있도록 쉽게 설명해 주셔서 정말 좋았어요.

강의 완전 추천합니다!!!!

 

모든과정을 이수하고 인공지능 전문가 시험을 쳤습니다.

글을 쓰는 날이 9월10일이라서 결과는 모르지만 꼭 붙었으면 좋겠네요ㅠㅠㅠ

 

70점 이상 합격인데 81점으로 합격했습니다!!!

 

아래 사이트에 들어가서 로그인을 한 후 

https://trinket.io/

 

Trinket

Trinket Premium Plans Designed with individual learners and educators in mind, premium plans offer more power and convenience. View Premium Plans Free Support for Educators Educators are a key part of our mission. We offer free support to all verified educ

trinket.io

 

계정을 누르고 new trinket 을 누른 후 원하는 언어를 선택하고 실행시킬 코드를 입력합니다.

 

 

그 뒤 share에 embed을 누르고 나온 주소를 복사합니다.

 

 

블로그를 hdml로 바꾸고 소스를 넣고싶은 위치에 

 

이런 형식으로 붙여넣으면 됩니다.

 

 

모션보드와 노트북 통신 연결하기

1. [설정] > [네트워크 및 인터넷] > [이더넷] > [어댑터 옵션 변경] > [이더넷] 마우스 우클릭 > [속성]

   > [인터넷 프로토콜 버전4] > [속성] > 사용할 ip주소 적고 서브넷 적는공간에 한번 클릭 > [확인] 

** ip 주소의 맨 마지막 숫자는 모션보드와 다른아무숫자나 적어주면 됩니다.

 

 

2. [window] 키 + r 해서 cmd 창 열기

3. ping [모션보드의 ip 주소] 적기

 

결과는 다음과 같이 응답이라고 떠야합니다.

 

 

UDP/TCP통신의 차이점

https://velog.io/@hidaehyunlee/TCP-%EC%99%80-UDP-%EC%9D%98-%EC%B0%A8%EC%9D%B4

네트워크의 계층들 중 전송 계층에서 사용하는 프로토콜에 대해서 알아봅시다.

전송계층이란 송신자와 수신자를 연결하는 통신서비스를 제공하는 계층입니다. 데이터의 전달을 담당한다고 보시면 됩니다. 데이터를 전달하기위해서는 프로토콜을 사용해야하는데 그 프로토콜이 UDP와 TCP입니다.

 

TCP : Transmission Control Protocol 전송을 제어하는 프로토콜

        인터넷상에서 데이터를 메세지의 형태로 보내기위해 ip와 함께 사용하는 프로토콜

UDP : User Datagram Protocol 사용자 데이터그램 프로토콜

        데이터를 데이터그램 단위로 처리하는 프로토콜

        

 

 

 

 

 

 

UDP통신을 이용하여 모션보드의 모터를 제어해 보도록 하겠습니다.

먼저 노트북내에서 udp통신이 되는지 확인해 보았습니다.

[client]                                                                                                   [server]

client 코드

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace UDPEchoClient
{
    class App
    {
        private const int ServerPortNumber = 5432;

        static void Main()
        {
            try
            {
                Socket udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                EndPoint localEP = new IPEndPoint(IPAddress.Any, 5433);
                EndPoint remoteEP = new IPEndPoint(IPAddress.Loopback, ServerPortNumber);

                udpSocket.Bind(localEP);
                int i = 0;
                while (i++ < 10)
                {
                    Console.WriteLine("보낼 메세지를 입력하세요 ({0}/10)", i);
                    byte[] sendBuffer = Encoding.UTF8.GetBytes(Console.ReadLine());
                    udpSocket.SendTo(sendBuffer, remoteEP);

                    byte[] receiveBuffer = new byte[512];
                    int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref remoteEP);
                    Console.Write("UDP 에코 메세지 : ");
                    Console.WriteLine(Encoding.UTF8.GetString(receiveBuffer, 0, receivedSize));
                }
                udpSocket.Close();
            }
            catch (SocketException se)
            {
                Console.WriteLine(se.Message);
            }
        }
    }
}

 

server 코드

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace UDPEchoServer
{
        class App
        {
                private const int ServerPortNumber = 5432;

                static void Main()
                {
                        try
                        {
                                // udpSocket 이라는 이름을 가진 소켓을 하나 만드는데 인자는 다음과 같다
                                // 1. IPv4 타입의 주소방식(InterNetwork)
                                // 2. 소켓 타입은 데이터그램(Dgram)
                                // 3. 프로토콜 타입은 UDP 방식을 사용한다
                                Socket udpSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);

                                // 내컴퓨터(locapEP)로 IP종단점을 하나 잡는다
                                // 원격컴퓨터(remoteEP)로 IP종단점을 하나 잡는다
                                EndPoint localEP = new IPEndPoint(IPAddress.Any, ServerPortNumber);
                                EndPoint remoteEP = new IPEndPoint(IPAddress.None, ServerPortNumber);

                                // udpSOCKET 을 localEP 와 연결시킨다
                                // -> udpSOCKET 은 localEP 를 통해 통신대기상태에 들어감
                                udpSocket.Bind(localEP);

                                // 원격컴퓨터에서 데이터를 받아올 receiveBuffer 를 선언함
                                byte[] receiveBuffer = new byte[512];

                                try
                                {
                                        Console.WriteLine("UDP 에코 서버를 시작합니다");
                                        while( true )
                                        {
                                                // 기다리고 있다가 remoteEP 로부터 데이터를 받는다
                                                // receivedSize  : 받은 바이트수
                                                // receiveBuffer : 받은 데이터가 들어갈 저장소
                                                // remoteEP      : 데이터를 받아올 원격컴퓨터의 IP종단점
                                                int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref remoteEP);
                                                Console.Write(DateTime.Now.ToShortTimeString() + " 메세지 : ");
                                                Console.WriteLine(Encoding.UTF8.GetString(receiveBuffer, 0,receivedSize));
                                                
                                                // 받은 데이터(receiveBuffer)를 remoteEP 로 다시 보낸다
                                                udpSocket.SendTo(receiveBuffer, receivedSize, SocketFlags.None, remoteEP);
                                        }
                                }
                                catch (SocketException se)
                                {
                                        Console.WriteLine(se.Message);
                                }
                                finally
                                {
                                         udpSocket.Close();
                                }
                        }
                        catch (SocketException se)
                        {
                                Console.WriteLine(se.Message);
                        }

                }
        }
}

 

노트북 내에서는 통신이 잘 되는 것을 확인했으니 모션보드와 통신을 해보겠습니다.

5432라는 포트번호를 제가 가지고있는 모션보드의 포트번호인 4000으로 바꾸고 client코드를 실행했을 때 아래와 같이 응답이 오긴하는데

첫번째 과제는 아래와 같이 응답이 오도록 하는 것 입니다. 어떻게 해야할까요

 

수정한 코드

 

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace UDPEchoClient
{
    class App
    {
        private const int ServerPortNumber = 4000;

        static void Main()
        {
            try
            {
                Socket udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                EndPoint localEP = new IPEndPoint(IPAddress.Any, 4000);
                IPAddress ip1 = IPAddress.Parse("192.168.10.7");
                EndPoint remoteEP = new IPEndPoint(ip1, ServerPortNumber);

                udpSocket.Bind(localEP);
                int i = 0;
                while (i++ < 10)
                {
                    Console.WriteLine("보낼 메세지를 입력하세요 ({0}/10)", i);
                    byte[] sendBuffer = Encoding.UTF8.GetBytes(Console.ReadLine());
                    udpSocket.SendTo(sendBuffer, remoteEP);

                    byte[] receiveBuffer = new byte[512];
                    int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref remoteEP);
                    Console.Write("UDP 에코 메세지 : ");
                    Console.WriteLine(Encoding.UTF8.GetString(receiveBuffer, 0, receivedSize));
                }
                udpSocket.Close();
            }
            catch (SocketException se)
            {
                Console.WriteLine(se.Message);
            }
        }
    }
}

 

성공!!!

 

두번째 과제

 

 

두번째 과제도 성공!!

 

다음과제는 이것을 콘솔창에서 하는 것이 아니라 c#의 net framework라는 앱을 통해 버튼을 눌러 정보를 보내는 창을 만드는 것입니다. 

 

net framework 만들기

1. Visual Studio에서 파일 > 새로 만들기 > 프로젝트 를 차례로 선택하고, Visual C# 노드를 선택하고, "Windows Forms 앱(.NET Framework) 템플릿을 선택

2.  Ctrl+Alt+키로 도구상자 열기 --> pin 아이콘으로 도구상자 고정하기

 

양식에 Button 추가

1. 모든 Windows Forms 누르고 Button을 선택한 후 드래그로 끌어와서 넣기

2. 속성(마우스 우클릭)에서 Text 에 button1 대신 넣을 이름 쓰기

3. 시작 단추로 실행

 

 

 

양식에 텍스트를 내보낼 레이블 추가

1. 레이블을 선택하고 드래그로 끌어와서 넣기

2. 속성에서 디자인에 label1 대신 넣고싶은 텍스트 넣기

 

양식에 코드 추가

1. 넣은 버튼을 두번클릭합니다.

2. 아래 그림과 같이 private void button부분에 코드를 추가합니다.

** 버튼 속성에서 디자인에 이름을 바꾸면 button1_Click에서 button1이 바꾼이름이 됩니다.

실행

 

[send 클릭 전]                                                                                       [send 클릭 후]

 

이후 여러 toolbox로 기능을 넣고 넣은 부분을 더블클릭하면 그와 관련된 함수를 짤수있게 코드가 추가됩니다.

 

메세지 입력하고 출력하는 것 성공

 

그럼 모션보드와 ip주소를 연결하는 방법은 뭘까요?

일단 조건문을 사용하여 제가 연결하고싶은 주소와 같으면 연결이 됐다는 코드를 짜봤습니다.

 

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void 메세지전송_Click(object sender, EventArgs e)
        {
            string str = string.Empty; // 입력받을 곳을 비우기
            str = textBox1.Text; // 이름이 textBox1이라는 곳에 넣고싶은 것 쓰기
            textBox2.Text = str; // 메세지 전송이라는 버튼을 눌렀을때 textBox2라는 곳에 textBox1과 같은 것이 입력되도록 하기
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {
            string str = string.Empty;  // 입력받을 곳을 비우기
            str = ip.Text;  // ip라고 이름이 붙여진 텍스트상자에 입력하고싶은 것 입력하기
        }

        private void 연결하기_Click(object sender, EventArgs e)
        {
            string connect = "192";  // 192라고 입력받기를 원한다.
            if (connect==ip.Text) // ip 텍스트상자에 입력한 것과 내가 원하던 것이 같으면
            {
                연결전.Text = "연결완료"; // 연결완료라고 레이블을 바꾸기
            }
            else
            {
                연결전.Text = "연결실패"; // 그렇지않으면 연결실패라고 레이블 바꾸기
            }
        }
    }
}

 

** 여러줄 입력하기

저 파란부분을 누르고 MultiLine을 체크하면 여러줄을 입력할수 있습니다.

 

그런데 ip주소를 입력한 후 연결하기 버튼을 눌렀을때 진짜 모션보드랑 연결이 되려면 어떻게 해야할까요?

원래 코드랑 폼코드를 합치면 되는데 그게 힘드네요..

 

응답받기 성공

 

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace WindowsFormsApp6
{
    public partial class Form1 : Form
    {
        private const int ServerPortNumber = 4000;

        Socket udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);  // 선언, 초기화
        EndPoint localEP = new IPEndPoint(IPAddress.Any, 4000);
        EndPoint remoteEP = new IPEndPoint(IPAddress.Parse("192.168.10.7"), ServerPortNumber);
        
        
        public Form1()
        {
            InitializeComponent();
            udpSocket.Bind(localEP);  // 실행

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void 메세지전송_Click(object sender, EventArgs e)
        {
            string str = string.Empty;
            str = textBox1.Text;  // textBox1이름을 바꾸고싶으면 디자인에 Name을 바꾸면 됩니다. 
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, remoteEP);
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref remoteEP);
            textBox2.Text = Encoding.UTF8.GetString(receiveBuffer);
        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {
            string str = string.Empty;
            str = ip.Text;
        }

        private void 연결하기_Click(object sender, EventArgs e)
        {
            string connect="192";
            if(connect==ip.Text)
            {
                연결전.Text = "연결완료";
            }
            else
            {
                연결전.Text = "연결실패";
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

 

이제 IP랑 PORT번호도 주는걸 만들어봅시다

 

 

이런 오류가 떴는데 무슨뜻일까요?

전역 변수로 ip랑 port를 0으로 선언해서 그런거였더라구요. 지역변수로 선언해 주니까 잘 됩니다.

 

ip주소와 port번호를 받아서 모션보드와 연결하고 메세지를 보내면 받는 것까지 성공했습니다.

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace WindowsFormsApp6
{
    public partial class Form1 : Form
    {

        Socket udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);  // 선언, 초기화
        EndPoint localEP = new IPEndPoint(IPAddress.Any,0);
        EndPoint remoteEP = new IPEndPoint(0, 0); // 전역변수로 선언해 주긴했지만 모두 0으로 초기화했습니다.


        public Form1()
        {
            InitializeComponent();
            udpSocket.Bind(localEP);  // 실행
            this.ActiveControl = ip; // 폼을 시작하자마자 ip 텍스트박스에 커서가 가게하기

        }

        private void label1_Click(object sender, EventArgs e)  // 
        {
            // 전송할 메세지 label
        }

        private void ip_TextChanged(object sender, EventArgs e)
        {
            // ip 입력하는 textbox
        }

        private void 연결하기_Click(object sender, EventArgs e)
        {
            // 연결하기 버튼
            // 위에서 전역변수로 지정해줬던 ip와 port번호 받는것을 지역변수로 선언했습니다.
            string ipaddress = string.Empty;
            ipaddress = ip.Text;  // ip 번호 입력
            IPAddress ipin = IPAddress.Parse(ipaddress);  // 문자열 ip주소를 숫자로 변환하기

            string portn = string.Empty;
            portn = port.Text;  // 포트 번호 입력
            int portin = Convert.ToInt32(portn);  // 문자열 포트 번호를 int형으로 변환하기

            EndPoint localEP = new IPEndPoint(IPAddress.Any, portin);
            EndPoint remoteEP = new IPEndPoint(ipin, portin);

            if(Convert.ToBoolean(portin))  // int형인 SeverPortNumber를 bool로 변환
            {
                연결전.Text = "연결완료";
            }
            else
            {
                연결전.Text = "연결실패";
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 만든 폼 띄우기
        }


        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            // 받은 메세지 입력되는 textbox
        }



        private void textBox1_TextChanged_1(object sender, EventArgs e)
        {
            // 전송할 메세지 입력하는 textbox
        }

        private void 메세지전송_Click(object sender, EventArgs e)
        {
            // 메세지전송
            // 여기서도 똑같이 ip와 port번호 받는것을 지역변수로 선언해 줬습니다.
            string ipaddress = string.Empty;
            ipaddress = ip.Text;  // ip 번호 입력
            IPAddress ipin = IPAddress.Parse(ipaddress);  // 문자열 ip주소를 숫자로 변환하기

            string portn = string.Empty;
            portn = port.Text;  // 포트 번호 입력
            int portin = Convert.ToInt32(portn);  // 문자열 포트 번호를 int형으로 변환하기

            EndPoint localEP = new IPEndPoint(IPAddress.Any, portin);
            EndPoint remoteEP = new IPEndPoint(ipin, portin);

            string str = string.Empty;
            str = textBox1.Text;
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, remoteEP);
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref remoteEP);
            textBox2.Text = Encoding.UTF8.GetString(receiveBuffer);
        }

        private void label3_Click(object sender, EventArgs e)
        {
            // 연결할 주소입력 label
        }

        private void label4_Click(object sender, EventArgs e)
        {
            // 포트번호 입력 label
        }

        private void port_TextChanged(object sender, EventArgs e)
        {
            // port번호 입력하는 textbox
        }

        private void 연결전_Click(object sender, EventArgs e)
        {
            // 연결전 label
        }

        private void label2_Click(object sender, EventArgs e)
        {
            // 받은 메세지 label
        }
    }
}

 

위의 코드에서 port번호를 받아왔을때 연결완료라고 뜨게하면 실제로 연결되지도않았는데 잘못된 번호이더라도 연결완료라고 뜨게 되더라구요. 그래서 remoteEP를 받아오면 연결완료라고 뜨게 하려고했는데 다음과 같은 오류가 떴습니다.

 

 

코드짜다가 위의 사진에서 처럼 연결전이라는 이름을 바꾸고싶으면 코드상의 연결전이름으로 된 함수로 가서 연결전에 커서를 두고 shift+F12를 누르면 Designer라는 파일이 참조창에 뜰것입니다. 그럼 함수의 이름을 먼저 바꾼후 Designer파일의 EventHandler에 한글이름을 바꾸면 됩니다. 

 

일단 remoteEP를 받아오는 대신 ip주소와 port주소가 원하는 것과 같으면 연결완료라고 뜨게 만들었습니다. 그런데 이또한 문제가있습니다. 왜냐햐면 text가 일치한다고 연결이 됐다고 할수는 없기때문에 연결되지않았지만 text가 일치하면 연결완료라고 뜹니다. 진짜 연결이 됐을때를 조건으로 쓰고싶으면 어떻게 해야할까요?

 

 

 

연결실패일때 메세지를 전송하면 받아오지못하거나 코드에 오류가 발생합니다.

 

여기서 또다른 의문점은 제가 ip주소와 port번호를 지역변수로 줬는데 이는 코드가 반복되는 부분입니다. 혹시 ip주소와 port번호를 받아올수있는 다른 방법이 있을까요? 지역변수로 주는 방법밖에 없을까요?

 

모션보드는 motion target position인 U[0,5]에서 위치를 받으면 motion counter position인 U[0,4]에 그위치그대로 출력합니다. 그래서 위에서 U[0,5]에 5000을 주면 U[0,4]에도 5000을 출력한 것입니다.

 

목표위치를 주고 move라는 버튼을 눌렀을때 모터가 그 위치까지 가기위해 현재위치가 변하는 것을 계속 출력하는 폼을 만드는 방법은 무엇일까요? while 문으로 목표위치까지 갈때까지 현재위치를 업데이트하라는 방식으로 해보려고합니다.그게 아니였습니다. 폼에 timer만 추가해주니까 바로 현재위치를 업데이트 하도록 만들 수 있었습니다.

 

motion counter position : 마지막 위치

 

타이머를 추가하여 현재위치를 계속업데이트하도록 하였습니다.

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace WindowsFormsApp6
{
    public partial class Form1 : Form
    {

        Socket udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);  // 선언, 초기화
        //EndPoint localEP = new IPEndPoint(IPAddress.Any,0);
        EndPoint _remoteEP;


        public Form1()
        {
            InitializeComponent();
            //udpSocket.Bind(localEP);  // 실행
            //this.ActiveControl = textbox_ip; // 폼을 시작하자마자 ip 텍스트박스에 커서가 가게하기

            this.message.Enabled = false;
            this.textbox_ip.Text = "192.168.10.7";
            this.textbox_port.Text = "4000";
        }

        private void label1_Click(object sender, EventArgs e)  
        {
            // 전송할 메세지 label
        }

        private void ip_TextChanged(object sender, EventArgs e)
        {
            // ip 입력하는 textbox
        }

        private void connect_Click(object sender, EventArgs e)
        {
            // 연결하기 버튼
            string ipaddress = string.Empty;
            ipaddress = textbox_ip.Text;  // ip 번호 입력
            IPAddress ipin = IPAddress.Parse(ipaddress);  // 문자열 ip주소를 숫자로 변환하기

            string portn = string.Empty;
            portn = textbox_port.Text;  // 포트 번호 입력
            int portin = Convert.ToInt32(portn);  // 문자열 포트 번호를 int형으로 변환하기



            if((Convert.ToString(ipin)=="192.168.10.7") && (portin==4000)) // ip주소와 port번호가 원하는 것과 일치하면
            {
                before.Text = "유효한 IP 와 Port Number";
                this.message.Enabled = true;

                //EndPoint localEP = new IPEndPoint(IPAddress.Any, portin);
                _remoteEP = new IPEndPoint(ipin, portin);

                this.timer1.Start();
            }
            else
            {
                before.Text = "IP 와 Port Number 확인해 주세요";
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 만든 폼 띄우기
        }


        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            // 받은 메세지 입력되는 textbox
        }



        private void textBox1_TextChanged_1(object sender, EventArgs e)
        {
            // 전송할 메세지 입력하는 textbox
        }

        private void message_Click(object sender, EventArgs e)
        {
            // 메세지전송
            //string ipaddress = string.Empty;
            //ipaddress = ip.Text;  // ip 번호 입력
            //IPAddress ipin = IPAddress.Parse(ipaddress);  // 문자열 ip주소를 숫자로 변환하기

            //string portn = string.Empty;
            //portn = port.Text;  // 포트 번호 입력
            //int portin = Convert.ToInt32(portn);  // 문자열 포트 번호를 int형으로 변환하기

            //EndPoint localEP = new IPEndPoint(IPAddress.Any, portin);
            //EndPoint remoteEP = new IPEndPoint(ipin, portin);

            string str = string.Empty;
            str = textBox1.Text;
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            textBox2.Text = Encoding.UTF8.GetString(receiveBuffer); // 받아온 receiveBuffer를 textbox에 넣기
        }

        private void label3_Click(object sender, EventArgs e)
        {
            // 연결할 주소입력 label
        }

        private void label4_Click(object sender, EventArgs e)
        {
            // 포트번호 입력 label
        }

        private void port_TextChanged(object sender, EventArgs e)
        {
            // port번호 입력하는 textbox
        }

        private void before_Click(object sender, EventArgs e)
        {
            // 연결전 label
        }

        private void label2_Click(object sender, EventArgs e)
        {
            // 받은 메세지 label
        }

        private void button_getCurrentPos_Click(object sender, EventArgs e)
        {
            string str = string.Empty;
            str = "U[0,3]=0,M[0]=5,U[0,4]";
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            textBox2.Text = Encoding.UTF8.GetString(receiveBuffer); // 받아온 receiveBuffer를 textbox에 넣기
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            string str = string.Empty;
            str = "U[0,3]=0,M[0]=5,U[0,4]";
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            textBox2.Text = Encoding.UTF8.GetString(receiveBuffer);
        }
    }
}

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace WindowsFormsApp6
{
    public partial class Form1 : Form
    {

        Socket udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);  // 선언, 초기화
        //EndPoint localEP = new IPEndPoint(IPAddress.Any,0); // localEP를 사용할데가 없다.
        EndPoint _remoteEP;  // 전역변수로 member변수를 선언


        public Form1()
        {
            InitializeComponent();
            //udpSocket.Bind(localEP);  // tcp/ip일때 사용
            //this.ActiveControl = textbox_ip; // 폼을 시작하자마자 ip 텍스트박스에 커서가 가게하기

            this.button_send.Enabled = false;  // 폼을 열었을때 버튼 누르지못하게 하기
            this.button_getCurrentPos.Enabled = false;
            this.textbox_ip.Text = "192.168.10.7";
            this.textbox_port.Text = "4000";
        }

        private void label1_Click(object sender, EventArgs e)  
        {
            // 전송할 메세지 label
        }

        private void ip_TextChanged(object sender, EventArgs e)
        {
            // ip 입력하는 textbox
        }

        private void connect_Click(object sender, EventArgs e)
        {
            // 연결하기 버튼
            string ipaddress = string.Empty;
            ipaddress = textbox_ip.Text;  // ip 번호 입력
            IPAddress ipin = IPAddress.Parse(ipaddress);  // 문자열 ip주소를 숫자로 변환하기

            string portn = string.Empty;
            portn = textbox_port.Text;  // 포트 번호 입력
            int portin = Convert.ToInt32(portn);  // 문자열 포트 번호를 int형으로 변환하기



            if((Convert.ToString(ipin)=="192.168.10.7") && (portin==4000)) // ip주소와 port번호가 원하는 것과 일치하면
            {
                before.Text = "유효한 IP 와 Port Number";
                this.button_send.Enabled = true;   // ip주소가 유효하면 위치전송 버튼 on
                this.button_getCurrentPos.Enabled = true;  // 같이 현재위치보기 버튼 on 

                //EndPoint localEP = new IPEndPoint(IPAddress.Any, portin);
                _remoteEP = new IPEndPoint(ipin, portin);

                this.timer1.Start();  // 유효한 ip가 입력되면 타이머 시작
            }
            else
            {
                before.Text = "IP 와 Port Number 확인해 주세요";
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 만든 폼 띄우기
        }


        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            // 받은 메세지 입력되는 textbox
        }



        private void textBox1_TextChanged_1(object sender, EventArgs e)
        {
            // 전송할 메세지 입력하는 textbox
        }

        private void button_send_Click(object sender, EventArgs e)
        {
            // 메세지전송
            //string ipaddress = string.Empty;
            //ipaddress = ip.Text;  // ip 번호 입력
            //IPAddress ipin = IPAddress.Parse(ipaddress);  // 문자열 ip주소를 숫자로 변환하기

            //string portn = string.Empty;
            //portn = port.Text;  // 포트 번호 입력
            //int portin = Convert.ToInt32(portn);  // 문자열 포트 번호를 int형으로 변환하기

            //EndPoint localEP = new IPEndPoint(IPAddress.Any, portin);
            //EndPoint remoteEP = new IPEndPoint(ipin, portin);

            string str = string.Empty;
            str = textBox1.Text;
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            textBox2.Text = Encoding.UTF8.GetString(receiveBuffer); // 받아온 receiveBuffer를 textbox에 넣기
        }

        private void label3_Click(object sender, EventArgs e)
        {
            // 연결할 주소입력 label
        }

        private void label4_Click(object sender, EventArgs e)
        {
            // 포트번호 입력 label
        }

        private void port_TextChanged(object sender, EventArgs e)
        {
            // port번호 입력하는 textbox
        }

        private void before_Click(object sender, EventArgs e)
        {
            // 연결전 label
        }

        private void label2_Click(object sender, EventArgs e)
        {
            // 받은 메세지 label
        }

        private void button_getCurrentPos_Click(object sender, EventArgs e)
        {
            string str = string.Empty;
            str = "U[0,3]=0,M[0]=5,U[0,4]";
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            textBox2.Text = Encoding.UTF8.GetString(receiveBuffer); // 받아온 receiveBuffer를 textbox에 넣기
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            string str = string.Empty;
            str = "U[0,3]=0,M[0]=5,U[0,4]";
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            textBox2.Text = Encoding.UTF8.GetString(receiveBuffer);
        }
    }
}

 

** 전역변수에 어떤 변수를 쓸건지 선언만 해주면 첫번째 함수에서 지역변수를 한번만 지정해주면 그 밑에 함수에서 같은 지역변수를 또 선언해 주지않아도됩니다. 전역변수로 선언해줬기때문에 정보가 살아있습니다.

 

** 위치를 계속 받아오는 반복을 사용하기위해서는 timer가 필요합니다.

** Bind는 통신 할 것들을 연결해주라는 의미의 코드인데 udp통신에는 연결의 의미가 없기때문에 사용하지않습니다. TCP/IP통신을 할때는 Bind를 써줘야합니다.

 

** 모터의 X-Axis : 0번

   모터의 Y-Axis : 1번

 

실행화면

 

 

현재위치를 업데이트 하긴했지만 입력할때 많은 정보를 한번에 주는 대신 위치, 속도, 가속도 다 따로 주려고 합니다. 그럼 정보를 하나하나 나눠야겠죠? 

 

실행화면 

 

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace WindowsFormsApp6
{
    public partial class Form1 : Form
    {

        Socket udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);  // 선언, 초기화
        //EndPoint localEP = new IPEndPoint(IPAddress.Any,0);
        EndPoint _remoteEP;
        string str1;


        public Form1()
        {
            InitializeComponent();
            //udpSocket.Bind(localEP);  // 실행
            //this.ActiveControl = textbox_ip; // 폼을 시작하자마자 ip 텍스트박스에 커서가 가게하기

            this.button_send.Enabled = false;  // 폼을 열었을때 버튼 누르지못하게 하기
            this.button_getCurrentPos.Enabled = false;
            this.textbox_ip.Text = "192.168.10.7"; // 폼을 열었을때 텍스트 박스에 값이 들어가있도록 하기
            this.textbox_port.Text = "4000";
            //this.textBox4.Text = "100";
            //this.textBox5.Text = "15000";
            //this.textBox6.Text = "1500000";
            //this.textBox7.Text = "1500000";
            //this.textBox8.Text = "100";  // jerk : 홱 움직이다.
            //string str1 = string.Empty;
            //str1 = textBox1.Text;
            //this.textBox1.Text="U[0, 5] = " +  str1 + ", U[0, 6] = 100, U[0, 7] = 15000, U[0, 8] = 1500000, U[0, 9] = 1500000, U[0, 10] = 100, M[0] = 7";
        }

        private void label1_Click(object sender, EventArgs e)  
        {
            // 전송할 메세지 label
        }

        private void ip_TextChanged(object sender, EventArgs e)
        {
            // ip 입력하는 textbox
        }

        private void connect_Click(object sender, EventArgs e)
        {
            // 연결하기 버튼
            string ipaddress = string.Empty;
            ipaddress = textbox_ip.Text;  // ip 번호 입력
            IPAddress ipin = IPAddress.Parse(ipaddress);  // 문자열 ip주소를 숫자로 변환하기

            string portn = string.Empty;
            portn = textbox_port.Text;  // 포트 번호 입력
            int portin = Convert.ToInt32(portn);  // 문자열 포트 번호를 int형으로 변환하기



            if((Convert.ToString(ipin)=="192.168.10.7") && (portin==4000)) // ip주소와 port번호가 원하는 것과 일치하면
            {
                before.Text = "유효한 IP 와 Port Number";
                this.button_send.Enabled = true;   // ip주소가 유효하면 위치전송 버튼 on
                this.button_getCurrentPos.Enabled = true;  // 같이 현재위치보기 버튼 on 

                //EndPoint localEP = new IPEndPoint(IPAddress.Any, portin);
                _remoteEP = new IPEndPoint(ipin, portin);  // ip와 port번호가 유효하면 remoteEP에 저장한다. if문밖에 remoteEP가 있으면 유효하지 않은 정보들을 다 저장하고 마지막으로 옳은것을 저장하게 된다.

                this.timer1.Start();  // 유효한 ip가 입력되면 타이머 시작
            }
            else
            {
                before.Text = "IP 와 Port Number 확인해 주세요";
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 만든 폼 띄우기
        }


        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            // 받은 메세지 입력되는 textbox
        }



        private void textBox1_TextChanged_1(object sender, EventArgs e)
        {
            // 전송할 메세지 입력하는 textbox
        }

        private void textBox3_position_TextChanged(object sender, EventArgs e)
        {
            string str1 = string.Empty;
            str1 = textBox3_position.Text;
        }

        private void button_send_Click(object sender, EventArgs e)
        {
            // 메세지전송
            //string ipaddress = string.Empty;
            //ipaddress = ip.Text;  // ip 번호 입력
            //IPAddress ipin = IPAddress.Parse(ipaddress);  // 문자열 ip주소를 숫자로 변환하기

            //string portn = string.Empty;
            //portn = port.Text;  // 포트 번호 입력
            //int portin = Convert.ToInt32(portn);  // 문자열 포트 번호를 int형으로 변환하기

            //EndPoint localEP = new IPEndPoint(IPAddress.Any, portin);
            //EndPoint remoteEP = new IPEndPoint(ipin, portin);

            //string str = string.Empty;
            string str1 = string.Empty;   // 전송 명령 순서대로 박스에 넣기
            str1 = textBox3_position.Text;
            string str2 = string.Empty;
            str2 = textBox4.Text;
            string str3 = string.Empty;
            str3 = textBox5.Text;
            string str4 = string.Empty;
            str4 = textBox6.Text;
            string str5 = string.Empty;
            str5 = textBox7.Text;
            string str6 = string.Empty;
            str6 = textBox8.Text;
            string str = "U[0, 5] ="+ str1+", U[0, 6] = "+str2+", U[0, 7] = "+str3+", U[0, 8] = "+str4+", U[0, 9] = "+str5+", U[0, 10] = "+str6+", M[0] = 7";
            //str = textBox1.Text;
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            //textBox1.Text = Encoding.UTF8.GetString(sendBuffer);
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            //textBox2.Text = Encoding.UTF8.GetString(receiveBuffer); // 받아온 receiveBuffer를 textbox에 넣기
        }

        private void label3_Click(object sender, EventArgs e)
        {
            // 연결할 주소입력 label
        }

        private void label4_Click(object sender, EventArgs e)
        {
            // 포트번호 입력 label
        }

        private void port_TextChanged(object sender, EventArgs e)
        {
            // port번호 입력하는 textbox
        }

        private void before_Click(object sender, EventArgs e)
        {
            // 연결전 label
        }

        private void label2_Click(object sender, EventArgs e)
        {
            // 받은 메세지 label
        }

        private void button_getCurrentPos_Click(object sender, EventArgs e)  // 현재위치 버튼을 누르면 위치가 계속 업데이트 되도록했지만 timer를 넣어서 자동으로 업데이트되도록 했다.
        {
            string str = string.Empty;
            str = "U[0,3]=0,M[0]=5,U[0,4]";
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            //textBox2.Text = Encoding.UTF8.GetString(receiveBuffer); // 받아온 receiveBuffer를 textbox에 넣기
            string a = Encoding.UTF8.GetString(receiveBuffer);  // 받아온 데이터를 문자열 a에 저장
            string b = null;  // 문자열 b를 null로 선언
            for (int i = 16; i < 50; i++)  // a에 있는 문자열에서 위치를 나타내는 부분이 16번째 문자열 부터이다. 50은 그냥 어디가 끝인지몰라서 임의의 숫자 적음
            {
                b += Convert.ToString(a[i]);  // 빈 문자열 b에 a의 문자열을 하나씩 넣는다.
            }
            textBox2.Text = b;  // 수신 명령 텍스트 박스에 위치값만 적힌다.
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            string str = string.Empty;
            str = "U[0,3]=0,M[0]=5,U[0,4]";
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            //textBox2.Text = Encoding.UTF8.GetString(receiveBuffer);
            string a = Encoding.UTF8.GetString(receiveBuffer);
            string b = null;
            for (int i = 16; i < 50; i++)
            {
                b += Convert.ToString(a[i]);
            }
            textBox2.Text = b;
        }

        private void textBox4_TextChanged(object sender, EventArgs e)
        {
            string str2 = string.Empty;
            str2 = textBox4.Text;
        }

        private void textBox5_TextChanged(object sender, EventArgs e)
        {
            string str3 = string.Empty;
            str3 = textBox5.Text;
        }

        private void textBox6_TextChanged(object sender, EventArgs e)
        {
            string str4 = string.Empty;
            str4 = textBox6.Text;
        }

        private void textBox7_TextChanged(object sender, EventArgs e)
        {
            string str5 = string.Empty;
            str5 = textBox7.Text;
        }

        private void textBox8_TextChanged(object sender, EventArgs e)
        {
            string str6 = string.Empty;
            str6 = textBox8.Text;
        }
    }
}

 

위 코드가 모션보드에서는 돌아가는데 실제 모터와 연결하니까 돌아가지않았습니다. 왜그럴까요..

저는 ip주소 바꾼거밖에 없는데...

 

 

수신명령으로 받는 값은 모터의 위치를 의미합니다.

endvelocity를 줄이고 위치를 바꾸면 위치가 느리게 값이 바뀌는 것을 볼수있습니다.

acceleration은 둘다 같게 하는 것이 좋고 의미는 1초에 얼마까지 갈수있냐 입니다.

velocity를 150을 주고 acceleration을 300을 주면 1초에 속도가 300까지 변할수있다는 것인데 150까지만 변하겠다라는 의미이기때문에 0.5초만에 150을 변할수있다는 의미로 천천히 가속하거나 감속합니다.

 

velocity : 위치 변화량

acceleratioin : 속도 변화량

jerk : 가속도 변화량

 

세미나 후 더 간단하게 코드를 바꿨습니다.

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace WindowsFormsApp6
{
    public partial class Form1 : Form
    {

        Socket udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);  // 선언, 초기화
        //EndPoint localEP = new IPEndPoint(IPAddress.Any,0);
        EndPoint _remoteEP;
        //string positionValue;


        public Form1()
        {
            InitializeComponent();
            //udpSocket.Bind(localEP);  // 실행
            //this.ActiveControl = textbox_ip; // 폼을 시작하자마자 ip 텍스트박스에 커서가 가게하기


            //ip 5번 천천히, 빠르게
            this.button_send.Enabled = false;  // 폼을 열었을때 버튼 누르지못하게 하기
            this.button_getCurrentPos.Enabled = false;
            this.textbox_ip.Text = "192.168.10.7"; // 폼을 열었을때 텍스트 박스에 값이 들어가있도록 하기
            this.textbox_port.Text = "4000";
            //this.textBox4.Text = "100";
            //this.textBox5.Text = "15000";
            //this.textBox6.Text = "1500000";
            //this.textBox7.Text = "1500000";
            //this.textBox8.Text = "100";  // jerk : 홱 움직이다.
            //string positionValue = string.Empty;
            //positionValue = textBox1.Text;
            //this.textBox1.Text="U[0, 5] = " +  positionValue + ", U[0, 6] = 100, U[0, 7] = 15000, U[0, 8] = 1500000, U[0, 9] = 1500000, U[0, 10] = 100, M[0] = 7";
        }

        private void label1_Click(object sender, EventArgs e)  
        {
            // 전송할 메세지 label
        }

        private void ip_TextChanged(object sender, EventArgs e)
        {
            // ip 입력하는 textbox
        }

        private void connect_Click(object sender, EventArgs e)
        {
            // 연결하기 버튼
            string ipaddress = string.Empty;
            ipaddress = textbox_ip.Text;  // ip 번호 입력
            IPAddress ipin = IPAddress.Parse(ipaddress);  // 문자열 ip주소를 숫자로 변환하기

            string portn = string.Empty;
            portn = textbox_port.Text;  // 포트 번호 입력
            int portin = Convert.ToInt32(portn);  // 문자열 포트 번호를 int형으로 변환하기



            if((Convert.ToString(ipin)=="192.168.10.7") && (portin==4000)) // ip주소와 port번호가 원하는 것과 일치하면
            {
                before.Text = "유효한 IP 와 Port Number";
                this.button_send.Enabled = true;   // ip주소가 유효하면 위치전송 버튼 on
                this.button_getCurrentPos.Enabled = true;  // 같이 현재위치보기 버튼 on 

                //EndPoint localEP = new IPEndPoint(IPAddress.Any, portin);
                _remoteEP = new IPEndPoint(ipin, portin);  // ip와 port번호가 유효하면 remoteEP에 저장한다. if문밖에 remoteEP가 있으면 유효하지 않은 정보들을 다 저장하고 마지막으로 옳은것을 저장하게 된다.

                this.timer1.Start();  // 유효한 ip가 입력되면 타이머 시작
            }
            else
            {
                before.Text = "IP 와 Port Number 확인해 주세요";
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 만든 폼 띄우기
        }


        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            // 받은 메세지 입력되는 textbox
        }



        private void textBox1_TextChanged_1(object sender, EventArgs e)
        {
            // 전송할 메세지 입력하는 textbox
        }

        private void textBox3_position_TextChanged(object sender, EventArgs e)
        {
            string positionValue = string.Empty;
            positionValue = textBox3_position.Text;
        }

        private void button_send_Click(object sender, EventArgs e)
        {
            // 메세지전송
            //string ipaddress = string.Empty;
            //ipaddress = ip.Text;  // ip 번호 입력
            //IPAddress ipin = IPAddress.Parse(ipaddress);  // 문자열 ip주소를 숫자로 변환하기

            //string portn = string.Empty;
            //portn = port.Text;  // 포트 번호 입력
            //int portin = Convert.ToInt32(portn);  // 문자열 포트 번호를 int형으로 변환하기

            //EndPoint localEP = new IPEndPoint(IPAddress.Any, portin);
            //EndPoint remoteEP = new IPEndPoint(ipin, portin);

            //string str = string.Empty;
            string positionValue = string.Empty;   // 전송 명령 순서대로 박스에 넣기
            positionValue = textBox3_position.Text;
            string startvelocityValue = string.Empty;
            startvelocityValue = textBox4.Text;
            string  endvelocityValue= string.Empty;
            endvelocityValue = textBox5.Text;
            string accelerationValue = string.Empty;
            accelerationValue = textBox6.Text;
            string decelerationValue = string.Empty;
            decelerationValue = textBox7.Text;
            string jerkValue = string.Empty;
            jerkValue = textBox8.Text;

            string sendMsg = String.Format("U[0, 5] ={0}, U[0, 6] ={1}, U[0, 7] ={2}, U[0, 8] ={3}, U[0, 9] ={4}, U[0, 10] ={5}, M[0] = 7", positionValue, startvelocityValue,endvelocityValue, accelerationValue, decelerationValue, jerkValue);
            //str = textBox1.Text;
            byte[] sendBuffer = Encoding.UTF8.GetBytes(sendMsg);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            //textBox1.Text = Encoding.UTF8.GetString(sendBuffer);
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            //textBox2.Text = Encoding.UTF8.GetString(receiveBuffer); // 받아온 receiveBuffer를 textbox에 넣기
        }

        private void label3_Click(object sender, EventArgs e)
        {
            // 연결할 주소입력 label
        }

        private void label4_Click(object sender, EventArgs e)
        {
            // 포트번호 입력 label
        }

        private void port_TextChanged(object sender, EventArgs e)
        {
            // port번호 입력하는 textbox
        }

        private void before_Click(object sender, EventArgs e)
        {
            // 연결전 label
        }

        private void label2_Click(object sender, EventArgs e)
        {
            // 받은 메세지 label
        }

        private void button_getCurrentPos_Click(object sender, EventArgs e)  // 현재위치 버튼을 누르면 위치가 계속 업데이트 되도록했지만 timer를 넣어서 자동으로 업데이트되도록 했다.
        {
            string str = string.Empty;
            str = "U[0,3]=0,M[0]=5,U[0,4]";
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            //textBox2.Text = Encoding.UTF8.GetString(receiveBuffer); // 받아온 receiveBuffer를 textbox에 넣기
            string receivedMsg = Encoding.UTF8.GetString(receiveBuffer);  // 받아온 데이터를 문자열 a에 저장
            //string b = null;  // 문자열 b를 null로 선언
            //for (int i = 16; i < 50; i++)  // a에 있는 문자열에서 위치를 나타내는 부분이 16번째 문자열 부터이다. 50은 그냥 어디가 끝인지몰라서 임의의 숫자 적음
            //{
            //    b += Convert.ToString(receivedMsg[i]);  // 빈 문자열 b에 a의 문자열을 하나씩 넣는다.
            //}
            //textBox2.Text = b;  // 수신 명령 텍스트 박스에 위치값만 적힌다.

            //string [] splittedMsg = receivedMsg.Split(new char[] { ':',',', '[', ']', '=' });  // split : 문자열 나누기
            string[] splittedMsg = receivedMsg.Split(new char[] { ':', ',',' '});
            //textBox2.Text = Convert.ToString(splittedMsg.Length);  // 문자열을 나눴을때 나오는 개수 세기
            textBox2.Text = splittedMsg[6];  // 문자열 7개중 마지막 번지인 6을 출력하면 위치값만 나온다.

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            string str = string.Empty;
            str = "U[0,3]=0,M[0]=5,U[0,4]";
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            //textBox2.Text = Encoding.UTF8.GetString(receiveBuffer);
            string receivedMsg = Encoding.UTF8.GetString(receiveBuffer);
            //string b = null;
            //for (int i = 16; i < 50; i++)
            //{
            //    b += Convert.ToString(a[i]);
            //}
            //textBox2.Text = b;

            //string[] splittedMsg = receivedMsg.Split(new char[] { ':',',', '[', ']', '=' });  // split : 문자열 나누기
            string[] splittedMsg = receivedMsg.Split(new char[] { ':', ',',' ' });
            //textBox2.Text = Convert.ToString(splittedMsg.Length);
            textBox2.Text = splittedMsg[6];
        }

        private void textBox4_TextChanged(object sender, EventArgs e)
        {
            string startvelocityValue = string.Empty;
            startvelocityValue = textBox4.Text;
        }

        private void textBox5_TextChanged(object sender, EventArgs e)
        {
            string endvelocityValue = string.Empty;
            endvelocityValue = textBox5.Text;
        }

        private void textBox6_TextChanged(object sender, EventArgs e)
        {
            string accelerationValue = string.Empty;
            accelerationValue = textBox6.Text;
        }

        private void textBox7_TextChanged(object sender, EventArgs e)
        {
            string decelerationValue = string.Empty;
            decelerationValue = textBox7.Text;
        }

        private void textBox8_TextChanged(object sender, EventArgs e)
        {
            string jerkValue = string.Empty;
            jerkValue = textBox8.Text;
        }
    }
}

 

 

end velocity를 바꾸면 위치가 바뀌는 속도가 달라집니다.

 

 

 

이제 실제로 모터를 돌려보려고 합니다.

 

앞뒤로 움직이기 ( x축 움직이기 )

 

 

 

position을 바꾸고 위치를 전송하면 모터가 x축으로 움직이고 폼에서도 위치가 계속 바뀌는 것을 확인할 수 있습니다.

 

왼쪽,오른쪽으로 움직이기 ( y축 움직이기 )

 

 

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace WindowsFormsApp6
{
    public partial class Form1 : Form
    {

        Socket udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);  // 선언, 초기화
        //EndPoint localEP = new IPEndPoint(IPAddress.Any,0);
        EndPoint _remoteEP;
        //string positionValue;


        public Form1()
        {
            InitializeComponent();
            //udpSocket.Bind(localEP);  // 실행
            //this.ActiveControl = textbox_ip; // 폼을 시작하자마자 ip 텍스트박스에 커서가 가게하기

            // 조그명령으로 앱으로 이동
            // 사각형 그리기
            // x축 
            // 뒤 마지막 : 1110297
            // 앞 마지막 : 952240
            // y축
            // 오른쪽 마지막 : 51339
            // 왼쪽 마지막 : -192068
            //ip 5번 천천히, 빠르게
            this.button_send.Enabled = false;  // 폼을 열었을때 버튼 누르지못하게 하기
            this.button_getCurrentPos.Enabled = false;
            this.textbox_ip.Text = "192.168.10.5"; // 폼을 열었을때 텍스트 박스에 값이 들어가있도록 하기
            this.textbox_port.Text = "4000";
            this.textBox4.Text = "100";
            this.textBox5.Text = "15000";
            this.textBox6.Text = "1500000";
            this.textBox7.Text = "1500000";
            this.textBox8.Text = "100";  // jerk : 홱 움직이다.
            //string positionValue = string.Empty;
            //positionValue = textBox1.Text;
            //this.textBox1.Text="U[0, 5] = " +  positionValue + ", U[0, 6] = 100, U[0, 7] = 15000, U[0, 8] = 1500000, U[0, 9] = 1500000, U[0, 10] = 100, M[0] = 7";
        }

        private void label1_Click(object sender, EventArgs e)  
        {
            // 전송할 메세지 label
        }

        private void ip_TextChanged(object sender, EventArgs e)
        {
            // ip 입력하는 textbox
        }

        private void connect_Click(object sender, EventArgs e)
        {
            // 연결하기 버튼
            string ipaddress = string.Empty;
            ipaddress = textbox_ip.Text;  // ip 번호 입력
            IPAddress ipin = IPAddress.Parse(ipaddress);  // 문자열 ip주소를 숫자로 변환하기

            string portn = string.Empty;
            portn = textbox_port.Text;  // 포트 번호 입력
            int portin = Convert.ToInt32(portn);  // 문자열 포트 번호를 int형으로 변환하기



            if((Convert.ToString(ipin)=="192.168.10.5") && (portin==4000)) // ip주소와 port번호가 원하는 것과 일치하면
            {
                before.Text = "유효한 IP 와 Port Number";
                this.button_send.Enabled = true;   // ip주소가 유효하면 위치전송 버튼 on
                this.button_getCurrentPos.Enabled = true;  // 같이 현재위치보기 버튼 on 

                //EndPoint localEP = new IPEndPoint(IPAddress.Any, portin);
                _remoteEP = new IPEndPoint(ipin, portin);  // ip와 port번호가 유효하면 remoteEP에 저장한다. if문밖에 remoteEP가 있으면 유효하지 않은 정보들을 다 저장하고 마지막으로 옳은것을 저장하게 된다.

                this.timer1.Start();  // 유효한 ip가 입력되면 타이머 시작
            }
            else
            {
                before.Text = "IP 와 Port Number 확인해 주세요";
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 만든 폼 띄우기
        }


        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            // 받은 메세지 입력되는 textbox
        }



        private void textBox1_TextChanged_1(object sender, EventArgs e)
        {
            // 전송할 메세지 입력하는 textbox
        }

        private void textBox3_position_TextChanged(object sender, EventArgs e)
        {
            string positionValue = string.Empty;
            positionValue = textBox3_position.Text;
        }

        private void button_send_Click(object sender, EventArgs e)
        {
            // 메세지전송
            //string ipaddress = string.Empty;
            //ipaddress = ip.Text;  // ip 번호 입력
            //IPAddress ipin = IPAddress.Parse(ipaddress);  // 문자열 ip주소를 숫자로 변환하기

            //string portn = string.Empty;
            //portn = port.Text;  // 포트 번호 입력
            //int portin = Convert.ToInt32(portn);  // 문자열 포트 번호를 int형으로 변환하기

            //EndPoint localEP = new IPEndPoint(IPAddress.Any, portin);
            //EndPoint remoteEP = new IPEndPoint(ipin, portin);

            //string str = string.Empty;
            string positionValue = string.Empty;   // 전송 명령 순서대로 박스에 넣기
            positionValue = textBox3_position.Text;
            string startvelocityValue = string.Empty;
            startvelocityValue = textBox4.Text;
            string  endvelocityValue= string.Empty;
            endvelocityValue = textBox5.Text;
            string accelerationValue = string.Empty;
            accelerationValue = textBox6.Text;
            string decelerationValue = string.Empty;
            decelerationValue = textBox7.Text;
            string jerkValue = string.Empty;
            jerkValue = textBox8.Text;

            // 0은 x축, 1은 y축
            //string sendMsg = String.Format("U[0, 5] ={0}, U[0, 6] ={1}, U[0, 7] ={2}, U[0, 8] ={3}, U[0, 9] ={4}, U[0, 10] ={5}, M[0] = 7", positionValue, startvelocityValue,endvelocityValue, accelerationValue, decelerationValue, jerkValue);
            string sendMsg = String.Format("U[1, 5] ={0}, U[1, 6] ={1}, U[1, 7] ={2}, U[1, 8] ={3}, U[1, 9] ={4}, U[1, 10] ={5}, M[1] = 7", positionValue, startvelocityValue, endvelocityValue, accelerationValue, decelerationValue, jerkValue);
            //str = textBox1.Text;
            byte[] sendBuffer = Encoding.UTF8.GetBytes(sendMsg);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            //textBox1.Text = Encoding.UTF8.GetString(sendBuffer);
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            //textBox2.Text = Encoding.UTF8.GetString(receiveBuffer); // 받아온 receiveBuffer를 textbox에 넣기
        }

        private void label3_Click(object sender, EventArgs e)
        {
            // 연결할 주소입력 label
        }

        private void label4_Click(object sender, EventArgs e)
        {
            // 포트번호 입력 label
        }

        private void port_TextChanged(object sender, EventArgs e)
        {
            // port번호 입력하는 textbox
        }

        private void before_Click(object sender, EventArgs e)
        {
            // 연결전 label
        }

        private void label2_Click(object sender, EventArgs e)
        {
            // 받은 메세지 label
        }

        private void button_getCurrentPos_Click(object sender, EventArgs e)  // 현재위치 버튼을 누르면 위치가 계속 업데이트 되도록했지만 timer를 넣어서 자동으로 업데이트되도록 했다.
        {
            string str = string.Empty;
            str = "U[1,3]=0,M[1]=5,U[1,4]";
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            //textBox2.Text = Encoding.UTF8.GetString(receiveBuffer); // 받아온 receiveBuffer를 textbox에 넣기
            string receivedMsg = Encoding.UTF8.GetString(receiveBuffer);  // 받아온 데이터를 문자열 a에 저장
            //string b = null;  // 문자열 b를 null로 선언
            //for (int i = 16; i < 50; i++)  // a에 있는 문자열에서 위치를 나타내는 부분이 16번째 문자열 부터이다. 50은 그냥 어디가 끝인지몰라서 임의의 숫자 적음
            //{
            //    b += Convert.ToString(receivedMsg[i]);  // 빈 문자열 b에 a의 문자열을 하나씩 넣는다.
            //}
            //textBox2.Text = b;  // 수신 명령 텍스트 박스에 위치값만 적힌다.

            //string [] splittedMsg = receivedMsg.Split(new char[] { ':',',', '[', ']', '=' });  // split : 문자열 나누기
            string[] splittedMsg = receivedMsg.Split(new char[] { ':', ',',' '});
            //textBox2.Text = Convert.ToString(splittedMsg.Length);  // 문자열을 나눴을때 나오는 개수 세기
            textBox2.Text = splittedMsg[6];  // 문자열 7개중 마지막 번지인 6을 출력하면 위치값만 나온다.

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            string str = string.Empty;
            str = "U[1,3]=0,M[1]=5,U[1,4]";
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            //textBox2.Text = Encoding.UTF8.GetString(receiveBuffer);
            string receivedMsg = Encoding.UTF8.GetString(receiveBuffer);
            //string b = null;
            //for (int i = 16; i < 50; i++)
            //{
            //    b += Convert.ToString(a[i]);
            //}
            //textBox2.Text = b;

            //string[] splittedMsg = receivedMsg.Split(new char[] { ':',',', '[', ']', '=' });  // split : 문자열 나누기
            string[] splittedMsg = receivedMsg.Split(new char[] { ':', ',',' ' });
            //textBox2.Text = Convert.ToString(splittedMsg.Length);
            textBox2.Text = splittedMsg[6];
        }

        private void textBox4_TextChanged(object sender, EventArgs e)
        {
            string startvelocityValue = string.Empty;
            startvelocityValue = textBox4.Text;
        }

        private void textBox5_TextChanged(object sender, EventArgs e)
        {
            string endvelocityValue = string.Empty;
            endvelocityValue = textBox5.Text;
        }

        private void textBox6_TextChanged(object sender, EventArgs e)
        {
            string accelerationValue = string.Empty;
            accelerationValue = textBox6.Text;
        }

        private void textBox7_TextChanged(object sender, EventArgs e)
        {
            string decelerationValue = string.Empty;
            decelerationValue = textBox7.Text;
        }

        private void textBox8_TextChanged(object sender, EventArgs e)
        {
            string jerkValue = string.Empty;
            jerkValue = textBox8.Text;
        }
    }
}

 

모터 1회전 : 10000 pulse

움직이는 거리 모터 1회전 당 : 20mm

움직일때 속도 : mm/sec  --> pulse/sec

100mm --> 500000puls/sec

그럼 end velocity에 50000을 주면 됩니다.

 

최대속도 : 1000mm/sec

 

이번에는 축을 선택하는 부분도 만들려고합니다.

폼에서 위치값은 바뀌는데 모터가 움직이지는 않습니다. 왜그럴까요..

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace WindowsFormsApp6
{
    public partial class Form1 : Form
    {

        Socket udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);  // 선언, 초기화
        //EndPoint localEP = new IPEndPoint(IPAddress.Any,0);
        EndPoint _remoteEP;
        //string positionValue;


        public Form1()
        {
            InitializeComponent();
            //udpSocket.Bind(localEP);  // 실행
            //this.ActiveControl = textbox_ip; // 폼을 시작하자마자 ip 텍스트박스에 커서가 가게하기

            // 조그명령으로 앱으로 이동
            // 사각형 그리기
            // x축 
            // 뒤 마지막 : 1110297
            // 앞 마지막 : 952240
            // y축
            // 오른쪽 마지막 : 51339
            // 왼쪽 마지막 : -192068
            //ip 5번 천천히, 빠르게
            this.button_send.Enabled = false;  // 폼을 열었을때 버튼 누르지못하게 하기
            this.button_getCurrentPos.Enabled = false;
            this.textbox_ip.Text = "192.168.10.5"; // 폼을 열었을때 텍스트 박스에 값이 들어가있도록 하기
            this.textbox_port.Text = "4000";
            this.textBox4.Text = "100";
            this.textBox5.Text = "15000";
            this.textBox6.Text = "1500000";
            this.textBox7.Text = "1500000";
            this.textBox8.Text = "100";  // jerk : 홱 움직이다.
            //string positionValue = string.Empty;
            //positionValue = textBox1.Text;
            //this.textBox1.Text="U[0, 5] = " +  positionValue + ", U[0, 6] = 100, U[0, 7] = 15000, U[0, 8] = 1500000, U[0, 9] = 1500000, U[0, 10] = 100, M[0] = 7";
        }

        private void label1_Click(object sender, EventArgs e)  
        {
            // 전송할 메세지 label
        }

        private void ip_TextChanged(object sender, EventArgs e)
        {
            // ip 입력하는 textbox
        }

        private void connect_Click(object sender, EventArgs e)
        {
            // 연결하기 버튼
            string ipaddress = string.Empty;
            ipaddress = textbox_ip.Text;  // ip 번호 입력
            IPAddress ipin = IPAddress.Parse(ipaddress);  // 문자열 ip주소를 숫자로 변환하기

            string portn = string.Empty;
            portn = textbox_port.Text;  // 포트 번호 입력
            int portin = Convert.ToInt32(portn);  // 문자열 포트 번호를 int형으로 변환하기

            string axisValue = string.Empty;
            axisValue = textBox3.Text;


            if ((Convert.ToString(ipin)=="192.168.10.5") && (portin==4000)) // ip주소와 port번호가 원하는 것과 일치하면
            {
                before.Text = "유효한 IP 와 Port Number";
                this.button_send.Enabled = true;   // ip주소가 유효하면 위치전송 버튼 on
                this.button_getCurrentPos.Enabled = true;  // 같이 현재위치보기 버튼 on 

                //EndPoint localEP = new IPEndPoint(IPAddress.Any, portin);
                _remoteEP = new IPEndPoint(ipin, portin);  // ip와 port번호가 유효하면 remoteEP에 저장한다. if문밖에 remoteEP가 있으면 유효하지 않은 정보들을 다 저장하고 마지막으로 옳은것을 저장하게 된다.
            }
            else
            {
                before.Text = "IP 와 Port Number 확인해 주세요";
            }
            if (axisValue=="1" || axisValue=="0")
            {
                this.timer1.Start();  // 유효한 ip가 입력되면 타이머 시작
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 만든 폼 띄우기
        }


        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            // 받은 메세지 입력되는 textbox
        }



        private void textBox1_TextChanged_1(object sender, EventArgs e)
        {
            // 전송할 메세지 입력하는 textbox
        }

        private void textBox3_position_TextChanged(object sender, EventArgs e)
        {
            string positionValue = string.Empty;
            positionValue = textBox3_position.Text;
        }

        private void button_send_Click(object sender, EventArgs e)
        {
            // 메세지전송
            //string ipaddress = string.Empty;
            //ipaddress = ip.Text;  // ip 번호 입력
            //IPAddress ipin = IPAddress.Parse(ipaddress);  // 문자열 ip주소를 숫자로 변환하기

            //string portn = string.Empty;
            //portn = port.Text;  // 포트 번호 입력
            //int portin = Convert.ToInt32(portn);  // 문자열 포트 번호를 int형으로 변환하기

            //EndPoint localEP = new IPEndPoint(IPAddress.Any, portin);
            //EndPoint remoteEP = new IPEndPoint(ipin, portin);

            //string str = string.Empty;
            string positionValue = string.Empty;   // 전송 명령 순서대로 박스에 넣기
            positionValue = textBox3_position.Text;
            string startvelocityValue = string.Empty;
            startvelocityValue = textBox4.Text;
            string  endvelocityValue= string.Empty;
            endvelocityValue = textBox5.Text;
            string accelerationValue = string.Empty;
            accelerationValue = textBox6.Text;
            string decelerationValue = string.Empty;
            decelerationValue = textBox7.Text;
            string jerkValue = string.Empty;
            jerkValue = textBox8.Text;
            string axisValue = string.Empty;
            axisValue = textBox3.Text;

            // 0은 x축, 1은 y축
            //string sendMsg = String.Format("U[0, 5] ={0}, U[0, 6] ={1}, U[0, 7] ={2}, U[0, 8] ={3}, U[0, 9] ={4}, U[0, 10] ={5}, M[0] = 7", positionValue, startvelocityValue,endvelocityValue, accelerationValue, decelerationValue, jerkValue);
            string sendMsg = String.Format("U[{6}, 5] ={0}, U[0, 6] ={1}, U[0, 7] ={2}, U[0, 8] ={3}, U[0, 9] ={4}, U[0, 10] ={5}, M[0] = 7", positionValue, startvelocityValue, endvelocityValue, accelerationValue, decelerationValue, jerkValue, axisValue);
            //str = textBox1.Text;
            byte[] sendBuffer = Encoding.UTF8.GetBytes(sendMsg);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            //textBox1.Text = Encoding.UTF8.GetString(sendBuffer);
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            //textBox2.Text = Encoding.UTF8.GetString(receiveBuffer); // 받아온 receiveBuffer를 textbox에 넣기
        }

        private void label3_Click(object sender, EventArgs e)
        {
            // 연결할 주소입력 label
        }

        private void label4_Click(object sender, EventArgs e)
        {
            // 포트번호 입력 label
        }

        private void port_TextChanged(object sender, EventArgs e)
        {
            // port번호 입력하는 textbox
        }

        private void before_Click(object sender, EventArgs e)
        {
            // 연결전 label
        }

        private void label2_Click(object sender, EventArgs e)
        {
            // 받은 메세지 label
        }

        private void button_getCurrentPos_Click(object sender, EventArgs e)  // 현재위치 버튼을 누르면 위치가 계속 업데이트 되도록했지만 timer를 넣어서 자동으로 업데이트되도록 했다.
        {
            string str = string.Empty;
            string axisValue = string.Empty;
            axisValue = textBox3.Text;
            str = String.Format("U[{0},3]=0,M[{0}]=5,U[{0},4]",axisValue);
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            //textBox2.Text = Encoding.UTF8.GetString(receiveBuffer); // 받아온 receiveBuffer를 textbox에 넣기
            string receivedMsg = Encoding.UTF8.GetString(receiveBuffer);  // 받아온 데이터를 문자열 a에 저장
            //string b = null;  // 문자열 b를 null로 선언
            //for (int i = 16; i < 50; i++)  // a에 있는 문자열에서 위치를 나타내는 부분이 16번째 문자열 부터이다. 50은 그냥 어디가 끝인지몰라서 임의의 숫자 적음
            //{
            //    b += Convert.ToString(receivedMsg[i]);  // 빈 문자열 b에 a의 문자열을 하나씩 넣는다.
            //}
            //textBox2.Text = b;  // 수신 명령 텍스트 박스에 위치값만 적힌다.

            //string [] splittedMsg = receivedMsg.Split(new char[] { ':',',', '[', ']', '=' });  // split : 문자열 나누기
            string[] splittedMsg = receivedMsg.Split(new char[] { ':', ',', ' ' });
            //textBox2.Text = Convert.ToString(splittedMsg.Length);  // 문자열을 나눴을때 나오는 개수 세기
            textBox2.Text = splittedMsg[6];  // 문자열 7개중 마지막 번지인 6을 출력하면 위치값만 나온다.

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            string str = string.Empty;
            string axisValue = string.Empty;
            axisValue = textBox3.Text;
            str = String.Format("U[{0},3]=0,M[{0}]=5,U[{0},4]", axisValue);
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            //textBox2.Text = Encoding.UTF8.GetString(receiveBuffer);
            string receivedMsg = Encoding.UTF8.GetString(receiveBuffer);
            //string b = null;
            //for (int i = 16; i < 50; i++)
            //{
            //    b += Convert.ToString(a[i]);
            //}
            //textBox2.Text = b;

            //string[] splittedMsg = receivedMsg.Split(new char[] { ':',',', '[', ']', '=' });  // split : 문자열 나누기
            string[] splittedMsg = receivedMsg.Split(new char[] { ':', ',', ' ' });
            //textBox2.Text = Convert.ToString(splittedMsg.Length);
            textBox2.Text = splittedMsg[6];
        }

        private void textBox4_TextChanged(object sender, EventArgs e)
        {
            string startvelocityValue = string.Empty;
            startvelocityValue = textBox4.Text;
        }

        private void textBox5_TextChanged(object sender, EventArgs e)
        {
            string endvelocityValue = string.Empty;
            endvelocityValue = textBox5.Text;
        }

        private void textBox6_TextChanged(object sender, EventArgs e)
        {
            string accelerationValue = string.Empty;
            accelerationValue = textBox6.Text;
        }

        private void textBox7_TextChanged(object sender, EventArgs e)
        {
            string decelerationValue = string.Empty;
            decelerationValue = textBox7.Text;
        }

        private void textBox8_TextChanged(object sender, EventArgs e)
        {
            string jerkValue = string.Empty;
            jerkValue = textBox8.Text;
        }

        private void label11_Click(object sender, EventArgs e)
        {

        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {
            string axisValue = string.Empty;
            axisValue = textBox3.Text;
        }
    }
}

 

위 코드를 모션보드에 연결을 해봤을때는 잘 됩니다. x축(0)일때, y축(1)일때 입력받고 위치를 잘 이동하는 것을 아래에서 확인할수있습니다.

 

[x축일 때]                                                                                             [y축일 때]

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace WindowsFormsApp6
{
    public partial class Form1 : Form
    {

        Socket udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);  // 선언, 초기화
        //EndPoint localEP = new IPEndPoint(IPAddress.Any,0);
        EndPoint _remoteEP;
        //string positionValue;


        public Form1()
        {
            InitializeComponent();
            //udpSocket.Bind(localEP);  // 실행
            //this.ActiveControl = textbox_ip; // 폼을 시작하자마자 ip 텍스트박스에 커서가 가게하기

            // 조그명령으로 앱으로 이동
            // 사각형 그리기
            // x축 
            // 뒤 마지막 : 1110297
            // 앞 마지막 : 952240
            // y축
            // 오른쪽 마지막 : 51339
            // 왼쪽 마지막 : -192068
            //ip 5번 천천히, 빠르게
            this.button_send.Enabled = false;  // 폼을 열었을때 버튼 누르지못하게 하기
            this.button_getCurrentPos.Enabled = false;
            this.button_axisselect.Enabled = false;
            this.textbox_ip.Text = "192.168.10.7"; // 폼을 열었을때 텍스트 박스에 값이 들어가있도록 하기
            this.textbox_port.Text = "4000";
            this.textBox4.Text = "100";
            this.textBox5.Text = "15000";
            this.textBox6.Text = "1500000";
            this.textBox7.Text = "1500000";
            this.textBox8.Text = "100";  // jerk : 홱 움직이다.
            //string positionValue = string.Empty;
            //positionValue = textBox1.Text;
            //this.textBox1.Text="U[0, 5] = " +  positionValue + ", U[0, 6] = 100, U[0, 7] = 15000, U[0, 8] = 1500000, U[0, 9] = 1500000, U[0, 10] = 100, M[0] = 7";
        }

        private void label1_Click(object sender, EventArgs e)
        {
            // 전송할 메세지 label
        }

        private void ip_TextChanged(object sender, EventArgs e)
        {
            // ip 입력하는 textbox
        }

        private void connect_Click(object sender, EventArgs e)
        {
            // 연결하기 버튼
            string ipaddress = string.Empty;
            ipaddress = textbox_ip.Text;  // ip 번호 입력
            IPAddress ipin = IPAddress.Parse(ipaddress);  // 문자열 ip주소를 숫자로 변환하기

            string portn = string.Empty;
            portn = textbox_port.Text;  // 포트 번호 입력
            int portin = Convert.ToInt32(portn);  // 문자열 포트 번호를 int형으로 변환하기

            string axisValue = string.Empty;
            axisValue = textBox1.Text;


            if ((Convert.ToString(ipin) == "192.168.10.7") && (portin == 4000)) // ip주소와 port번호가 원하는 것과 일치하면
            {
                before.Text = "유효한 IP 와 Port Number";
                this.button_axisselect.Enabled = true;
                
                //EndPoint localEP = new IPEndPoint(IPAddress.Any, portin);
                _remoteEP = new IPEndPoint(ipin, portin);  // ip와 port번호가 유효하면 remoteEP에 저장한다. if문밖에 remoteEP가 있으면 유효하지 않은 정보들을 다 저장하고 마지막으로 옳은것을 저장하게 된다.
            }
            else
            {
                before.Text = "IP 와 Port Number 확인해 주세요";
            }
            

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 만든 폼 띄우기
        }


        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            // 받은 메세지 입력되는 textbox
        }



        private void textBox1_TextChanged_1(object sender, EventArgs e)
        {
            // 전송할 메세지 입력하는 textbox
        }

        private void textBox3_position_TextChanged(object sender, EventArgs e)
        {
            string positionValue = string.Empty;
            positionValue = textBox3_position.Text;
        }

        private void button_send_Click(object sender, EventArgs e)
        {
            // 메세지전송
            //string ipaddress = string.Empty;
            //ipaddress = ip.Text;  // ip 번호 입력
            //IPAddress ipin = IPAddress.Parse(ipaddress);  // 문자열 ip주소를 숫자로 변환하기

            //string portn = string.Empty;
            //portn = port.Text;  // 포트 번호 입력
            //int portin = Convert.ToInt32(portn);  // 문자열 포트 번호를 int형으로 변환하기

            //EndPoint localEP = new IPEndPoint(IPAddress.Any, portin);
            //EndPoint remoteEP = new IPEndPoint(ipin, portin);

            //string str = string.Empty;
            string positionValue = string.Empty;   // 전송 명령 순서대로 박스에 넣기
            positionValue = textBox3_position.Text;
            string startvelocityValue = string.Empty;
            startvelocityValue = textBox4.Text;
            string endvelocityValue = string.Empty;
            endvelocityValue = textBox5.Text;
            string accelerationValue = string.Empty;
            accelerationValue = textBox6.Text;
            string decelerationValue = string.Empty;
            decelerationValue = textBox7.Text;
            string jerkValue = string.Empty;
            jerkValue = textBox8.Text;
            string axisValue = string.Empty;
            axisValue = textBox1.Text;

            // 0은 x축, 1은 y축
            //string sendMsg = String.Format("U[0, 5] ={0}, U[0, 6] ={1}, U[0, 7] ={2}, U[0, 8] ={3}, U[0, 9] ={4}, U[0, 10] ={5}, M[0] = 7", positionValue, startvelocityValue,endvelocityValue, accelerationValue, decelerationValue, jerkValue);
            //string sendMsg = String.Format("U[{0}, 5] ={1}, U[{0}, 6] ={2}, U[{0}, 7] ={3}, U[{0}, 8] ={4}, U[{0}, 9] ={5}, U[{0}, 10] ={6}, M[{0}] = 7", axisValue, positionValue, startvelocityValue, endvelocityValue, accelerationValue, decelerationValue, jerkValue);
            string sendMsg = String.Format("U[{6}, 5] ={0}, U[{6}, 6] ={1}, U[{6}, 7] ={2}, U[{6}, 8] ={3}, U[{6}, 9] ={4}, U[{6}, 10] ={5}, M[{6}] = 7", positionValue, startvelocityValue, endvelocityValue, accelerationValue, decelerationValue, jerkValue, axisValue);
            //string sendMsg = String.Format("U[1, 5] ={0}, U[1, 6] ={1}, U[1, 7] ={2}, U[1, 8] ={3}, U[1, 9] ={4}, U[1, 10] ={5}, M[1] = 7", positionValue, startvelocityValue, endvelocityValue, accelerationValue, decelerationValue, jerkValue);
            //str = textBox1.Text;
            byte[] sendBuffer = Encoding.UTF8.GetBytes(sendMsg);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            //textBox1.Text = Encoding.UTF8.GetString(sendBuffer);
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            //textBox2.Text = Encoding.UTF8.GetString(receiveBuffer); // 받아온 receiveBuffer를 textbox에 넣기
        }

        private void label3_Click(object sender, EventArgs e)
        {
            // 연결할 주소입력 label
        }

        private void label4_Click(object sender, EventArgs e)
        {
            // 포트번호 입력 label
        }

        private void port_TextChanged(object sender, EventArgs e)
        {
            // port번호 입력하는 textbox
        }

        private void before_Click(object sender, EventArgs e)
        {
            // 연결전 label
        }

        private void label2_Click(object sender, EventArgs e)
        {
            // 받은 메세지 label
        }

        private void button_getCurrentPos_Click(object sender, EventArgs e)  // 현재위치 버튼을 누르면 위치가 계속 업데이트 되도록했지만 timer를 넣어서 자동으로 업데이트되도록 했다.
        {
            string str = string.Empty;
            string axisValue = string.Empty;
            axisValue = textBox1.Text;
            str = String.Format("U[{0},3]=0,M[{0}]=5,U[{0},4]", axisValue);
            //str = "U[0,3]=0,M[0]=5,U[0,4]";
            //str = "U[1,3]=0,M[1]=5,U[1,4]";
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            //textBox2.Text = Encoding.UTF8.GetString(receiveBuffer); // 받아온 receiveBuffer를 textbox에 넣기
            string receivedMsg = Encoding.UTF8.GetString(receiveBuffer);  // 받아온 데이터를 문자열 a에 저장
            //string b = null;  // 문자열 b를 null로 선언
            //for (int i = 16; i < 50; i++)  // a에 있는 문자열에서 위치를 나타내는 부분이 16번째 문자열 부터이다. 50은 그냥 어디가 끝인지몰라서 임의의 숫자 적음
            //{
            //    b += Convert.ToString(receivedMsg[i]);  // 빈 문자열 b에 a의 문자열을 하나씩 넣는다.
            //}
            //textBox2.Text = b;  // 수신 명령 텍스트 박스에 위치값만 적힌다.

            //string [] splittedMsg = receivedMsg.Split(new char[] { ':',',', '[', ']', '=' });  // split : 문자열 나누기
            string[] splittedMsg = receivedMsg.Split(new char[] { ':', ',', ' ' });
            //textBox2.Text = Convert.ToString(splittedMsg.Length);  // 문자열을 나눴을때 나오는 개수 세기
            textBox2.Text = splittedMsg[6];  // 문자열 7개중 마지막 번지인 6을 출력하면 위치값만 나온다.

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            string str = string.Empty;
            string axisValue = string.Empty;
            axisValue = textBox1.Text;
            str = String.Format("U[{0},3]=0,M[{0}]=5,U[{0},4]", axisValue);
            //str = "U[0,3]=0,M[0]=5,U[0,4]";
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            //textBox2.Text = Encoding.UTF8.GetString(receiveBuffer);
            string receivedMsg = Encoding.UTF8.GetString(receiveBuffer);
            //string b = null;
            //for (int i = 16; i < 50; i++)
            //{
            //    b += Convert.ToString(a[i]);
            //}
            //textBox2.Text = b;

            //string[] splittedMsg = receivedMsg.Split(new char[] { ':',',', '[', ']', '=' });  // split : 문자열 나누기
            string[] splittedMsg = receivedMsg.Split(new char[] { ':', ',', ' ' });
            //textBox2.Text = Convert.ToString(splittedMsg.Length);
            textBox2.Text = splittedMsg[6];
        }

        private void textBox4_TextChanged(object sender, EventArgs e)
        {
            string startvelocityValue = string.Empty;
            startvelocityValue = textBox4.Text;
        }

        private void textBox5_TextChanged(object sender, EventArgs e)
        {
            string endvelocityValue = string.Empty;
            endvelocityValue = textBox5.Text;
        }

        private void textBox6_TextChanged(object sender, EventArgs e)
        {
            string accelerationValue = string.Empty;
            accelerationValue = textBox6.Text;
        }

        private void textBox7_TextChanged(object sender, EventArgs e)
        {
            string decelerationValue = string.Empty;
            decelerationValue = textBox7.Text;
        }

        private void textBox8_TextChanged(object sender, EventArgs e)
        {
            string jerkValue = string.Empty;
            jerkValue = textBox8.Text;
        }

        private void label11_Click(object sender, EventArgs e)
        {

        }


        private void label11_Click_1(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            string axisValue = string.Empty;
            axisValue = textBox1.Text;
        }

        private void button_axisselect_Click(object sender, EventArgs e)
        {
            string axisValue = string.Empty;
            axisValue = textBox1.Text;
            if (axisValue == "1" || axisValue == "0")
            {
                this.button_send.Enabled = true;   // ip주소가 유효하면 위치전송 버튼 on
                this.button_getCurrentPos.Enabled = true;  // 같이 현재위치보기 버튼 on 
                this.timer1.Start();  // 유효한 ip가 입력되면 타이머 시작
            }
        }
    }
}

 

그런데 모터를 연결한 모션보드와 연결했을때는 에러가 떠서 모터가 작동을 하지않습니다...

아래 에러는 x축방향으로 모터를 움직이라고 명령했을때 입니다.

 

 

24번에러는 위치와 관련된 에러라고합니다. 엔코더에 얼마를 움직이라고 명령이 들어갔는데 서보모터가 그 명령만큼 움직이지 못했을때 발생하는 에러로 잘 발생하지않는 에러라고합니다. 

그런데 그냥 모터를 껐다가 키니까 다시 잘 됩니다.

 

x축,y축 선택한 후 그 축으로 움직이게 하는 것은 성공했습니다.

 

x축 

 

y축

 

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;

namespace WindowsFormsApp6
{
    public partial class Form1 : Form
    {

        Socket udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);  // 선언, 초기화
        //EndPoint localEP = new IPEndPoint(IPAddress.Any,0);
        EndPoint _remoteEP;
        //string positionValue;


        public Form1()
        {
            InitializeComponent();
            //udpSocket.Bind(localEP);  // 실행
            //this.ActiveControl = textbox_ip; // 폼을 시작하자마자 ip 텍스트박스에 커서가 가게하기

            // 조그명령으로 앱으로 이동
            // 사각형 그리기
            // x축 
            // 뒤 마지막 : 1110297
            // 앞 마지막 : 952240
            // y축
            // 오른쪽 마지막 : 51339
            // 왼쪽 마지막 : -192068
            //ip 5번 천천히, 빠르게
            this.button_send.Enabled = false;  // 폼을 열었을때 버튼 누르지못하게 하기
            this.button_getCurrentPos.Enabled = false;
            this.button_axisselect.Enabled = false;
            this.textbox_ip.Text = "192.168.10.5"; // 폼을 열었을때 텍스트 박스에 값이 들어가있도록 하기
            this.textbox_port.Text = "4000";
            this.textBox4.Text = "100";
            this.textBox5.Text = "50000";
            this.textBox6.Text = "100000";
            this.textBox7.Text = "100000";
            this.textBox8.Text = "100";  // jerk : 홱 움직이다.
            //string positionValue = string.Empty;
            //positionValue = textBox1.Text;
            //this.textBox1.Text="U[0, 5] = " +  positionValue + ", U[0, 6] = 100, U[0, 7] = 15000, U[0, 8] = 1500000, U[0, 9] = 1500000, U[0, 10] = 100, M[0] = 7";
        }

        private void label1_Click(object sender, EventArgs e)
        {
            // 전송할 메세지 label
        }

        private void ip_TextChanged(object sender, EventArgs e)
        {
            // ip 입력하는 textbox
        }

        private void connect_Click(object sender, EventArgs e)
        {
            // 연결하기 버튼
            string ipaddress = string.Empty;
            ipaddress = textbox_ip.Text;  // ip 번호 입력
            IPAddress ipin = IPAddress.Parse(ipaddress);  // 문자열 ip주소를 숫자로 변환하기

            string portn = string.Empty;
            portn = textbox_port.Text;  // 포트 번호 입력
            int portin = Convert.ToInt32(portn);  // 문자열 포트 번호를 int형으로 변환하기

            string axisValue = string.Empty;
            axisValue = textBox1.Text;


            if ((Convert.ToString(ipin) == "192.168.10.5") && (portin == 4000)) // ip주소와 port번호가 원하는 것과 일치하면
            {
                before.Text = "유효한 IP 와 Port Number";
                this.button_axisselect.Enabled = true;
                
                //EndPoint localEP = new IPEndPoint(IPAddress.Any, portin);
                _remoteEP = new IPEndPoint(ipin, portin);  // ip와 port번호가 유효하면 remoteEP에 저장한다. if문밖에 remoteEP가 있으면 유효하지 않은 정보들을 다 저장하고 마지막으로 옳은것을 저장하게 된다.
            }
            else
            {
                before.Text = "IP 와 Port Number 확인해 주세요";
            }
            

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 만든 폼 띄우기
        }


        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            // 받은 메세지 입력되는 textbox
        }



        private void textBox1_TextChanged_1(object sender, EventArgs e)
        {
            // 전송할 메세지 입력하는 textbox
        }

        private void textBox3_position_TextChanged(object sender, EventArgs e)
        {
            string positionValue = string.Empty;
            positionValue = textBox3_position.Text;
        }

        private void button_send_Click(object sender, EventArgs e)
        {
            // 메세지전송
            //string ipaddress = string.Empty;
            //ipaddress = ip.Text;  // ip 번호 입력
            //IPAddress ipin = IPAddress.Parse(ipaddress);  // 문자열 ip주소를 숫자로 변환하기

            //string portn = string.Empty;
            //portn = port.Text;  // 포트 번호 입력
            //int portin = Convert.ToInt32(portn);  // 문자열 포트 번호를 int형으로 변환하기

            //EndPoint localEP = new IPEndPoint(IPAddress.Any, portin);
            //EndPoint remoteEP = new IPEndPoint(ipin, portin);

            //string str = string.Empty;
            string positionValue = string.Empty;   // 전송 명령 순서대로 박스에 넣기
            positionValue = textBox3_position.Text;
            string startvelocityValue = string.Empty;
            startvelocityValue = textBox4.Text;
            string endvelocityValue = string.Empty;
            endvelocityValue = textBox5.Text;
            string accelerationValue = string.Empty;
            accelerationValue = textBox6.Text;
            string decelerationValue = string.Empty;
            decelerationValue = textBox7.Text;
            string jerkValue = string.Empty;
            jerkValue = textBox8.Text;
            string axisValue = string.Empty;
            axisValue = textBox1.Text;

            // 0은 x축, 1은 y축
            //string sendMsg = String.Format("U[0, 5] ={0}, U[0, 6] ={1}, U[0, 7] ={2}, U[0, 8] ={3}, U[0, 9] ={4}, U[0, 10] ={5}, M[0] = 7", positionValue, startvelocityValue,endvelocityValue, accelerationValue, decelerationValue, jerkValue);
            string sendMsg = String.Format("U[{0}, 5] ={1}, U[{0}, 6] ={2}, U[{0}, 7] ={3}, U[{0}, 8] ={4}, U[{0}, 9] ={5}, U[{0}, 10] ={6}, M[{0}] = 7", axisValue, positionValue, startvelocityValue, endvelocityValue, accelerationValue, decelerationValue, jerkValue);
            //string sendMsg = String.Format("U[{6}, 5] ={0}, U[{6}, 6] ={1}, U[{6}, 7] ={2}, U[{6}, 8] ={3}, U[{6}, 9] ={4}, U[{6}, 10] ={5}, M[{6}] = 7", positionValue, startvelocityValue, endvelocityValue, accelerationValue, decelerationValue, jerkValue, axisValue);
            //string sendMsg = String.Format("U[1, 5] ={0}, U[1, 6] ={1}, U[1, 7] ={2}, U[1, 8] ={3}, U[1, 9] ={4}, U[1, 10] ={5}, M[1] = 7", positionValue, startvelocityValue, endvelocityValue, accelerationValue, decelerationValue, jerkValue);
            //str = textBox1.Text;
            byte[] sendBuffer = Encoding.UTF8.GetBytes(sendMsg);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            //textBox3_position.Text = Encoding.UTF8.GetString(sendBuffer);
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            //textBox2.Text = Encoding.UTF8.GetString(receiveBuffer); // 받아온 receiveBuffer를 textbox에 넣기
        }

        private void label3_Click(object sender, EventArgs e)
        {
            // 연결할 주소입력 label
        }

        private void label4_Click(object sender, EventArgs e)
        {
            // 포트번호 입력 label
        }

        private void port_TextChanged(object sender, EventArgs e)
        {
            // port번호 입력하는 textbox
        }

        private void before_Click(object sender, EventArgs e)
        {
            // 연결전 label
        }

        private void label2_Click(object sender, EventArgs e)
        {
            // 받은 메세지 label
        }

        private void button_getCurrentPos_Click(object sender, EventArgs e)  // 현재위치 버튼을 누르면 위치가 계속 업데이트 되도록했지만 timer를 넣어서 자동으로 업데이트되도록 했다.
        {
            string str = string.Empty;
            string axisValue = string.Empty;
            axisValue = textBox1.Text;
            str = String.Format("U[{0},3]=0,M[{0}]=5,U[{0},4]", axisValue);
            //str = "U[0,3]=0,M[0]=5,U[0,4]";
            //str = "U[1,3]=0,M[1]=5,U[1,4]";
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            //textBox2.Text = Encoding.UTF8.GetString(receiveBuffer); // 받아온 receiveBuffer를 textbox에 넣기
            string receivedMsg = Encoding.UTF8.GetString(receiveBuffer);  // 받아온 데이터를 문자열 a에 저장
            //textBox2.Text = Convert.ToString(receivedMsg.Length);
            //string b = null;  // 문자열 b를 null로 선언
            //for (int i = 16; i < 50; i++)  // a에 있는 문자열에서 위치를 나타내는 부분이 16번째 문자열 부터이다. 50은 그냥 어디가 끝인지몰라서 임의의 숫자 적음
            //{
            //    b += Convert.ToString(receivedMsg[i]);  // 빈 문자열 b에 a의 문자열을 하나씩 넣는다.
            //}
            //textBox2.Text = b;  // 수신 명령 텍스트 박스에 위치값만 적힌다.

            //string [] splittedMsg = receivedMsg.Split(new char[] { ':',',', '[', ']', '=' });  // split : 문자열 나누기
            string[] splittedMsg = receivedMsg.Split(new char[] { ':', ',', ' ' });
            //textBox2.Text = Convert.ToString(splittedMsg.Length);  // 문자열을 나눴을때 나오는 개수 세기
            textBox2.Text = splittedMsg[6];  // 문자열 7개중 마지막 번지인 6을 출력하면 위치값만 나온다.

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            string str = string.Empty;
            string axisValue = string.Empty;
            axisValue = textBox1.Text;
            str = String.Format("U[{0},3]=0,M[{0}]=5,U[{0},4]", axisValue);
            //str = "U[0,3]=0,M[0]=5,U[0,4]";
            //str = "U[1,3]=0,M[1]=5,U[1,4]";
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            //textBox2.Text = Encoding.UTF8.GetString(receiveBuffer);
            string receivedMsg = Encoding.UTF8.GetString(receiveBuffer);
            //textBox2.Text = Convert.ToString(receivedMsg.Length);
            //string b = null;
            //for (int i = 16; i < 50; i++)
            //{
            //    b += Convert.ToString(a[i]);
            //}
            //textBox2.Text = b;

            //string[] splittedMsg = receivedMsg.Split(new char[] { ':',',', '[', ']', '=' });  // split : 문자열 나누기
            string[] splittedMsg = receivedMsg.Split(new char[] { ':', ',', ' ' });
            //textBox2.Text = Convert.ToString(splittedMsg.Length);
            textBox2.Text = splittedMsg[6];
        }

        private void textBox4_TextChanged(object sender, EventArgs e)
        {
            string startvelocityValue = string.Empty;
            startvelocityValue = textBox4.Text;
        }

        private void textBox5_TextChanged(object sender, EventArgs e)
        {
            string endvelocityValue = string.Empty;
            endvelocityValue = textBox5.Text;
        }

        private void textBox6_TextChanged(object sender, EventArgs e)
        {
            string accelerationValue = string.Empty;
            accelerationValue = textBox6.Text;
        }

        private void textBox7_TextChanged(object sender, EventArgs e)
        {
            string decelerationValue = string.Empty;
            decelerationValue = textBox7.Text;
        }

        private void textBox8_TextChanged(object sender, EventArgs e)
        {
            string jerkValue = string.Empty;
            jerkValue = textBox8.Text;
        }

        private void label11_Click_1(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            string axisValue = string.Empty;
            axisValue = textBox1.Text;
        }

        private void button_axisselect_Click(object sender, EventArgs e)
        {
            string axisValue = string.Empty;
            axisValue = textBox1.Text;
            if (axisValue == "1" || axisValue == "0")
            {
                this.button_send.Enabled = true;   // ip주소가 유효하면 위치전송 버튼 on
                this.button_getCurrentPos.Enabled = true;  // 같이 현재위치보기 버튼 on 
                this.timer1.Start();  // 유효한 ip가 입력되면 타이머 시작
                label12.Text = " ";
            }
            else
            {
                label12.Text = "축 번호를 확인해 주세요";
            }
            }

        private void label12_Click(object sender, EventArgs e)
        {

        }
    }
}

 

축을 바꾸려고하면 계속 모터가 꺼져서 프로그램을 다시 시작했어야했는데 알고보니 텍스트박스를 비우면 null값이 들어가서 아무값도 받지못해서 꺼지는 거였습니다. 그래서 backspace로 지우고 값을 넣는것이 아니고 드래그로 값을 바로 바꾸니까 됐습니다.

 

일단 제가 값을 바꿔가면서 사각형으로 움직이도록 해보았습니다.

 

 

 

시퀀스로 사각형을 기계가 알아서 그리도록 해보겠습니다.

 

 

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace WindowsFormsApp6
{
    public partial class Form1 : Form
    {

        Socket udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);  // 선언, 초기화
        //EndPoint localEP = new IPEndPoint(IPAddress.Any,0);
        EndPoint _remoteEP;
        //string positionValue;
        int a = 1;


        public Form1()
        {
            InitializeComponent();
            //udpSocket.Bind(localEP);  // 실행
            //this.ActiveControl = textbox_ip; // 폼을 시작하자마자 ip 텍스트박스에 커서가 가게하기

            // 조그명령으로 앱으로 이동
            // 사각형 그리기
            // x축 
            // 뒤 마지막 : 1110297
            // 앞 마지막 : 952240
            // y축
            // 오른쪽 마지막 : 51339
            // 왼쪽 마지막 : -192068
            // 사각형 그리기
            // y: -37433
            // x: -147411
            // y: 207197
            // x: 11826
            //ip 5번 천천히, 빠르게
            //this.button_send.Enabled = false;   // 폼을 열었을때 버튼 누르지못하게 하기
            //this.button_getCurrentPos.Enabled = false;
            //this.button_axisselect.Enabled = false;
            this.textbox_ip.Text = "192.168.10.5";  // 폼을 열었을때 텍스트 박스에 값이 들어가있도록 하기
            this.textbox_port.Text = "4000";
            this.textBox4.Text = "100";
            this.textBox5.Text = "50000";
            this.textBox6.Text = "100000";
            this.textBox7.Text = "100000";
            this.textBox8.Text = "100";  // jerk : 홱 움직이다.
        }

        private void label1_Click(object sender, EventArgs e)
        {
            // 전송할 메세지 label
        }

        private void ip_TextChanged(object sender, EventArgs e)
        {
            // ip 입력하는 textbox
        }

        private void connect_Click(object sender, EventArgs e)
        {
            // 연결하기 버튼
            string ipaddress = string.Empty;
            ipaddress = textbox_ip.Text;  // ip 번호 입력
            IPAddress ipin = IPAddress.Parse(ipaddress);  // 문자열 ip주소를 숫자로 변환하기

            string portn = string.Empty;
            portn = textbox_port.Text;  // 포트 번호 입력
            int portin = Convert.ToInt32(portn);  // 문자열 포트 번호를 int형으로 변환하기

            string axisValue = string.Empty;
            axisValue = textBox1.Text;


            if ((Convert.ToString(ipin) == "192.168.10.5") && (portin == 4000)) // ip주소와 port번호가 원하는 것과 일치하면
            {
                before.Text = "유효한 IP 와 Port Number";
                //this.button_axisselect.Enabled = true;
                _remoteEP = new IPEndPoint(ipin, portin);  // ip와 port번호가 유효하면 remoteEP에 저장한다. if문밖에 remoteEP가 있으면 유효하지 않은 정보들을 다 저장하고 마지막으로 옳은것을 저장하게 된다.
            }
            else
            {
                before.Text = "IP 와 Port Number 확인해 주세요";
            }
            

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 만든 폼 띄우기
        }


        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            // 받은 메세지 입력되는 textbox
        }



        private void textBox1_TextChanged_1(object sender, EventArgs e)
        {
            // 전송할 메세지 입력하는 textbox
        }

        private void textBox3_position_TextChanged(object sender, EventArgs e)
        {
            string positionValue = string.Empty;
            positionValue = textBox3_position.Text;
        }

        private void button_send_Click(object sender, EventArgs e)
        {
            // 메세지전송
            string positionValue = string.Empty;   // 전송 명령 순서대로 박스에 넣기
            positionValue = textBox3_position.Text;
            string startvelocityValue = string.Empty;
            startvelocityValue = textBox4.Text;
            string endvelocityValue = string.Empty;
            endvelocityValue = textBox5.Text;
            string accelerationValue = string.Empty;
            accelerationValue = textBox6.Text;
            string decelerationValue = string.Empty;
            decelerationValue = textBox7.Text;
            string jerkValue = string.Empty;
            jerkValue = textBox8.Text;
            string axisValue = string.Empty;
            axisValue = textBox1.Text;

            // 0은 x축, 1은 y축
            string sendMsg = String.Format("U[{0}, 5] ={1}, U[{0}, 6] ={2}, U[{0}, 7] ={3}, U[{0}, 8] ={4}, U[{0}, 9] ={5}, U[{0}, 10] ={6}, M[{0}] = 7", axisValue, positionValue, startvelocityValue, endvelocityValue, accelerationValue, decelerationValue, jerkValue);
            byte[] sendBuffer = Encoding.UTF8.GetBytes(sendMsg);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기

        }

        private void label3_Click(object sender, EventArgs e)
        {
            // 연결할 주소입력 label
        }

        private void label4_Click(object sender, EventArgs e)
        {
            // 포트번호 입력 label
        }

        private void port_TextChanged(object sender, EventArgs e)
        {
            // port번호 입력하는 textbox
        }

        private void before_Click(object sender, EventArgs e)
        {
            // 연결전 label
        }

        private void label2_Click(object sender, EventArgs e)
        {
            // 받은 메세지 label
        }

        private void button_getCurrentPos_Click(object sender, EventArgs e)  // 현재위치 버튼을 누르면 위치가 계속 업데이트 되도록했지만 timer를 넣어서 자동으로 업데이트되도록 했다.
        {
            string str = string.Empty;
            string axisValue = string.Empty;
            axisValue = textBox1.Text;
            str = String.Format("U[{0},3]=0,M[{0}]=5,U[{0},4]", axisValue);
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            string receivedMsg = Encoding.UTF8.GetString(receiveBuffer);  // 받아온 데이터를 문자열 a에 저장
            string[] splittedMsg = receivedMsg.Split(new char[] { ':', ',', ' ' });
            textBox2.Text = splittedMsg[6];  // 문자열 7개중 마지막 번지인 6을 출력하면 위치값만 나온다.

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            string str = string.Empty;
            string axisValue = string.Empty;
            axisValue = textBox1.Text;
            str = String.Format("U[{0},3]=0,M[{0}]=5,U[{0},4]", axisValue);
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            string receivedMsg = Encoding.UTF8.GetString(receiveBuffer);
            string[] splittedMsg = receivedMsg.Split(new char[] { ':', ',', ' ' });
            textBox2.Text = splittedMsg[6];
        }

        private void textBox4_TextChanged(object sender, EventArgs e)
        {
            string startvelocityValue = string.Empty;
            startvelocityValue = textBox4.Text;
        }

        private void textBox5_TextChanged(object sender, EventArgs e)
        {
            string endvelocityValue = string.Empty;
            endvelocityValue = textBox5.Text;
        }

        private void textBox6_TextChanged(object sender, EventArgs e)
        {
            string accelerationValue = string.Empty;
            accelerationValue = textBox6.Text;
        }

        private void textBox7_TextChanged(object sender, EventArgs e)
        {
            string decelerationValue = string.Empty;
            decelerationValue = textBox7.Text;
        }

        private void textBox8_TextChanged(object sender, EventArgs e)
        {
            string jerkValue = string.Empty;
            jerkValue = textBox8.Text;
        }

        private void label11_Click_1(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            string axisValue = string.Empty;
            axisValue = textBox1.Text;
        }

        private void button_axisselect_Click(object sender, EventArgs e)
        {
            string axisValue = string.Empty;
            axisValue = textBox1.Text;
            if (axisValue == "1" || axisValue == "0")
            {
                //this.button_send.Enabled = true;   // ip주소가 유효하면 위치전송 버튼 on
                //this.button_getCurrentPos.Enabled = true;  // 같이 현재위치보기 버튼 on 
                this.timer1.Start();  // 유효한 ip가 입력되면 타이머 시작
                label12.Text = " ";
            }
            else
            {
                label12.Text = "축 번호를 확인해 주세요";
            }
            }

        private void label12_Click(object sender, EventArgs e)
        {

        }
        
        private void rectangle_draw(string axisValue,string positionValue,int sleep)
        {
            string sendMsg = String.Format("U[{0}, 5] ={1}, U[{0}, 6] ={2}, U[{0}, 7] ={3}, U[{0}, 8] ={4}, U[{0}, 9] ={5}, U[{0}, 10] ={6}, M[{0}] = 7", axisValue, positionValue, 100, 50000, 100000, 100000, 100);
            byte[] sendBuffer = Encoding.UTF8.GetBytes(sendMsg);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            Thread.Sleep(sleep);
        }

        private void button_rectangle_Click(object sender, EventArgs e)
        {
                while(true)
                {
                    rectangle_draw("1", "-37433", 5000);
                    rectangle_draw("0", "-147411", 3500);
                    rectangle_draw("1", "206365", 5000);
                    rectangle_draw("0", "373081", 3500);
                }
        }

    }
}

 

위 코드에서 함수안에 문장이없는 함수를 지우려면 함수를 우클릭한후 모든참조찾기을 눌러 eventhandler를 지운후 해당하는 함수를 지우면 됩니다. 지운후 폼을 보고 오류가 없는지 확인을 꼭 해보세요.

 

그런데 무한루프로 사각형을 그리도록하였는데 루프를 탈출하는 방법을 모르겠습니다. for문으로 3번 그리라고 명령을 해봤을때 3번을 그린후에야 다른 버튼이 활성화되는 것을 확인하였습니다. 그럼 무한루프가 끝나기전까지 끝낼수있는 버튼이 활성화되지않는데 어떻게 해야 버튼을 활성화 시켜서 무한루프를 탈출할수있을까요?

 

알고보니 Thread.Sleep을 하면 버튼이 활성화되지않는거였습니다. sleep을 이용하지않고 함수에 delay를 주면서 버튼이 활성화되는 방법이 뭐가있을까요?

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace WindowsFormsApp6
{
    public partial class Form1 : Form
    {

        Socket udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);  // 선언, 초기화
        //EndPoint localEP = new IPEndPoint(IPAddress.Any,0);
        EndPoint _remoteEP;
        //string positionValue;
        int a=1;
        string axisValue;


        public Form1()
        {
            InitializeComponent();
            //udpSocket.Bind(localEP);  // 실행
            //this.ActiveControl = textbox_ip; // 폼을 시작하자마자 ip 텍스트박스에 커서가 가게하기

            // 조그명령으로 앱으로 이동
            // 사각형 그리기
            // x축 
            // 뒤 마지막 : 1110297
            // 앞 마지막 : 952240
            // y축
            // 오른쪽 마지막 : 51339
            // 왼쪽 마지막 : -192068
            // 사각형 그리기
            // y: -37433
            // x: -147411
            // y: 207197
            // x: 11826
            //ip 5번 천천히, 빠르게
            this.button_send.Enabled = false;   // 폼을 열었을때 버튼 누르지못하게 하기
            this.button_rectangle.Enabled = false;
            this.button_stop.Enabled = false;
            this.textbox_ip.Text = "192.168.10.5";  // 폼을 열었을때 텍스트 박스에 값이 들어가있도록 하기
            this.textbox_port.Text = "4000";
            this.textBox4.Text = "100";
            this.textBox5.Text = "50000";
            this.textBox6.Text = "100000";
            this.textBox7.Text = "100000";
            this.textBox8.Text = "100";  // jerk : 홱 움직이다.
        }


        private void connect_Click(object sender, EventArgs e)
        {
            // 연결하기 버튼
            string ipaddress = string.Empty;
            ipaddress = textbox_ip.Text;  // ip 번호 입력
            IPAddress ipin = IPAddress.Parse(ipaddress);  // 문자열 ip주소를 숫자로 변환하기

            string portn = string.Empty;
            portn = textbox_port.Text;  // 포트 번호 입력
            int portin = Convert.ToInt32(portn);  // 문자열 포트 번호를 int형으로 변환하기


            if ((Convert.ToString(ipin) == "192.168.10.5") && (portin == 4000)) // ip주소와 port번호가 원하는 것과 일치하면
            {
                before.Text = "축을 선택하세요.";
                this.button_rectangle.Enabled = true;
                this.button_stop.Enabled = true;
                _remoteEP = new IPEndPoint(ipin, portin);  // ip와 port번호가 유효하면 remoteEP에 저장한다. if문밖에 remoteEP가 있으면 유효하지 않은 정보들을 다 저장하고 마지막으로 옳은것을 저장하게 된다.
            }
            else
            {
                before.Text = "IP 와 Port Number 확인해 주세요.";
            }
            

        }

        private void textBox3_position_TextChanged(object sender, EventArgs e)
        {
            string positionValue = string.Empty;
            positionValue = textBox3_position.Text;

        }

        private void radioButton_X_CheckedChanged(object sender, EventArgs e)
        {
            //string axisValue = string.Empty;
            axisValue = "0";
            this.button_send.Enabled = true;   // ip주소가 유효하면 위치전송 버튼 on
            this.timer1.Start();  // 유효한 ip가 입력되면 타이머 시작V
        }

        private void radioButton_Y_CheckedChanged(object sender, EventArgs e)
        {
            //string axisValue = string.Empty;
            axisValue = "1";
            this.button_send.Enabled = true;   // ip주소가 유효하면 위치전송 버튼 on
            this.timer1.Start();  // 유효한 ip가 입력되면 타이머 시작
        }

        private void button_send_Click(object sender, EventArgs e)
        {
            // 메세지전송
            string positionValue = string.Empty;   // 전송 명령 순서대로 박스에 넣기
            positionValue = textBox3_position.Text;
            string startvelocityValue = string.Empty;
            startvelocityValue = textBox4.Text;
            string endvelocityValue = string.Empty;
            endvelocityValue = textBox5.Text;
            string accelerationValue = string.Empty;
            accelerationValue = textBox6.Text;
            string decelerationValue = string.Empty;
            decelerationValue = textBox7.Text;
            string jerkValue = string.Empty;
            jerkValue = textBox8.Text;

            // 0은 x축, 1은 y축
            string sendMsg = String.Format("U[{0}, 5] ={1}, U[{0}, 6] ={2}, U[{0}, 7] ={3}, U[{0}, 8] ={4}, U[{0}, 9] ={5}, U[{0}, 10] ={6}, M[{0}] = 7", axisValue, positionValue, startvelocityValue, endvelocityValue, accelerationValue, decelerationValue, jerkValue);
            byte[] sendBuffer = Encoding.UTF8.GetBytes(sendMsg);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            string str = string.Empty;
            str = String.Format("U[{0},3]=0,M[{0}]=5,U[{0},4]", axisValue);
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            string receivedMsg = Encoding.UTF8.GetString(receiveBuffer);
            string[] splittedMsg = receivedMsg.Split(new char[] { ':', ',', ' ' });
            textBox2.Text = splittedMsg[6];
        }

        private void textBox4_TextChanged(object sender, EventArgs e)
        {
            string startvelocityValue = string.Empty;
            startvelocityValue = textBox4.Text;
        }

        private void textBox5_TextChanged(object sender, EventArgs e)
        {
            string endvelocityValue = string.Empty;
            endvelocityValue = textBox5.Text;
        }

        private void textBox6_TextChanged(object sender, EventArgs e)
        {
            string accelerationValue = string.Empty;
            accelerationValue = textBox6.Text;
        }

        private void textBox7_TextChanged(object sender, EventArgs e)
        {
            string decelerationValue = string.Empty;
            decelerationValue = textBox7.Text;
        }

        private void textBox8_TextChanged(object sender, EventArgs e)
        {
            string jerkValue = string.Empty;
            jerkValue = textBox8.Text;
        }
        
        private void rectangle_draw(string axisValue,string positionValue,int delay) // 축, 위치, delay값 받아오기
        {
            string sendMsg = String.Format("U[{0}, 5] ={1}, U[{0}, 6] ={2}, U[{0}, 7] ={3}, U[{0}, 8] ={4}, U[{0}, 9] ={5}, U[{0}, 10] ={6}, M[{0}] = 7", axisValue, positionValue, 100, 50000, 100000, 100000, 100);
            byte[] sendBuffer = Encoding.UTF8.GetBytes(sendMsg);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            Delay(delay);
        }

        private void button_rectangle_Click(object sender, EventArgs e)
        {
            rectangle_draw("1", "-114056", 5000);
            rectangle_draw("0", "-158796", 3500);
            rectangle_draw("1", "130613", 5000);
            rectangle_draw("0", "431", 3500);
        }   

        private void button_stop_Click(object sender, EventArgs e)
        {
            string str = string.Empty;
            str = String.Format("U[0,11]=0");
            str = String.Format("M[0]=10");
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기

            str = String.Format("U[1,11]=0");
            str = String.Format("M[1]=10");
            sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            receiveBuffer = new byte[512];
            receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
        }

        private void textBox3_position_TextChanged(object sender, KeyEventArgs e)
        {
                if (e.KeyCode == Keys.Enter)
                {
                    button_send_Click(sender, e);
                } 
        }

        private void button_send_Click(object sender, KeyEventArgs e)
        {
            //if (e.KeyCode == Keys.Enter)
            //{
            //    button_send_Click(sender, e);
            //}
        }

        private void connect_Click(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                connect_Click(sender, e);
            }
        }
        private void Delay(int ms)
        {
            DateTime dateTimeNow = DateTime.Now;
            TimeSpan duration = new TimeSpan(0, 0, 0, 0, ms);
            DateTime dateTimeAdd = dateTimeNow.Add(duration);
            while (dateTimeAdd >= dateTimeNow)
            {
                System.Windows.Forms.Application.DoEvents();
                dateTimeNow = DateTime.Now;
            }
            return;
        }
    }
}

delay함수를 만들어서 줬는데 사각형을 그리고 stop을 누르면 멈추기는 하는데 잠시 멈췄다가 다시 움직입니다. 이유를 찾아보니까 stop을 누르면 함수하나만 종료되고 delay만큼 시간이 지나면 다음 함수를 시작시켜서 움직이는 거였습니다. 아예 끄는 방법이 뭐가있을까요

 

stop한 후 다시 그리라고하면 되긴하는데 왜 stop버튼을 두번눌러야 멈추는 걸까요?

사각형그리기 버튼이 활성화돼있어서 그걸 풀어주고 stop을 누르니까 한번만 눌러도 됐습니다.

그런데 멈춘뒤 다시 그리라고했을 때 왜 뒤로갔다가 다시 앞으로 가는건지 모르겠습니다.

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace WindowsFormsApp6
{
    public partial class Form1 : Form
    {

        Socket udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);  // 선언, 초기화
        //EndPoint localEP = new IPEndPoint(IPAddress.Any,0);
        EndPoint _remoteEP;
        //string positionValue;
        int state=0;
        string axisValue;


        public Form1()
        {
            InitializeComponent();
            //udpSocket.Bind(localEP);  // 실행
            //this.ActiveControl = textbox_ip; // 폼을 시작하자마자 ip 텍스트박스에 커서가 가게하기

            // 조그명령으로 앱으로 이동
            // 사각형 그리기
            // x축 
            // 뒤 마지막 : 1110297
            // 앞 마지막 : 952240
            // y축
            // 오른쪽 마지막 : 51339
            // 왼쪽 마지막 : -192068
            // 사각형 그리기
            // y: -37433
            // x: -147411
            // y: 207197
            // x: 11826
            //ip 5번 천천히, 빠르게
            this.button_send.Enabled = false;   // 폼을 열었을때 버튼 누르지못하게 하기
            this.button_rectangle.Enabled = false;
            this.button_stop.Enabled = false;
            this.textbox_ip.Text = "192.168.10.5";  // 폼을 열었을때 텍스트 박스에 값이 들어가있도록 하기
            this.textbox_port.Text = "4000";
            this.textBox4.Text = "100";
            this.textBox5.Text = "50000";
            this.textBox6.Text = "100000";
            this.textBox7.Text = "100000";
            this.textBox8.Text = "100";  // jerk : 홱 움직이다.
        }


        private void connect_Click(object sender, EventArgs e)
        {
            // 연결하기 버튼
            string ipaddress = string.Empty;
            ipaddress = textbox_ip.Text;  // ip 번호 입력
            IPAddress ipin = IPAddress.Parse(ipaddress);  // 문자열 ip주소를 숫자로 변환하기

            string portn = string.Empty;
            portn = textbox_port.Text;  // 포트 번호 입력
            int portin = Convert.ToInt32(portn);  // 문자열 포트 번호를 int형으로 변환하기


            if ((Convert.ToString(ipin) == "192.168.10.5") && (portin == 4000)) // ip주소와 port번호가 원하는 것과 일치하면
            {
                before.Text = "축을 선택하세요.";
                this.button_rectangle.Enabled = true;
                this.button_stop.Enabled = true;
                _remoteEP = new IPEndPoint(ipin, portin);  // ip와 port번호가 유효하면 remoteEP에 저장한다. if문밖에 remoteEP가 있으면 유효하지 않은 정보들을 다 저장하고 마지막으로 옳은것을 저장하게 된다.
            }
            else
            {
                before.Text = "IP 와 Port Number 확인해 주세요.";
            }
            

        }

        private void textBox3_position_TextChanged(object sender, EventArgs e)
        {
            string positionValue = string.Empty;
            positionValue = textBox3_position.Text;

        }

        private void radioButton_X_CheckedChanged(object sender, EventArgs e)
        {
            //string axisValue = string.Empty;
            axisValue = "0";
            this.button_send.Enabled = true;   // ip주소가 유효하면 위치전송 버튼 on
            this.timer1.Start();  // 유효한 ip가 입력되면 타이머 시작V
        }

        private void radioButton_Y_CheckedChanged(object sender, EventArgs e)
        {
            //string axisValue = string.Empty;
            axisValue = "1";
            this.button_send.Enabled = true;   // ip주소가 유효하면 위치전송 버튼 on
            this.timer1.Start();  // 유효한 ip가 입력되면 타이머 시작
        }

        private void button_send_Click(object sender, EventArgs e)
        {
            // 메세지전송
            string positionValue = string.Empty;   // 전송 명령 순서대로 박스에 넣기
            positionValue = textBox3_position.Text;
            string startvelocityValue = string.Empty;
            startvelocityValue = textBox4.Text;
            string endvelocityValue = string.Empty;
            endvelocityValue = textBox5.Text;
            string accelerationValue = string.Empty;
            accelerationValue = textBox6.Text;
            string decelerationValue = string.Empty;
            decelerationValue = textBox7.Text;
            string jerkValue = string.Empty;
            jerkValue = textBox8.Text;

            // 0은 x축, 1은 y축
            string sendMsg = String.Format("U[{0}, 5] ={1}, U[{0}, 6] ={2}, U[{0}, 7] ={3}, U[{0}, 8] ={4}, U[{0}, 9] ={5}, U[{0}, 10] ={6}, M[{0}] = 7", axisValue, positionValue, startvelocityValue, endvelocityValue, accelerationValue, decelerationValue, jerkValue);
            byte[] sendBuffer = Encoding.UTF8.GetBytes(sendMsg);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            string str = string.Empty;
            str = String.Format("U[{0},3]=0,M[{0}]=5,U[{0},4]", axisValue);
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            string receivedMsg = Encoding.UTF8.GetString(receiveBuffer);
            string[] splittedMsg = receivedMsg.Split(new char[] { ':', ',', ' ' });
            textBox2.Text = splittedMsg[6];
        }

        private void textBox4_TextChanged(object sender, EventArgs e)
        {
            string startvelocityValue = string.Empty;
            startvelocityValue = textBox4.Text;
        }

        private void textBox5_TextChanged(object sender, EventArgs e)
        {
            string endvelocityValue = string.Empty;
            endvelocityValue = textBox5.Text;
        }

        private void textBox6_TextChanged(object sender, EventArgs e)
        {
            string accelerationValue = string.Empty;
            accelerationValue = textBox6.Text;
        }

        private void textBox7_TextChanged(object sender, EventArgs e)
        {
            string decelerationValue = string.Empty;
            decelerationValue = textBox7.Text;
        }

        private void textBox8_TextChanged(object sender, EventArgs e)
        {
            string jerkValue = string.Empty;
            jerkValue = textBox8.Text;
        }
        
        private void rectangle_draw(string axisValue,string positionValue,int delay) // 축, 위치, delay값 받아오기
        {
            string sendMsg = String.Format("U[{0}, 5] ={1}, U[{0}, 6] ={2}, U[{0}, 7] ={3}, U[{0}, 8] ={4}, U[{0}, 9] ={5}, U[{0}, 10] ={6}, M[{0}] = 7", axisValue, positionValue, 100, 50000, 100000, 100000, 100);
            byte[] sendBuffer = Encoding.UTF8.GetBytes(sendMsg);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            Delay(delay);
            //this.timer1.Start();
        }

        private void button_rectangle_Click(object sender, EventArgs e)
        {
            state = 0;
            while(true)
            {
                rectangle_draw("1", "-446", 5000);
                if (state == 1)
                {
                    break;
                }
                rectangle_draw("0", "-150878", 3500);
                if (state == 1)
                {
                    break;
                }
                rectangle_draw("1", "244220", 5000);
                if (state == 1)
                {
                    break;
                }
                rectangle_draw("0","8354", 3500);
                if (state == 1)
                {
                    break;
                }

            }
        }   

        private void button_stop_Click(object sender, EventArgs e)
        {
            state = 1;
            string str = string.Empty;
            str = String.Format("U[0,11]=0");
            str = String.Format("M[0]=10");
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기

            str = String.Format("U[1,11]=0");
            str = String.Format("M[1]=10");
            sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            receiveBuffer = new byte[512];
            receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
        }

        private void textBox3_position_TextChanged(object sender, KeyEventArgs e)
        {
                if (e.KeyCode == Keys.Enter)
                {
                    button_send_Click(sender, e);
                } 
        }


        private void connect_Click(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                connect_Click(sender, e);
            }
        }
        private void Delay(int ms)
        {
            DateTime dateTimeNow = DateTime.Now;
            TimeSpan duration = new TimeSpan(0, 0, 0, 0, ms);
            DateTime dateTimeAdd = dateTimeNow.Add(duration);
            while (dateTimeAdd >= dateTimeNow)
            {
                System.Windows.Forms.Application.DoEvents();
                dateTimeNow = DateTime.Now;
            }
            return;
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

 

축마다 따로 움직이기, 사각형그리기, 그리다가 멈추기 다 가능하고 어떤 명령이든 모터의 현재위치를 받아오는 것까지 성공했습니다.

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace WindowsFormsApp6
{
    public partial class Form1 : Form
    {

        Socket udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);  // 선언, 초기화
        //EndPoint localEP = new IPEndPoint(IPAddress.Any,0);
        EndPoint _remoteEP;
        //string positionValue;
        bool _state=true;
        string axisValue;
        


        public Form1()
        {
            InitializeComponent();
            //udpSocket.Bind(localEP);  // 실행
            //this.ActiveControl = textbox_ip; // 폼을 시작하자마자 ip 텍스트박스에 커서가 가게하기

            // 조그명령으로 앱으로 이동
            // 사각형 그리기
            // x축 
            // 뒤 마지막 : 1110297
            // 앞 마지막 : 952240
            // y축
            // 오른쪽 마지막 : 51339
            // 왼쪽 마지막 : -192068
            // 사각형 그리기
            // y: -37433
            // x: -147411
            // y: 207197
            // x: 11826
            //ip 5번 천천히, 빠르게
            this.button_send.Enabled = false;   // 폼을 열었을때 버튼 누르지못하게 하기
            this.button_rectangle.Enabled = false;
            this.button_stop.Enabled = false;
            this.textbox_ip.Text = "192.168.10.5";  // 폼을 열었을때 텍스트 박스에 값이 들어가있도록 하기
            this.textbox_port.Text = "4000";
            this.textBox4.Text = "100";
            this.textBox5.Text = "50000";
            this.textBox6.Text = "100000";
            this.textBox7.Text = "100000";
            this.textBox8.Text = "100";  // jerk : 홱 움직이다.

        }


        private void connect_Click(object sender, EventArgs e)
        {
            // 연결하기 버튼
            string ipaddress = string.Empty;
            ipaddress = textbox_ip.Text;  // ip 번호 입력
            IPAddress ipin = IPAddress.Parse(ipaddress);  // 문자열 ip주소를 숫자로 변환하기

            string portn = string.Empty;
            portn = textbox_port.Text;  // 포트 번호 입력
            int portin = Convert.ToInt32(portn);  // 문자열 포트 번호를 int형으로 변환하기



            if ((Convert.ToString(ipin) == "192.168.10.5") && (portin == 4000)) // ip주소와 port번호가 원하는 것과 일치하면
            {
                before.Text = "축을 선택하세요.";
                this.button_rectangle.Enabled = true;
                this.button_stop.Enabled = true;
                this.timer1.Start();
                _remoteEP = new IPEndPoint(ipin, portin);  // ip와 port번호가 유효하면 remoteEP에 저장한다. if문밖에 remoteEP가 있으면 유효하지 않은 정보들을 다 저장하고 마지막으로 옳은것을 저장하게 된다.
            }
            else
            {
                before.Text = "IP 와 Port Number 확인해 주세요.";
            }
            

        }

        private void textBox3_position_TextChanged(object sender, EventArgs e)
        {
            string positionValue = string.Empty;
            positionValue = textBox3_position.Text;

        }

        private void radioButton_X_CheckedChanged(object sender, EventArgs e)
        {
            //string axisValue = string.Empty;
            axisValue = "0";
            this.button_send.Enabled = true;   // ip주소가 유효하면 위치전송 버튼 on
            this.timer1.Start();  // 유효한 ip가 입력되면 타이머 시작V
        }

        private void radioButton_Y_CheckedChanged(object sender, EventArgs e)
        {
            //string axisValue = string.Empty;
            axisValue = "1";
            this.button_send.Enabled = true;   // ip주소가 유효하면 위치전송 버튼 on
            this.timer1.Start();  // 유효한 ip가 입력되면 타이머 시작
        }

        private void button_send_Click(object sender, EventArgs e)
        {
            // 메세지전송
            string positionValue = string.Empty;   // 전송 명령 순서대로 박스에 넣기
            positionValue = textBox3_position.Text;
            string startvelocityValue = string.Empty;
            startvelocityValue = textBox4.Text;
            string endvelocityValue = string.Empty;
            endvelocityValue = textBox5.Text;
            string accelerationValue = string.Empty;
            accelerationValue = textBox6.Text;
            string decelerationValue = string.Empty;
            decelerationValue = textBox7.Text;
            string jerkValue = string.Empty;
            jerkValue = textBox8.Text;

            // 0은 x축, 1은 y축
            string sendMsg = String.Format("U[{0}, 5] ={1}, U[{0}, 6] ={2}, U[{0}, 7] ={3}, U[{0}, 8] ={4}, U[{0}, 9] ={5}, U[{0}, 10] ={6}, M[{0}] = 7", axisValue, positionValue, startvelocityValue, endvelocityValue, accelerationValue, decelerationValue, jerkValue);
            byte[] sendBuffer = Encoding.UTF8.GetBytes(sendMsg);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            string str = string.Empty;
            str = String.Format("U[0,3]=0,M[0]=5,U[0,4]");
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            string receivedMsg = Encoding.UTF8.GetString(receiveBuffer);
            string[] splittedMsg = receivedMsg.Split(new char[] { ':', ',', ' ' });

            string str_y = string.Empty;
            str_y = String.Format("U[1,3]=0,M[1]=5,U[1,4]");
            byte[] sendBuffer_y = Encoding.UTF8.GetBytes(str_y);
            udpSocket.SendTo(sendBuffer_y, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer_y = new byte[512];
            int receivedSize_y = udpSocket.ReceiveFrom(receiveBuffer_y, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            string receivedMsg_y = Encoding.UTF8.GetString(receiveBuffer_y);
            string[] splittedMsg_y = receivedMsg_y.Split(new char[] { ':', ',', ' ' });

            if (axisValue == "0")
            {
                textBox2.Text = splittedMsg[6];
            }
            else if (axisValue == "1")
            {
                textBox1.Text= splittedMsg_y[6];
            }
        }

        private void textBox4_TextChanged(object sender, EventArgs e)
        {
            string startvelocityValue = string.Empty;
            startvelocityValue = textBox4.Text;
        }

        private void textBox5_TextChanged(object sender, EventArgs e)
        {
            string endvelocityValue = string.Empty;
            endvelocityValue = textBox5.Text;
        }

        private void textBox6_TextChanged(object sender, EventArgs e)
        {
            string accelerationValue = string.Empty;
            accelerationValue = textBox6.Text;
        }

        private void textBox7_TextChanged(object sender, EventArgs e)
        {
            string decelerationValue = string.Empty;
            decelerationValue = textBox7.Text;
        }

        private void textBox8_TextChanged(object sender, EventArgs e)
        {
            string jerkValue = string.Empty;
            jerkValue = textBox8.Text;
        }
        
        private void rectangle_draw(string axis, string positionValue,int delay) // 축, 위치, delay값 받아오기
        {
            axisValue = axis;
            string sendMsg = String.Format("U[{0}, 5] ={1}, U[{0}, 6] ={2}, U[{0}, 7] ={3}, U[{0}, 8] ={4}, U[{0}, 9] ={5}, U[{0}, 10] ={6}, M[{0}] = 7", axisValue, positionValue, 100, 50000, 100000, 100000, 100);
            byte[] sendBuffer = Encoding.UTF8.GetBytes(sendMsg);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            Delay(delay);
            this.timer1.Start();
        } // x위치가 비어있으면 안뜬다.

        private void button_rectangle_Click(object sender, EventArgs e)
        {
            while(_state)
            {
                // 디자인 패턴 읽어보기
                rectangle_draw("1", "-168091", 5000);
                rectangle_draw("0", "-124152", 3500);
                rectangle_draw("1", "76570", 5000);
                rectangle_draw("0", "35082", 3500);
            }  // 작업스레드 만들어서 while문 만들기, 스레드 죽이기 : while문 돌고있으면 abort쓰지말기 그냥 false하면 스레드 나감. 스레드함수를 탈출해서 종료시키면된다.
        }   // getstate로 거리로 짜기
        // while -switch로 짜기 case 0 이면 move, step을 1로 바꾸고 checkposition하고 되면 2로 바꿈 아니면 계속 1 , 스레드를 쓰면 sleep을 쓸일이없다. 시퀀스는 while switch case를 쓴다. .성공하면 다음 스텝으로 while문만 나오면 스레드가 그냥 종료된다.  장비를 껐다키면 쓰레기값이 들어가있다. 초기화하고나면 위치를 주면 계속 같은 사각형을 그린다.   
        // 스레드를 짜면 이전 오류가 없을 것이다. 
        private void button_stop_Click(object sender, EventArgs e)
        {
            _state = false;
            string str = string.Empty;
            str = String.Format("U[0,11]=0");
            str = String.Format("M[0]=10");
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기

            str = String.Format("U[1,11]=0");
            str = String.Format("M[1]=10");
            sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            receiveBuffer = new byte[512];
            receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
        }

        private void textBox3_position_TextChanged(object sender, KeyEventArgs e)
        {
                if (e.KeyCode == Keys.Enter)
                {
                    button_send_Click(sender, e);
                } 
        }


        private void connect_Click(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                connect_Click(sender, e);
            }
        }
        private void Delay(int ms)
        {
            DateTime dateTimeNow = DateTime.Now;
            TimeSpan duration = new TimeSpan(0, 0, 0, 0, ms);
            DateTime dateTimeAdd = dateTimeNow.Add(duration);
            while (dateTimeAdd >= dateTimeNow)
            {
                System.Windows.Forms.Application.DoEvents(); //sleep이랑 비슷하다 그냥 doevents로 다른일이 있는지 보고오라는 의미라서 버튼이 먹히는것이다.
                dateTimeNow = DateTime.Now;
            }
            return;
        }
        //private void rectangle_loop()
        //{
        //    while (_state)
        //    {
        //        string move_x = textBox2.Text;
        //        string move_y = textBox1.Text;
        //        switch (move_x)
        //        {
        //            case "-150878":



        //        }
        //        rectangle_draw("1", "-446", 5000);
        //        rectangle_draw("0", "-150878", 3500);
        //        rectangle_draw("1", "244220", 5000);
        //        rectangle_draw("0", "8354", 3500);
        //    }
        //}
    }
}

 

문제는 객체지향프로그램으로 만들어야된다는 것입니다.

위 코드는 절차지향이라서 하나를 고치면 하나가 안되고 복잡한 코드를 실행하기에는 부적합한 프로그래밍방법입니다.

스레드함수를 이용하여 객체지향 프로그램을 만들어보겠습니다.

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace WindowsFormsApp6
{
    public partial class Form1 : Form
    {

        Socket udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);  // 선언, 초기화
        EndPoint _remoteEP;
        bool _state=true;  // Thread 함수 while문 상태
        string _axisValue; // 선택한 축 받아오기
        

        public Form1()
        {
            InitializeComponent();
            this.button_send.Enabled = false;   // 폼을 열었을때 버튼 누르지못하게 하기
            this.button_rectangle.Enabled = false;
            this.button_stop.Enabled = false;
            this.textbox_ip.Text = "192.168.10.5";  // 폼을 열었을때 텍스트 박스에 값이 들어가있도록 하기
            this.textbox_port.Text = "4000";
            this.textBox4.Text = "100";
            this.textBox5.Text = "50000";
            this.textBox6.Text = "100000";
            this.textBox7.Text = "100000";
            this.textBox8.Text = "100";  // jerk : 홱 움직이다.( 가속도의 변화량 )

        }


        private void connect_Click(object sender, EventArgs e)
        {
            // 전송 버튼
            string ipaddress = string.Empty;
            ipaddress = textbox_ip.Text;  // ip 번호 입력
            IPAddress ipin = IPAddress.Parse(ipaddress);  // 문자열 ip주소를 숫자로 변환하기

            string portn = string.Empty;
            portn = textbox_port.Text;  // 포트 번호 입력
            int portin = Convert.ToInt32(portn);  // 문자열 포트 번호를 int형으로 변환하기

            if ((Convert.ToString(ipin) == "192.168.10.5") && (portin == 4000)) // ip주소와 port번호가 원하는 것과 일치하면
            {
                before.Text = "축을 선택하세요.";
                this.button_rectangle.Enabled = true;
                this.button_stop.Enabled = true;
                this.timer1.Start();  // 현재위치 받아오기
                _remoteEP = new IPEndPoint(ipin, portin);  // ip와 port번호가 유효하면 remoteEP에 저장한다.
            }
            else
            {
                before.Text = "IP 와 Port Number 확인해 주세요.";
            }
            

        }

        private void radioButton_X_CheckedChanged(object sender, EventArgs e)
        {
            _axisValue = "0";
            this.button_send.Enabled = true; // 축을 선택하면 '전송' 버튼 활성화
        }

        private void radioButton_Y_CheckedChanged(object sender, EventArgs e)
        {
            _axisValue = "1";
            this.button_send.Enabled = true;  
        }

        private void button_send_Click(object sender, EventArgs e) // 마우스로 클릭하면 '전송'버튼이 눌린다.
        {
            // 전송할 값
            string positionValue = string.Empty;
            positionValue = textBox3_position.Text;
            string startvelocityValue = string.Empty;
            startvelocityValue = textBox4.Text;
            string endvelocityValue = string.Empty;
            endvelocityValue = textBox5.Text;
            string accelerationValue = string.Empty;
            accelerationValue = textBox6.Text;
            string decelerationValue = string.Empty;
            decelerationValue = textBox7.Text;
            string jerkValue = string.Empty;
            jerkValue = textBox8.Text;

            // 0은 x축, 1은 y축
            string sendMsg = String.Format("U[{0}, 5] ={1}, U[{0}, 6] ={2}, U[{0}, 7] ={3}, U[{0}, 8] ={4}, U[{0}, 9] ={5}, U[{0}, 10] ={6}, M[{0}] = 7", _axisValue, positionValue, startvelocityValue, endvelocityValue, accelerationValue, decelerationValue, jerkValue);
            byte[] sendBuffer = Encoding.UTF8.GetBytes(sendMsg);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기

        }

        private void timer1_Tick(object sender, EventArgs e)  // 모터의 위치를 매 시간 받아오기
        {
            string str_x = string.Empty;
            str_x = String.Format("U[0,3]=0,M[0]=5,U[0,4]");
            xcurrent_position_print(str_x);

            string str_y = string.Empty;
            str_y = String.Format("U[1,3]=0,M[1]=5,U[1,4]");
            ycurrent_position_print(str_y);
        }

        private void xcurrent_position_print(string str)  // x 현재위치 출력
        {
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            string receivedMsg = Encoding.UTF8.GetString(receiveBuffer);
            string[] splittedMsg = receivedMsg.Split(new char[] { ':', ',', ' ' });
            textBox2.Text = splittedMsg[6];
        }

        private void ycurrent_position_print(string str_y)  // y 현재위치 출력
        {
            byte[] sendBuffer_y = Encoding.UTF8.GetBytes(str_y);
            udpSocket.SendTo(sendBuffer_y, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer_y = new byte[512];
            int receivedSize_y = udpSocket.ReceiveFrom(receiveBuffer_y, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            string receivedMsg_y = Encoding.UTF8.GetString(receiveBuffer_y);
            string[] splittedMsg_y = receivedMsg_y.Split(new char[] { ':', ',', ' ' });
            textBox1.Text = splittedMsg_y[6];
        }

        private void textBox3_position_TextChanged(object sender, EventArgs e)
        {
            string positionValue = string.Empty;
            positionValue = textBox3_position.Text;

        }
        
        private void rectangle_draw(string axis, string positionValue)
        {
            _axisValue = axis;  // 전역변수에 지역변수 대입하기
            string sendMsg = String.Format("U[{0}, 5] ={1}, U[{0}, 6] ={2}, U[{0}, 7] ={3}, U[{0}, 8] ={4}, U[{0}, 9] ={5}, U[{0}, 10] ={6}, M[{0}] = 7", _axisValue, positionValue, 100, 50000, 100000, 100000, 100);
            byte[] sendBuffer = Encoding.UTF8.GetBytes(sendMsg);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
            this.timer1.Start();
        } 

        private void button_rectangle_Click(object sender, EventArgs e)
        {
            _state = true; // while문 시작
            Thread myThread = new Thread(rectangle_loop);  // Thread 함수 시작
            myThread.Start(); // 작업스레드 만들어서 while문 만들기, 스레드 죽이기 : while문 돌고있으면 abort쓰지말기 그냥 false하면 스레드 나감. 스레드함수를 탈출해서 종료시키면된다.
        }  

        private void button_stop_Click(object sender, EventArgs e)
        {
            _state = false;  // while문을 빠져나와라
            stop("0");  // x축을 멈춰라
            stop("1");  // y축을 멈춰라
        }

        private void stop(string axisValue)
        {
            string str = string.Empty;
            str = String.Format("U[{0},11]=0",axisValue);
            str = String.Format("M[{0}]=10",axisValue);
            byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
            udpSocket.SendTo(sendBuffer, _remoteEP);  // sendBuffer에 받아온것을 remoteEP에 보내기
            byte[] receiveBuffer = new byte[512];
            int receivedSize = udpSocket.ReceiveFrom(receiveBuffer, ref _remoteEP); // remoteEP에 있는 것을 receiveBuffer로 받아오기
        }

        private void textBox3_position_TextChanged(object sender, KeyEventArgs e)  // position 텍스트박스에서 엔터키를 누르면 '전송' 버튼이 눌린다.
        {
                if (e.KeyCode == Keys.Enter)
                {
                    button_send_Click(sender, e);
                } 
        }


        private void connect_Click(object sender, KeyEventArgs e)  // '전송' 버튼이 활성화됐을때 엔터키를 누르면 '전송'버튼이 눌린다.
        {
            if (e.KeyCode == Keys.Enter)
            {
                connect_Click(sender, e);
            }
        }

        private void rectangle_loop()  // 사각형을 그리는 함수
        {
            string x1 = "-150000";
            string y1 = "-200000";

            string x2 = "6000";
            string y2 = "-800";
            
            int position_case = 0;
            while (_state)
            {
                switch (position_case)
                {
                    case 0:  
                        rectangle_draw("1", y1); // 사각형 그리기
                        position_case = 1;
                        Thread.Sleep(5000);
                        if (y1 == textBox1.Text) // 위치 확인하고 case 변경
                        {
                            position_case = 1;
                        }
                        else
                        {
                            position_case = 0;
                        }
                        break;
                    case 1:
                        rectangle_draw("0", x1);
                        position_case = 3;
                        Thread.Sleep(1000);
                        if (x1 == textBox2.Text)
                        {
                            position_case = 2;
                        }
                        else
                        {
                            position_case = 1;
                        }
                        break;
                    case 2:
                        rectangle_draw("1", y2);
                        position_case = 5;
                        Thread.Sleep(1000);
                        if (y2 == textBox1.Text)
                        {
                            position_case = 3;
                        }
                        else
                        {
                            position_case = 2;
                        }
                        break;
                    case 3:
                        rectangle_draw("0", x2);
                        position_case = 7;
                        Thread.Sleep(1000);
                        if (x2 == textBox2.Text)
                        {
                            position_case = 0;
                        }
                        else
                        {
                            position_case = 3;
                        }
                        break;
                }
            }
        }
         
        // 전송할 값 입력하기
        private void textBox4_TextChanged(object sender, EventArgs e)
        {
            string startvelocityValue = string.Empty;
            startvelocityValue = textBox4.Text;
        }

        private void textBox5_TextChanged(object sender, EventArgs e)
        {
            string endvelocityValue = string.Empty;
            endvelocityValue = textBox5.Text;
        }

        private void textBox6_TextChanged(object sender, EventArgs e)
        {
            string accelerationValue = string.Empty;
            accelerationValue = textBox6.Text;
        }

        private void textBox7_TextChanged(object sender, EventArgs e)
        {
            string decelerationValue = string.Empty;
            decelerationValue = textBox7.Text;
        }

        private void textBox8_TextChanged(object sender, EventArgs e)
        {
            string jerkValue = string.Empty;
            jerkValue = textBox8.Text;
        }
    }
}

 

모터를 껐다가 키면 초기위치에는 쓰레기값이 들어있기때문에 매번 초기화를 해줘야합니다. 이를 어떻게 구현할수있을까요?

 

 

폼에서 [보기]-[탭 순서]를 누르면 탭 순서를 바꿀 수 있습니다.

글자 두껍게 만드는 것을 속성에 font에 ...을 누르면 됩니다.

 

실행 오류 : 파일은 다른 프로세스에서 사용 중이므로 프로세스에서 액세스할 수 없습니다.

해결방법 : cmd창에 taskkill /pid 프로세스id /f 를 치면 됩니다.

ex) taskkill /pid 105004 /f

 

폼 저장된곳

C:\Users\yehjin\source\repos\WindowsFormsApp6

7번

 

udp 통신에 관한 블로그

https://github.com/synml/UDP-socket-programming

 

 

근데 쟤가 hello주면 받는걸로 모터 제어는 어떻게 하죠..

 

 

Q1. 연결완료된 것을 확인하려면 어떻게 해야할까요?

A1. UDP통신에는 연결이란 것이 없다고 합니다. 그냥 IP를 입력하면 연결확인 이런것 없이 모션보드에 위치를 무작정 보내는 것입니다.

 

Q2. 지역변수를 여러번 썼는데 간단하게 하는 방법이 뭘까요?

A2. 함수를 만들어서 사용하면됩니다. 

 

Q3. 모션보드에 모터는 왜 달려있어야 할까요?

A3. 모터를 꽂아야 현재 위치를 계속 업데이트 할수있습니다. 프로그램을 실행시키고 위치 전송을 한 후 현재위치가 바뀌는 것을 본후 모터를 제거해 보면 현재위치가 바뀌지않는 것을 확인 할 수 있습니다. 

 

Q4. 서보모터의 위치값이 왜 계속 바뀌는 건가요?

A4. 모터를 아예 껐다가 키면 초기값에는 쓰레기값이 들어있기때문입니다. 그래서 처음에는 값을 초기화 해줘야합니다.

 

Q5. 폼에 사각형그리기 버튼을 누른뒤 폼을 눌러서 버튼을 풀어줘야 다른 버튼이 눌리는데 왜 그런건가요?

A5. while문으로 만들었기때문에 cpu가 다른일을 할 틈을 주지않기때문에 다른 버튼이 눌리지않는 것입니다.

     Thread함수를 만들어서 실행시키면 이 문제는 해결할 수 있습니다.

 

Q6. Thread함수를 switch문을 만들면 Thread.Sleep이 필요없다고 하셨는데 저는 그 지정한 위치랑 현재위치가 sleep이없으면 같아지기힘들던데 어떻게 sleep없이 만들수있을까요?

A6.

 

Q7. 멤버 변수와 지역변수의 차이점은 무엇일까요?

A7. 

 

**참고

ip주소 설정

https://www.csharpstudy.com/net/article/3-IP-%EC%A3%BC%EC%86%8C%EC%99%80-%ED%98%B8%EC%8A%A4%ED%8A%B8

window framework 만들기

https://docs.microsoft.com/ko-kr/visualstudio/ide/create-csharp-winform-visual-studio?view=vs-2019 

데이터 주고 받기

https://afsdzvcx123.tistory.com/entry/C-%EC%9C%88%ED%8F%BC-%ED%8F%BC%EA%B0%84-%EB%8D%B0%EC%9D%B4%ED%84%B0-%EC%A0%84%EB%8B%AC%ED%95%98%EB%8A%94-%EB%B0%A9%EB%B2%95-%EB%B6%80%EB%AA%A8%ED%8F%BC-%EC%9E%90%EC%8B%9D%ED%8F%BC-%EC%9E%90%EC%8B%9D%ED%8F%BC-%EB%B6%80%EB%AA%A8-%ED%8F%BC

 

+ Recent posts