2013-05-24 5 views
0

현재 Arduino와 로봇 공학 프로젝트를 진행 중입니다. 서로 다른 시간에 다른 방법으로 직렬 포트에 액세스하려고합니다.다른 방법으로 직렬 포트 데이터에 액세스하는 방법

예를 들어, 나는 시간 t1에서 ADC를 읽고 시간 t2에서 모터 전류를 얻고 싶다. 그래서 나는 서로 다른 크기의 int 배열을 반환해야하는 readADC() 및 motorCurrents() 메서드를 만듭니다. 받은 직렬 포트 데이터는 다음과 같습니다.

private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) 
{ 
    int n = serialPort1.BytesToRead; 

    serialPort1.Read(data, 0, data.Length); 
} 

나는 모든 관련 코딩을 Arduino 측에서 구현했습니다. 직렬 포트도 설정했습니다. 내가 마찬가지로

private int[] ReadADC() 
{ 
    string input = "AN\n"; // This is the command for reading the ADC on the Wildthumper board. 
    serialPort1.Write(input); 

    // The Wildthumper now sends 11 bytes, the last of which is '*' and the first 
    // 10 bytes are the data that I want. I need to combine two bytes together 
    // from data received and make five values and return it. 
    for (int i = 0; i < 5; i++) 
    { 
     adcValues[i] = data[0 + i * 2] <<8+ data[1 + i * 2]; 
    } 

    return adcValues; 
    // Where data is the bytes received on serial port; 
} 

C#에서 다음 명령을 실행해야합니다 모든

private int[] getMotorCurrents() 
    { 
     string input = "MC\n"; // Wildthumper board command 
     serialPort1.Write(input); 

     // The Wildthumper now sends 5 bytes with the last one being '*'. 
     // And the first four bytes are the data that I want. 

     for (int i = 0; i < 2; i++) 
     { 
      MotorCurrents[i] = data[0 + i * 2] <<8 +data[1 + i * 2]; 
     } 

     return MotorCurrents; 
    } 

첫째, 나에게 전송 된 바이트의 수를 변경할 수 있습니다. 그렇다면 어떻게 전역 변수를 사용할 수 있습니까? 데이터 (위에 주어진 직렬 데이터를 저장하는 데 사용되는 변수)의 경우?

+0

하지 마십시오 * 지금 * 읽기() 메소드의 반환 값을 무시합니다. 그것은 당신이 원하는 바가 아닙니다. 직렬 포트가 느리면 일반적으로 1 또는 2 바이트 만 가져옵니다. 대신 ReadLine()을 사용하는 것을 고려하면 NewLine 문자열이 수신 될 때까지 차단됩니다. 또는 전체 응답을 얻을 때까지 데이터를 처리하지 마십시오. –

+0

@HansPassant 저는 실제로 Read()의 값을 무시하지 않습니다. 내가 보낸 모든 바이트를 읽었습니다. 몇 번에 걸쳐 readADC()가 보낸 11 바이트를 10과 1 또는 8과 3 등으로 나눕니다. –

+0

스 니펫에서는이를 무시합니다. BytesToRead를 사용하여 무언가를하고 싶었지만이를 포기했다. 그리고 그것은 당신이 묘사하는 것과 똑같이 잘못되고, 다음 Read() 호출에서 나머지는 줄어 듭니다. 그것을 무시하지 마십시오. –

답변

0

수신 된 데이터가 발생할 때 전역 변수를 만들어 데이터를 저장해야합니다. 이것은 어렵지 않습니다. 여기

코드 예제 :

public class myclass{ 
    public string arduinoData = ""; 

    private void serialPort1_DataReceived(
     object sender, System.IO.Ports.SerialDataReceivedEventArgs e) 
    { 
     this.arduinoData = serialPort1.ReadLine(data, 0, data.Length); 
    } 
    //....The rest of your code, such as main methods, etc... 
} 
관련 문제