페이스북을 통해 관심있던 ai수업을 교육비 전액 지원한다는 게시물을 보고 빠르게 신청했습니다.
강의로 먼저 개념을 설명해주시고 실습을 통해 바로 적용해볼수있다는 것이 정말좋았습니다. 반복적으로 실습을 하다보니까 이해가 바로바로 되더라구요! 제가 이해가 좀 느린편이기도하고 설명을 듣고 한번에 이해하기가 힘들어서 질문도 많이했는데 그때마다 엄청빨리 답변을 주셔서 좋았어요. 앞에서 설명을 들은것중에 이해가 안돼서 질문을하니까 예시를 들어가면서 되게 친절하게 답변을 해주셨어요. 많이물어봐서 귀찮으셨을텐데 답해주셔서 정말 감사했습니다ㅠㅠ
아래 사진처럼 실습에 대한 해설강의도 올려주셔서 이해하는데 문제가 없었어요!
강의를 다 듣고나면 프로젝트로 실무적용을 해볼수있어요!
처음에 ai를 공부했을때 Udacity를 봤는데 영어라서 너무 이해하기가 힘들더라구요.. 그런데 같은 내용을 한글강의로 듣기도했고 비전공자도 이해할수있도록 쉽게 설명해 주셔서 정말 좋았어요.
전송계층이란 송신자와 수신자를 연결하는 통신서비스를 제공하는 계층입니다. 데이터의 전달을 담당한다고 보시면 됩니다. 데이터를 전달하기위해서는 프로토콜을 사용해야하는데 그 프로토콜이 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+X 키로 도구상자 열기 --> 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를 주면서 버튼이 활성화되는 방법이 뭐가있을까요?
delay함수를 만들어서 줬는데 사각형을 그리고 stop을 누르면 멈추기는 하는데 잠시 멈췄다가 다시 움직입니다. 이유를 찾아보니까 stop을 누르면 함수하나만 종료되고 delay만큼 시간이 지나면 다음 함수를 시작시켜서 움직이는 거였습니다. 아예 끄는 방법이 뭐가있을까요