私は大学のプロジェクトをやっていて、大きな問題に直面しています。C# Visual Studio 2010 で UI を開発しています。シリアル接続を開き、マイクロ コントローラーにいくつかの値を入力する必要があります。基本的に、0x78A26F などの 24 ビット アドレス (3 バイト) を持つノードがあります。
テキストボックスのGUIでユーザーから入力を受け取ります。ユーザーはこの 78A26F を入力し、シリアル ポートが次のデータ 0x6F 0xA2 0x78 を送信するようにします。
しかし、ユーザー入力は文字列として保存され、シリアル接続を介して送信すると、ASCII が送信されます (例: 0x37 0x38 0x41 0x32 0x36 0x46)。uC で処理を行い、0x30 と 0x39 の間の場合は 0x30 を減算するか、0x41 と 0x46 の間の場合は 0x37 を減算するためのいくつかのチェックを実行できます。しかし、私はこの計算に uC を使用したくありません。正しい HEX 値を送信するために、GUI c# にいくつかのアルゴリズムを実装したいと考えています。というわけで以下のプログラムを書きました。しかし、私はエラーが発生しています。「値が符号なしバイトに対して大きすぎるか小さすぎます。」(data[2 - i] = Convert.ToByte(x*16 + y))を示すコード行。
私はこの問題を理解することができず、これは決して起こらないはずなので、今はうんざりしています。このコードまたは他のアルゴリズム/メソッドのいずれかで、誰かがこの点で私を助けることができれば、私は本当に感謝しています. uCにアルゴリズムを実装したくないです。
ありがとう
マリーハ
/***********************************************************************/
/*The code for opening the serial connection and converting it appropriately*/
/***********************************************************************/
byte[] conversion()
{
string text = label16.Text.ToUpper(); // if user enters not capital letters
byte[] data = new byte[3];
int x, y;
bool valid;
for (int i = 2; i >= 0; i--)
{
valid = true;
x = (Convert.ToInt32(Convert.ToChar(text[2 * i + 1])));
y = (Convert.ToInt32(Convert.ToChar(text[2 * i]))); // I want to first send the 0x6F then 0xA2 and finally 0x78. ToChar is so that i can check for A-F
if(x >= 48 || x <= 57) // i,e it is already a number
x = Convert.ToInt32(text[2 * i + 1]);
else if (x >= 65 || x <= 70) // it is between A-F
x = x - 55; // in case of A, i get 10
else // any other value i.e greater than F or any other.
{
valid = false;
break;
}
if (y >= 48 || y <= 57) // same for y
y = Convert.ToInt32(text[2 * i]);
else if (y >= 65 || y <= 70)
y = y - 55;
else
{
valid = false;
break;
}
if (valid == true)
data[2 - i] = Convert.ToByte(x*16 + y); // max will be 15*16 + 15 = 255 which should be OK for convert.ToByte.
}
return data;
}
void serial(byte[] text)
{
SerialPort serialPort1 = new SerialPort();
//configuring the serial port
serialPort1.PortName = "COM1";
serialPort1.BaudRate = 9600;
serialPort1.DataBits = 8;
serialPort1.Parity = Parity.None;
serialPort1.StopBits = StopBits.One;
//opening the serial port
serialPort1.Open();
//write data to serial port
serialPort1.Write(text, 0, 3);
//close the port
serialPort1.Close();
}
/***********************************************************************/
private void button3_Click(object sender, EventArgs e)
{
byte[] data = conversion();
serial(data);
}