C# Dynamixel 강좌 : 제 3강 - Dynamixel Serial 통신
Dynamixel & C#
Dynamixel과 C#에서 Serial 통신하여 액추에이터를 제어할 수 있습니다.
세부 코드
using System.IO.Ports;Serial 통신을 위하여 namespace에 IO.Ports를 선언합니다.
static SerialPort serial;Dynamixel과의 통신을 위하여 serial이라는 변수를 선언합니다.
private void Form1_Load(object sender, EventArgs e)
{
try
{
if (serial == null)
{
serial = new SerialPort("COM10", 1000000);
serial.Open();
}
}
catch
{
MessageBox.Show("Serial 포트가 없습니다.");
}
}Form1 로드 시 serial의 포트를 설정합니다. Dynamixel Wizard 또는 장치관리자에서 포트 번호를 확인할 수 있습니다.
private static void Dynamixel(byte ID, int position, byte speed)
{
byte length = 7;
byte pos_l = (byte)(position & 0xff);
byte pos_h = (byte)((position & 0xff00) >> 8);
byte speed_l = (byte)(speed & 0xff);
byte speed_h = (byte)((speed & 0xff00) >> 8);
byte checkSum = (byte)(~((ID + length + 0x03 + 0x1E + pos_h + pos_l + speed_h + speed_l) & 0xff));
byte[] buffer = { 0xFF, 0xFF, ID, length, 0x03, 0x1E, pos_l, pos_h, speed_l, speed_h, checkSum };
serial.Write(buffer, 0, buffer.Length);
}위의 코드를 활용하여 Dynamixel의 목표 위치와 속도를 제어할 수 있습니다.
Dynamixel(ID, POSITION, SPEED);Dynamixel이 작동할 부분에 위의 사용자 정의 함수를 이용해 제어할 수 있습니다.
POSITION은 0~2047 또는 0~4095 등의 범위를 가지며, SPEED는 0~2047 등의 값을 가집니다.
추가적인 제어가 필요하다면 checkSum과 buffer를 수정하여 제어가 가능합니다.
Dynamixel의 종류마다 POSITION과 SPEED 등의 값이 다릅니다.
ROBOTIS E-Manual을 통해 값을 확인이 가능합니다.
ROBOTIS e-Manual : 바로가기
전체 코드
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.IO.Ports;
namespace Dynamixel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
static SerialPort serial;
private void Form1_Load(object sender, EventArgs e)
{
try
{
if (serial == null)
{
serial = new SerialPort("COM10", 1000000);
serial.Open();
}
}
catch
{
MessageBox.Show("Serial Port가 없습니다.");
}
}
private static void Dynamixel(byte ID, int position, byte speed)
{
byte length = 7;
byte pos_l = (byte)(position & 0xff);
byte pos_h = (byte)((position & 0xff00) >> 8);
byte speed_l = (byte)(speed & 0xff);
byte speed_h = (byte)((speed & 0xff00) >> 8);
byte checkSum = (byte)(~((ID + length + 0x03 + 0x1E + pos_h + pos_l + speed_h + speed_l) & 0xff));
byte[] buffer = { 0xFF, 0xFF, ID, length, 0x03, 0x1E, pos_l, pos_h, speed_l, speed_h, checkSum };
serial.Write(buffer, 0, buffer.Length);
}
}
}공유하기
Kakao
Naver
Twitter
LinkedIn
Facebook
댓글 남기기