シリアルポート経由で送信しようとすると、Linuxは行末の文字(0x0Aと0x0D)のようなものをしばしば使いこなすでしょう。実際にバイナリデータであり、行末の文字ではない場合に問題になることがあります。
シリアルポートを正しく設定してから数バイトを送受信する方法を示すスニペットfrom Pololuがあります。特にtcsetattr
と呼ぶ部分に注意してください。
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#ifdef _WIN32
#define O_NOCTTY 0
#else
#include <termios.h>
#endif
// Gets the position of a Maestro channel.
// See the "Serial Servo Commands" section of the user's guide.
int maestroGetPosition(int fd, unsigned char channel)
{
unsigned char command[] = {0x90, channel};
if(write(fd, command, sizeof(command)) == -1)
{
perror("error writing");
return -1;
}
unsigned char response[2];
if(read(fd,response,2) != 2)
{
perror("error reading");
return -1;
}
return response[0] + 256*response[1];
}
// Sets the target of a Maestro channel.
// See the "Serial Servo Commands" section of the user's guide.
// The units of 'target' are quarter-microseconds.
int maestroSetTarget(int fd, unsigned char channel, unsigned short target)
{
unsigned char command[] = {0x84, channel, target & 0x7F, target >> 7 & 0x7F};
if (write(fd, command, sizeof(command)) == -1)
{
perror("error writing");
return -1;
}
return 0;
}
int main()
{
const char * device = "/dev/ttyACM0"; // Linux
int fd = open(device, O_RDWR | O_NOCTTY);
if (fd == -1)
{
perror(device);
return 1;
}
#ifdef _WIN32
_setmode(fd, _O_BINARY);
#else
struct termios options;
tcgetattr(fd, &options);
options.c_iflag &= ~(INLCR | IGNCR | ICRNL | IXON | IXOFF);
options.c_oflag &= ~(ONLCR | OCRNL);
options.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
tcsetattr(fd, TCSANOW, &options);
#endif
int position = maestroGetPosition(fd, 0);
printf("Current position is %d.\n", position);
int target = (position < 6000) ? 7000 : 5000;
printf("Setting target to %d (%d us).\n", target, target/4);
maestroSetTarget(fd, 0, target);
close(fd);
return 0;
}
stty
コマンドラインユーティリティでも同じことを行うことができます。
* termios * **(a)**が非正規(aka * raw *)モードで正しく構成され、**(b)**がソフトウェアフロー制御が無効になっていることを確認するだけで済みます。あなたは詳細ではない。このデータ転送を実行するためにどのソフトウェアを使用していますか?なぜポートを正しく設定しないのですか? – sawdust
'stty -F/dev/ttyACM0 raw'が動作する可能性があります(転送プログラムがこれらの属性も設定していない場合)。 'raw'パラメータの前にハイフンはありません。それはスイッチではなくパラメータ設定です。 '-raw'と入力すると、このコマンドの目的が無効になります。 – sawdust
私はソフトウェアを持っていないので、バイトを書き込むために/ dev/ttyACMxにecho -ne "\ xXY"を使用し、ポートから読み込み用にログファイルにcat/dev/ttyACMを使用します。受信したデータを見るために、xxd経由でログファイルを開きます。設定はsttyによって行われます。 私は生のパラメータが解決策であると思う、ありがとう! – JirkaRCK