[라이브러리 08.15] C# USB통신

2011. 8. 15. 23:26C#/라이브러리

LibUsbDotNet의 C# Usb 라이브러리는 WinUsb,Libusb win32, and Linux libusb v1.x 개발자들이 만들었으며 모든 기본 USB장치의 기능을 사용할수 있으며 일반적인 클래스를 할수 있습니다. 

이 라이브러리를 사용하기 위해서는 VendorID와 ProductID 가 있어야 하며 일반적인 USB에 대한 지식이 필요합니다.
그렇다고 깊게 이해하실 필요는 없고 Endpoint가 무엇이고 VID가 뭐고 PID가 뭔지만 아시면 쉽게 USB라이브러리를 사용하실수 있으실것이빈다.

가장 먼저 USB통신을 하실때 필요한게 이 USB가 꼽혔나?? 아닌가를 체크가 필요하게 됩니다.

1. 장치 알림!!(Usb Device Notify)

using System;
using System.Windows.Forms;
using LibUsbDotNet.DeviceNotify;

namespace Device.Notification
{
    internal class DeviceNotification
    {
        public static IDeviceNotifier UsbDeviceNotifier = DeviceNotifier.OpenDeviceNotifier();

        private static void Main(string[] args)
        {
            // Hook the device notifier event
            UsbDeviceNotifier.OnDeviceNotify += OnDeviceNotifyEvent; //이벤트 핸들 추가!!

            UsbDeviceNotifier.Enabled = false;  // 장치인식하는 걸 안하게 하는거!!
            UsbDeviceNotifier.OnDeviceNotify -= OnDeviceNotifyEvent;
            // 이벤트 핸들에서 삭제 한다.
        }

        private static void OnDeviceNotifyEvent(object sender, DeviceNotifyEventArgs e)
        {
            // 장치가 삽입되면 인식하여 이벤트가 발생한다.
        }
    }
}

 

 여기서 전체 흐름은 이게 끝이다 간단하게 구현되지만 프로그램 구현시 개발자로서는 꼭 사용자가 부탁하는 기능이다.

아놔...!!
많이 써놨는데 날라갔다....;ㅅ;제길

그래서 그냥 읽고 쓰는거 다 줄여서 읽기 인트럽트로 해서 읽고 쓰는거를 한방에 써버리기로 했다.!!

2. 
 
public UsbEndpointReader reader;
public UsbEndpointWriter writer;

public void ReadEventinitStart()
{
       reader.DataReceivedEnabled = true;
       reader.DataReceived += (ReadEvent)

 

 public bool Connect()
        {
            MyUsbFinder = new UsbDeviceFinder(0x0adc, 0x0018);
            ErrorCode ec = ErrorCode.None;

            try
            {
                MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);

                if (MyUsbDevice == null) throw new Exception("Device Not Found.");

                IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
                reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep02);
                writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep01);
                init();

                if (!ReferenceEquals(wholeUsbDevice, null))
                {
                    wholeUsbDevice.SetConfiguration(1);
                    wholeUsbDevice.ClaimInterface(0);
                }
                open = true;
                return true;

            }
            catch (Exception ex)
            {
                open = false;
                return false;
            }
                      
 }

public void writeProcess(string send)
{

           rec=send;

            try
            {
                
                ErrorCode ec = ErrorCode.None;
                int bytesWritten = 64;
                byte[] data = UnicodeEncoding.ASCII.GetBytes(send);
               //아스키코드 변환
                ec = writer.Write(data, 2000, out bytesWritten);
                
                
                if (ec != ErrorCode.None) throw new Exception(UsbDevice.LastErrorString);
            }
            catch (System.Exception e)
            {
                MessageBox.Show("USB연결 상태가 좋지 않습니다. 다시 접속중입니다.");
            }
}
 

public void ReadEvent(object sender, EndpointDataEventArgs e)
        {



            string str = UnicodeEncoding.ASCII.GetString(e.Buffer, 0, e.Count);

            try
            {

            }
            catch (System.Exception ex)
            {

            }
            
       } 




http://libusbdotnet.sourceforge.net 요기서 확인해요