반응형

이벤트 생성 3번째 입니다. 이번 예제는 이벤트 함수의 파라메타로 이벤트 발생시 데이타 정보를 전달하는 방법에 대해 설명을 합니다. 예제는 part-1 에서 사용했던 MyText 클래스를 변형하여 사용하였습니다. 

 

우선 아래와 같이 이벤트 발생시 데이타를 추가하여 파라메터로 넘겨줄 클래스를 하나 생성 합니다.
기본 클래스인 EventArgs를 상속 받아서 만드는데 EventArgs는 아무것도 넘겨줄게 없을때 사용하는 클래스 입니다. 

public class MyTextEventArgs : EventArgs
{
    public string Text { get; }    // 파라메터로 넘겨 줄 데이타

    public MyTextEventArgs(string text)   // 생성자에서 변경된 Text 정보를 넘겨받는다.
    {
        this.Text = text;
    }
}

 

델리케이트 선언에서 함수 파라메터로 위에서 만든 클래스를 사용합니다. 
그리고 이벤트 함수 실행부분에서 변경된 Text 정보를 생성자의 파라메터로 넘겨 줍니다.

public class MyText
{
    public delegate void EventHandler(object sender, MyTextEventArgs e);  // 이벤트 핸들러의 형식을 delegate로 등록한다.

    private string text = "";
    public string Text
    {
        set
        {
            text = value;
            if(OnTextChangedHandler != null)
            {
                OnTextChangedHandler(this, new MyTextEventArgs(text));  // 이벤트 함수 실행시 변경된 Text 정보를 전달합니다.
            }
        }
    }

    public event EventHandler? OnTextChangedHandler = null ;   
}

 

사용방법은 아래와 같습니다. 

public partial class Form1 : Form
{
    MyText myText = new MyText();
    public Form1()
    {
        InitializeComponent();
        myText.OnTextChangedHandler += text_Changed;
    }

    private void text_Changed(object sender, MyTextEventArgs e) 
    {
        textBox1.Text = e.Text;    // 파라메터를 통해 넘어온 변경 데이타를 이용합니다.
    }

    private void button1_Click(object sender, EventArgs e)
    {
        myText.Text = "Hello World.";        
    }
}
반응형
반응형

아두이노에서 내부 Timer를 이용하여 LED를 제어하는 코드 입니다. 

토글 스위치를 이용하여 타이머 동작을 제어하고 타이머가 구동되면 1초간격으로 LED 가 점멸하도록 했습니다.

#include "MsTimer2.h"    // Timer를 사용하기위한 헤더 선언 

#define     LED_ON          0
#define     LED_OFF         1

const int LED_CONT   = 1 ;
const int Timer_CONT = 2 ;      

boolean LED_Status = false ;     // LED 의 현재 상태 Flag 
boolean timerStatus = false ;    // 타이머 동작 여부 상태 Flag
//--------------------------------------------------------------------------------
void setup() 
{
    MsTimer2::set(1000, Timer_Event);      // 타이머 설정 : 1000msec, 구동 함수 선언  
	
	pinMode(LED_CONT, OUTPUT) ;
	pinMode(Timer_CONT, INPUT) ;           // toggle switch를 사용한 입력 
	
	digitalWrite(LED_CONT, LED_OFF);  
}
//--------------------------------------------------------------------------------
void loop() 
{
	int input = digitalRead(Timer_CONT) ;
	
	if(input == 1)
	{
		if(timerStatus == false)
		{		
			MsTimer2::start();  			// 타이머 동작 시작 
			timerStatus = true ;
		}
	}
	else
	{
		if(timerStatus == true)
		{		
			MsTimer2::stop();                // 타이머 동작 멈출
			timerStatus = false ;
		}
	}
}
//--------------------------------------------------------------------------------
void Timer_Event()  
{
    /* Timer Event : 1초에 한번씩 동작 */
    
	if(LED_Status)
	{
		digitalWrite(LED_CONT, LED_OFF);  
	}
	else
	{
		digitalWrite(LED_CONT, LED_ON);  
	}
	
	LED_Status = !LED_Status ;
}
//--------------------------------------------------------------------------------

아두이노 타이머 테스트
타이머 테스트 회로

반응형
반응형

아두이노 MPU에 내장되어 있는 EEP Rom 메모리에 데이타를 읽고 쓸수 있는 함수입니다.

정수형 데이타를 저장하거나 읽을 수 있도록 만들었습니다. 

하드웨어의 간단한 파라메터 값이나 보드의 어드레스 정보등을 저장하는 용도로 사용할 수 있습니다.

#include <EEPROM.h>

#define   FIRST_ADDRESS     0
#define   SECOND_ADDRESS    2

int EEPROM_Read(int Address)
{
	int result = 0  ;
	int temp ;

	result = EEPROM.read(Address+1) ;
	result <<= 8 ;
	temp = EEPROM.read(Address) ;

	result = result | temp ;  

	return result ;
}

void EEPROM_Write(int Address, int Value)
{
	char temp ;
	
	temp = 0x00ff & Value ;
	EEPROM.update(Address, temp) ;

	Value >>= 8 ;

	temp = 0x00ff & Value ;
	EEPROM.update(Address+1, temp) ; 
}


위의 함수들은 정수형 데이타를 저장하거나 읽어내는 용도이기 때문에 어드레스 설정을 할 경우 주의가 필요합니다. 

EEPROM의 번지는 바이트 단위이기 때문에 정수형 데이타는 2개의 번지를 점유하게 됨으로 그레 맞추어 번지를 설정 하여야 합니다.

 

 

반응형
반응형

이벤트 생성 part-2 에서는 MyTimer 클래스를 만들게 됩니다. 

타이머에 시간(초단위)을 설정하고 시작을 누르면 해당시간이 지나면 이벤트를 발생시키는 예제 입니다. 타이머 클래스 내부에 Thread 를 이용하여 시간의 흐름을 감지하도록 코딩되어 있습니다.

 

public class MyTimer
{
    public delegate void EventHandler(object sender, EventArgs e);
    public event EventHandler? OnTimeoutHandler = null;
    public int time {set; get;}    // Unit is sec 

    public MyTimer(int time)
    {
        this.time = time;
    }

    public void start()
    {
        Thread myThread = new Thread(run);
        myThread.Start();  // Thread 동작
    }

    private void run()   // 타이머 동작 함수 
    {
        var timeout = time;
        while(true)
        {
            Thread.Sleep(1000);
            if (--timeout <= 0) break; 
        }

        if(OnTimeoutHandler is not null) OnTimeoutHandler(this, new EventArgs());
        // 타이머 동작 완료가 되면 이벤트 함수를 호출합니다.
    }
}

 

사용방법은 아래와 같습니다. 

    public partial class Form1 : Form
    {
        MyTimer myTimer = new MyTimer(10);   // 10초 타이머 객체 생성 
        public Form1()
        {
            InitializeComponent();
            myTimer.OnTimeoutHandler += timeout_event;  // 이벤트 실행 함수 등록 
        }

        private void timeout_event(object sender, EventArgs e)
        {
            MessageBox.Show("Timeout Message..");  // 타이머 종료시 메시지 출력
        }

        private void button1_Click(object sender, EventArgs e)
        {
            myTimer.start();   // 타이머 시작 
        }
    }

 

반응형
반응형

객체 내에서 발생하는 어떤 사건에 대해 이벤트를 발생시키는 코드를 만들기 위해 인터넷을 검색해 봤는데 하나같이 뭔가 2% 부족한 부분이 있는것 같아서 이참에 간단한 예제를 하나 만들어 보았습니다. 

 

part-1에서는 MyText 라는 객체를 생성하고 객체의 Text 가 변경되면 이벤트가 발생하는 형식으로 예제를 구성했습니다.

 

아래는 MyText 라는 클래스입니다.

public class MyText
{
    public delegate void EventHandler(object sender, EventArgs e);  // 이벤트 발생을 위한 함수 형식의 델리게이트 선언

    private string text = "";
    public string Text
    {
        get { return text; }
        set
        {
            text = value;
            if(OnTextChangedHandler != null)
            {
                OnTextChangedHandler(this, new EventArgs());  // Text 가 변경될 경우 이벤트 함수 실행
            }
        }
    }

    public event EventHandler? OnTextChangedHandler = null;  // 이벤트 함수 핸들러 선언
}


이제 위의 클래스를 이용해서 실제 이벤트를 발생시키는 코드를 만들어 봅니다. 

폼에 버튼 하나와 TextBox 하나를 올려 놓고 테스트를 해 보았습니다. 

    public partial class Form1 : Form
    {
        MyText myText = new MyText();   // MyText 의 객체를 생성한다. 
        public Form1()
        {
            InitializeComponent();

            myText.OnTextChangedHandler += text_Changed;  // 객체내의 Text가 변경되었을 때 수행할 이벤트 함수를 등록한다.
        }

        private void text_Changed(object sender, EventArgs e) // 이벤트 함수 구현 부분
        {
            textBox1.Text = myText.Text;   // MyText 객체의 Text를 TextBox 에 쓴다.
        }

        private void button1_Click(object sender, EventArgs e)
        {
            myText.Text = "test";  // 버튼을 클릭하면 MyText 객체의 Text를 변경한다.
        }
    }

 

 

반응형
반응형

part-2 에서는 part-1에서 사용된 방법에서 좀더 직관적으로 코드를 작성하는 방법을 설명합니다. 

저장되는 데이타 형식은 동일하지만 코드를 생성하거나 분석하는데 있어 좀더 직관적으로 보일 수 있습니다.

코딩량도 많이 줄어 듭니다. 

private bool saveConfigData(string FileName)
{
	bool result = true ;

	try
	{
 		var jsonLIVParam = new JObject()
		{
			{"Start Current", 0},
			{"Stop Current", 100},
			{"Step Current", 0.1},
			{"Array", new JArray { 10, 20, 100 }}
		};

		var LIVObject = new JObject()
		{
			{"LIV Test", jsonLIVParam}
		};

		using (System.IO.StreamWriter file = new System.IO.StreamWriter(FileName, false))
		{
			file.WriteLine(LIVObject.ToString());
		}
	}
	catch
	{
		result = false ;
	}
    
	return result ;
}

private bool loadConfigData(string FileName)
{
    bool result = true ;
    int index = 0 ;

	try
	{
		string text = System.IO.File.ReadAllText(FileName);
		JObject jobj = JObject.Parse(text); //문자를 객체화

		var startCurrent = int.Parse(jobj["LIV Test"]["Start Current"].ToString()) ;
		var stopCurrent = int.Parse(jobj["LIV Test"]["Stop Current"].ToString()) ;
		var stopCurrent = float.Parse(jobj["LIV Test"]["Step Current"].ToString()) ;

		int[] arrayValue = new int[3] ;

		foreach(var elememts in jobj["LIV Test"]["Array"])
		{
			arrayValue[index++] = (int)elememts ;
		}
	}
	catch
	{
		result = false ;
	}
    
	return result ;
}
반응형
반응형

일본 Contec 사의 GPIB 통신 카드인 GP-IB(PCI)F 를 사용하기 위한 Class 입니다. C++ 로 제작되어서 제공되는 DLL 라이브러리를 사용합니다. Contec 사에서는 C#을 위한 별도의 라이브러리는 제공을 안하고 DLL을 사용한 예제 코드만 제공합니다. 

APIGPIB1.dll
0.18MB

DLL 파일은 올려둔 파일을 사용하시거나 제공받은 CD에서 드라이버를 설치하시면 찾을 수 있습니다. 

여기서는 통신에 꼭 필요한 기능만 멤버 함수로 만들었습니다. 필요한 부분은 더 추가하셔서 만들어 쓰시면 되겠습니다. 

using System;
using System.Text;
using System.Runtime.InteropServices;

namespace CGpibModule
{
    public class CContecGpib
    {
        [DllImport("apigpib1.dll")] static extern uint GpIni();
		[DllImport("apigpib1.dll")] static extern uint GpIfc(uint IfcTime);
		[DllImport("apigpib1.dll")] static extern uint GpRen();
		[DllImport("apigpib1.dll")] static extern uint GpResetren();
		[DllImport("apigpib1.dll")] static extern uint GpTalk(uint[] Cmd, uint Srlen, string Srbuf);
        [DllImport("apigpib1.dll")] static extern uint GpTalk(uint[] Cmd, uint Srlen, byte[] Srbufb);
		[DllImport("apigpib1.dll")] static extern uint GpListen(uint[] Cmd, ref uint Srlen, StringBuilder Srbuf);
        [DllImport("apigpib1.dll")] static extern uint GpListen(uint[] Cmd, ref uint Srlen, byte[] Srbufb);
        [DllImport("apigpib1.dll")] static extern uint GpPoll(uint[] Cmd, uint[] Pstb);
		[DllImport("apigpib1.dll")] static extern uint GpSrq(uint Eoi);
		[DllImport("apigpib1.dll")] static extern uint GpStb(uint Stb);
		[DllImport("apigpib1.dll")] static extern uint GpDelim(uint Delim, uint Eoi);
		[DllImport("apigpib1.dll")] static extern uint GpTimeout(uint Timeout);
		[DllImport("apigpib1.dll")] static extern uint GpChkstb(ref uint Stb, ref uint Eoi);
		[DllImport("apigpib1.dll")] static extern uint GpReadreg(uint Reg, ref uint Preg);
		[DllImport("apigpib1.dll")] static extern uint GpDma(uint Dmamode, uint Dmach);
		[DllImport("apigpib1.dll")] static extern uint GpExit();
		[DllImport("apigpib1.dll")] static extern uint GpComand(uint[] Cmd);
		[DllImport("apigpib1.dll")] static extern uint GpDmainuse();
		[DllImport("apigpib1.dll")] static extern uint GpStstop(uint Stp);
		[DllImport("apigpib1.dll")] static extern uint GpDmastop();
		[DllImport("apigpib1.dll")] static extern uint GpPpollmode(uint Pmode);
		[DllImport("apigpib1.dll")] static extern uint GpStppoll(uint[] Cmd, uint Stppu);
		[DllImport("apigpib1.dll")] static extern uint GpExppoll(ref uint Pprdata);
		[DllImport("apigpib1.dll")] static extern uint GpStwait(uint Buscode);
		[DllImport("apigpib1.dll")] static extern uint GpWaittime(uint Timeout);
		[DllImport("apigpib1.dll")] static extern uint GpReadbus(ref uint Bussta);
		[DllImport("apigpib1.dll")] static extern uint GpSfile(uint[] Cmd, uint Srlen, string Fname);
		[DllImport("apigpib1.dll")] static extern uint GpRfile(uint[] Cmd, uint Srlen, string Fname);
		[DllImport("apigpib1.dll")] static extern uint GpSdc(uint Adr);
		[DllImport("apigpib1.dll")] static extern uint GpDcl();
		[DllImport("apigpib1.dll")] static extern uint GpGet(uint Adr);
		[DllImport("apigpib1.dll")] static extern uint GpGtl(uint Adr);
		[DllImport("apigpib1.dll")] static extern uint GpLlo();
		[DllImport("apigpib1.dll")] static extern uint GpTct(uint Adr);
		[DllImport("apigpib1.dll")] static extern uint GpCrst(uint Adr);
		[DllImport("apigpib1.dll")] static extern uint GpCopc(uint Adr);
		[DllImport("apigpib1.dll")] static extern uint GpCwai(uint Adr);
		[DllImport("apigpib1.dll")] static extern uint GpCcls(uint Adr);
		[DllImport("apigpib1.dll")] static extern uint GpCtrg(uint Adr);
		[DllImport("apigpib1.dll")] static extern uint GpCpre(uint Adr, uint Stb);
		[DllImport("apigpib1.dll")] static extern uint GpCese(uint Adr, uint Stb);
		[DllImport("apigpib1.dll")] static extern uint GpCsre(uint Adr, uint Stb);
		[DllImport("apigpib1.dll")] static extern uint GpQidn(uint Adr, ref uint Srlen, StringBuilder Srbuf);
		[DllImport("apigpib1.dll")] static extern uint GpQopt(uint Adr, ref uint Srlen, StringBuilder Srbuf);
		[DllImport("apigpib1.dll")] static extern uint GpQpud(uint Adr, ref uint Srlen, StringBuilder Srbuf);
		[DllImport("apigpib1.dll")] static extern uint GpQrdt(uint Adr, ref uint Srlen, StringBuilder Srbuf);
		[DllImport("apigpib1.dll")] static extern uint GpQcal(uint Adr, ref uint Srlen, StringBuilder Srbuf);
		[DllImport("apigpib1.dll")] static extern uint GpQlrn(uint Adr, ref uint Srlen, StringBuilder Srbuf);
		[DllImport("apigpib1.dll")] static extern uint GpQtst(uint Adr, ref uint Srlen, StringBuilder Srbuf);
		[DllImport("apigpib1.dll")] static extern uint GpQopc(uint Adr, ref uint Srlen, StringBuilder Srbuf);
		[DllImport("apigpib1.dll")] static extern uint GpQemc(uint Adr, ref uint Srlen, StringBuilder Srbuf);
		[DllImport("apigpib1.dll")] static extern uint GpQgmc(uint Adr, ref uint Srlen, StringBuilder Srbuf);
		[DllImport("apigpib1.dll")] static extern uint GpQlmc(uint Adr, ref uint Srlen, StringBuilder Srbuf);
		[DllImport("apigpib1.dll")] static extern uint GpQist(uint Adr, ref uint Srlen, StringBuilder Srbuf);
		[DllImport("apigpib1.dll")] static extern uint GpQpre(uint Adr, ref uint Srlen, StringBuilder Srbuf);
		[DllImport("apigpib1.dll")] static extern uint GpQese(uint Adr, ref uint Srlen, StringBuilder Srbuf);
		[DllImport("apigpib1.dll")] static extern uint GpQesr(uint Adr, ref uint Srlen, StringBuilder Srbuf);
		[DllImport("apigpib1.dll")] static extern uint GpQpsc(uint Adr, ref uint Srlen, StringBuilder Srbuf);
		[DllImport("apigpib1.dll")] static extern uint GpQsre(uint Adr, ref uint Srlen, StringBuilder Srbuf);
		[DllImport("apigpib1.dll")] static extern uint GpQstb(uint Adr, ref uint Srlen, StringBuilder Srbuf);
		[DllImport("apigpib1.dll")] static extern uint GpQddt(uint Adr, ref uint Srlen, StringBuilder Srbuf);
		[DllImport("apigpib1.dll")] static extern uint GpTaLaBit(uint TaLaSts);
		[DllImport("apigpib1.dll")] static extern uint GpBoardsts(uint Reg, ref uint Preg);
		[DllImport("apigpib1.dll")] static extern uint GpSrqEvent(int hWnd, ushort wMsg, uint SrqOn);
		[DllImport("apigpib1.dll")] static extern uint GpSrqEventEx(int hWnd, ushort wMsg, uint SrqOn);
		[DllImport("apigpib1.dll")] static extern uint GpSrqOn();
		[DllImport("apigpib1.dll")] static extern uint GpDevFind(uint[] Fstb);
		[DllImport("apigpib1.dll")] static extern byte GpInpB(short Port);
		[DllImport("apigpib1.dll")] static extern short GpInpW(short Port);
		[DllImport("apigpib1.dll")] static extern int  GpInpD(short Port);
		[DllImport("apigpib1.dll")] static extern byte GpOutB(short Port, byte Dat);
		[DllImport("apigpib1.dll")] static extern short GpOutW(short Port, short Dat);
		[DllImport("apigpib1.dll")] static extern int  GpOutD(short Port, int Dat);
		[DllImport("apigpib1.dll")] static extern uint GpSetEvent(uint EventOn);
		[DllImport("apigpib1.dll")] static extern uint GpSetEventSrq(int hWnd, ushort wMsg, uint SrqOn);
		[DllImport("apigpib1.dll")] static extern uint GpSetEventDet(int hWnd, ushort wMsg, uint DetOn);
		[DllImport("apigpib1.dll")] static extern uint GpSetEventDec(int hWnd, ushort wMsg, uint DetOn);
		[DllImport("apigpib1.dll")] static extern uint GpSetEventIfc(int hWnd, ushort wMsg, uint IfcOn);
		[DllImport("apigpib1.dll")] static extern uint GpEnableNextEvent();
		[DllImport("apigpib1.dll")] static extern uint GpSrqEx(uint Stb, uint SrqFlag, uint EoiFlag);
		[DllImport("apigpib1.dll")] static extern uint GpUpperCode(uint UpperCode);
		[DllImport("apigpib1.dll")] static extern uint GpCnvSettings(string HeaderStr, string UnitStr, string SepStr, uint SfxFlag);
		[DllImport("apigpib1.dll")] static extern uint GpCnvSettingsToStr(uint PlusFlag, uint Digit, uint CutDown);
		[DllImport("apigpib1.dll")] static extern uint GpCnvStrToDbl(string Str, ref double DblData);
		[DllImport("apigpib1.dll")] static extern uint GpCnvStrToDblArray(string Str, double[] DblData, ref uint ArraySize);
		[DllImport("apigpib1.dll")] static extern uint GpCnvStrToFlt(string Str, ref float FltData);
		[DllImport("apigpib1.dll")] static extern uint GpCnvStrToFltArray(string Str, float[] FltData, ref uint ArraySize);
		[DllImport("apigpib1.dll")] static extern uint GpCnvDblToStr(StringBuilder Str, ref uint StrSize, double DblData);
		[DllImport("apigpib1.dll")] static extern uint GpCnvDblArrayToStr(StringBuilder Str, ref uint StrSize, double[] DblData, uint ArraySize);
		[DllImport("apigpib1.dll")] static extern uint GpCnvFltToStr(StringBuilder Str, ref uint StrSize, float FltData);
		[DllImport("apigpib1.dll")] static extern uint GpCnvFltArrayToStr(StringBuilder Str, ref uint StrSize, float[] FltData, uint ArraySize);
		[DllImport("apigpib1.dll")] static extern uint GpPollEx(uint[] Cmd, uint[] Pstb, uint[] Psrq);
		[DllImport("apigpib1.dll")] static extern uint GpSlowMode(uint SlowTime);
		[DllImport("apigpib1.dll")] static extern uint GpCnvCvSettings(uint Settings);
		[DllImport("apigpib1.dll")] static extern uint GpCnvCvi(byte[] Str, ref short ShtData);
		[DllImport("apigpib1.dll")] static extern uint GpCnvCviArray(byte[] Str, short[] ShtData, uint ArraySize);
		[DllImport("apigpib1.dll")] static extern uint GpCnvCvs(byte[] Str, ref float FltData);
		[DllImport("apigpib1.dll")] static extern uint GpCnvCvsArray(byte[] Str, float[] FltData, uint ArraySize);
		[DllImport("apigpib1.dll")] static extern uint GpCnvCvd(byte[] Str, ref double DblData);
		[DllImport("apigpib1.dll")] static extern uint GpCnvCvdArray(byte[] Str, double[] DblData, uint ArraySize);
		[DllImport("apigpib1.dll")] static extern uint GpTalkEx(uint[] Cmd, ref uint Srlen, string Srbuf);
        [DllImport("apigpib1.dll")] static extern uint GpTalkEx(uint[] Cmd, ref uint Srlen, byte[] Srbufb);
		[DllImport("apigpib1.dll")] static extern uint GpListenEx(uint[] Cmd, ref uint Srlen, StringBuilder Srbuf);
        [DllImport("apigpib1.dll")] static extern uint GpListenEx(uint[] Cmd, ref uint Srlen, byte[] Srbufb);
		[DllImport("apigpib1.dll")] static extern uint GpTalkAsync(uint[] Cmd, ref uint Srlen, string Srbuf);
        [DllImport("apigpib1.dll")] static extern uint GpTalkAsync(uint[] Cmd, ref uint Srlen, byte[] Srbufb);
		[DllImport("apigpib1.dll")] static extern uint GpListenAsync(uint[] Cmd, ref uint Srlen, StringBuilder Srbuf);
        [DllImport("apigpib1.dll")] static extern uint GpListenAsync(uint[] Cmd, ref uint Srlen, byte[] Srbufb);
        [DllImport("apigpib1.dll")] static extern uint GpCommandAsync(uint[] Cmd);
		[DllImport("apigpib1.dll")] static extern uint GpCheckAsync(uint WaitFlag, ref uint ErrCode);
		[DllImport("apigpib1.dll")] static extern uint GpStopAsync();
		[DllImport("apigpib1.dll")] static extern uint GpDevFindEx(short Pad, short Sad, ref short Lstn);
		[DllImport("apigpib1.dll")] static extern uint GpBoardstsEx(uint SetFlag, uint Reg, ref uint Preg);
		[DllImport("apigpib1.dll")] static extern uint GpSmoothMode(uint Mode);

        public CContecGpib() { }

        public Int32 Initialize() 
        {
            uint Ret;
            uint Master = 0;

            Ret = GpExit();                                  // Keep off initialize repeat
            Ret = GpIni();                                   // GP-IB initialize
            if ((Ret & 0xFF) != 0) return 1;

            GpBoardsts(0x0a, ref Master);                    // Get Master/Slave mode

            if (Master == 0)
            {
                Ret = GpIfc(1);                           // Default Ifctime = 1 
                if ((Ret & 0xFF) != 0) return 1;

                Ret = GpRen();
                if ((Ret & 0xFF) != 0) return 1;
            }
                                 
            Ret = GpTimeout(10000);                      // 10000ms (Default)
            if ((Ret & 0xFF) != 0) return 1;

            return 0;
        }

        public void Close() 
        {
            uint Master=0;                                        // Master/Slave mode flag
            uint Ret;
            uint[] Cmd = new uint[32];

            Ret = GpBoardsts(0x0a, ref Master);              // Mode check
            if (Ret == 80) return;                              // If found error then not doing 

            if (Master == 0)
            {                                                   // When mode is Master
                Cmd[0] = 2;                                     // Command count
                Cmd[1] = 0x3f;                                  // Unlisten / UNL
                Cmd[2] = 0x5f;                                  // UnTalken / UNT
                Ret = GpComand(Cmd);                         // Send command
                Ret = GpResetren();                          // Cancel remote
            }
            Ret = GpExit();
        }
        public Int32 GpibPrint(UInt32 address, string command) 
        {
            Int32 result = 0 ;
            uint MyAddr=0;
            uint[] Cmd = new uint[16];
            uint Ret;

            Ret = GpBoardsts(0x08, ref MyAddr);
            Cmd[0] = 2;
            Cmd[1] = MyAddr;
            Cmd[2] = address;

            Ret = GpTalk(Cmd, (uint)command.Length, command);

            if (Ret >= 3) result = 1 ;

            return result ;
        }
        public Int32 GpibInput(UInt32 address, StringBuilder readData)
        {
            Int32 result = 0 ;
            uint MyAddr = 0, srlen = 10000;
            uint[] Cmd = new uint[16];
            uint Ret;

            Ret = GpBoardsts(0x08, ref MyAddr);
            Cmd[0] = 2;
            Cmd[1] = address;
            Cmd[2] = MyAddr;
            Ret = GpListen(Cmd, ref srlen, readData);

            if (Ret >= 3) result = 1 ;

            return result;
        }

        public Int32 GpibInput(UInt32 address, byte[] readData)
        {
            Int32 result = 0 ;
            uint MyAddr = 0, srlen = (uint)readData.Length ;
            uint[] Cmd = new uint[16];
            uint Ret;

            Ret = GpBoardsts(0x08, ref MyAddr);
            Cmd[0] = 2;
            Cmd[1] = address;
            Cmd[2] = MyAddr;
            Ret = GpListen(Cmd, ref srlen, readData);

            if (Ret >= 3) result = 1 ;

            return result;
        }
    }
}

 

반응형
반응형

아두이노에 버튼이 여러개 있을 경우 각각의 버튼에 대한 입력을 체크하여 각각의 버튼에 대한 입력 처리만 하게됩니다. 

예를 들어 버튼이 3개가 있다면 3가지 경우의 입력만 처리하게 됩니다.  

 

하지만 적은 수의 버튼으로 좀더 많은 경우의 처리를 하는 방법이 있습니다. 바로 bit field 기능을 이용하면 됩니다. 

비트 필드를 구성하게 되면 두개 이상의 키가 동시에 눌리는 경우도 하나의 입력값으로 인식하여 처리 루틴을 만드는 것이 가능합니다.

만일 버튼이 3개 있다면 최대 7가지의 경우로 조합하여 입력 처리를 할 수 있습니다. 

 

#define U08  unsigned char 

union BUTTON_STATE   // 버튼입력 상태에 대한 비트필드 공용체
{
  U08 State ;
  struct
  {
    int UP_BUTTON    : 1 ;
    int DOWN_BUTTON  : 1 ;
    int LEFT_BUTTON  : 1 ;
    int RIGHT_BUTTON : 1 ;   
    int EMPTY        : 4 ;
  } ;
} ;

const int upButton    = 2;    
const int downButton  = 3;       
const int leftButton  = 4;
const int rightButton = 5;

BUTTON_STATE btn_state ;

void setup()
{
  // initialize the buttons' inputs:
  pinMode(upButton, INPUT);      
  pinMode(downButton, INPUT);      
  pinMode(leftButton, INPUT);      
  pinMode(rightButton, INPUT);     
}

U08 Read_Button()
{
   btn_state.UP_BUTTON    = digitalRead(upButton); 
   btn_state.DOWN_BUTTON  = digitalRead(downButton);
   btn_state.LEFT_BUTTON  = digitalRead(leftButton);
   btn_state.RIGHT_BUTTON = digitalRead(rightButton);

   return btn_state.State ;
}
 
void loop()
{
    U08 Key_State ;

    Key_State = Read_Button() ;

    switch(Key_State)
    {
        case 0x01 : function1() ; break ;  // UP_BUTTON
        case 0x02 : function2() ; break ;  // DOWN_BUTTON
        case 0x04 : function3() ; break ;  // LEFT_BUTTON
        case 0x08 : function4() ; break ;  // RIGHT_BUTTON
        case 0x03 : function5() ; break ;  // UP_BUTTON & DOWN_BUTTON
    }
}
반응형

+ Recent posts