ElseTU
ElseTU

Reputation: 9

Serial communication c++ SerialPort-Class

First of all - I'm a student from Germany, so please excuse my bad english. At the moment, I'm working on a Project which target is to controll servo Motors on an arduino board by Serial communication through xbee modules. So now I'm studying the SerialPort but got Problems by using the write().

My plan is to send integer values seperated by a commata through my Serial Port. Visual Studio Reports an error and says that there is no Argument type that fits. I really don't know how to handle this problem, because I'm completely new to this whole programming topic.

   #include <iostream>
using namespace std;
#using <System.dll>;

using namespace System;
using namespace System::IO::Ports;
using namespace System::Threading;

int main() {
    unsigned char values[2] = { 50, 120 };
    SerialPort^ mySerialPort = gcnew SerialPort("COM3");
        mySerialPort->BaudRate = 9600;
        mySerialPort->Open();
while (true) {

            mySerialPort->Write(values);

    }
}

Upvotes: 0

Views: 8703

Answers (1)

EgorBr
EgorBr

Reputation: 64

You can fix it this way:

#include <iostream>
using namespace std;
#using <System.dll>

using namespace System;
using namespace System::IO::Ports;
using namespace System::Threading;

int main() {
  // Managed array
  cli::array<unsigned char> ^values = { 50, 120 };
  SerialPort^ mySerialPort = gcnew SerialPort("COM3");
  mySerialPort->BaudRate = 9600;
  mySerialPort->Open();
  while (true) {

    // some work with values goes here...

    // We should specify buffer offset and length
    mySerialPort->Write(values, 0, values->Length);
  }
}

As you noticed, you can also send this data as string:

mySerialPort->WriteLine(String::Format("val1 = {0}; val2 = {1}", values[0], values[1]));

But be warned that mySerialPort->Write() sends raw bytes, and mySerialPort->WriteLine() sends each character as a single byte. For instance:

cli::array<unsigned char> ^buffer = {123};

// Send one single byte 0x7b
mySerialPort->Write(buffer, 0, buffer->Length);

// Send 3 bytes (0x49, 0x50, 0x51)
mySerialPort->WriteLine(String::Format("{0}", buffer[0]));

Upvotes: 1

Related Questions