I have this program that is reading the test string from a textbox and convert it to a byte array that makeup data to be diplayed on a screen. I am getting very close. The code can currently pull the text, convert it to a char array, and then replace the zeros in the byte array with useful data from a 2 dimensional array that contains 5 bits for all the letters of the alphabet. I am have a problem though. The code only seems to run once. If I click the button a second time I end up with an “indexOutOfRange exception unhandled.” Also it only seems to work for one letter at a time
EX: if I type “A” it will display, but if I type “AA” I get the same error.
Here is the WordArray[]
byte[,] Letters = new byte[18, 5] { { 63, 72, 72, 63, 0 },
{ 127, 73, 73, 54, 0 },
{ 63, 72, 72, 63, 0 },
{ 127, 73, 73, 54, 0 },
{ 63, 72, 72, 63, 0 },
{ 127, 73, 73, 54, 0 },
{ 63, 72, 72, 63, 0 },
{ 127, 73, 73, 54, 0 },
{ 63, 72, 72, 63, 0 },
{ 127, 73, 73, 54, 0 },
{ 63, 72, 72, 63, 0 },
{ 127, 73, 73, 54, 0 },
{ 63, 72, 72, 63, 0 },
{ 127, 73, 73, 54, 0 },
{ 63, 72, 72, 63, 0 },
{ 127, 73, 73, 54, 0 },
{ 63, 72, 72, 63, 0 },
{ 127, 73, 73, 54, 0 } };
Here is the click_button method:
int Aindex = 0;
int LettersIndex = 0;
private void SendButton_Click(object sender, EventArgs e)
{
WordIndex = 0;
if (Aindex > 0)
{
Aindex = 0;
}
string CurrentTextString = textBox1.Text;
char[] charArray = CurrentTextString.ToCharArray();
if (textBox1.Text == "")
{
}
else
{
foreach (char c in charArray)
{
int index = 0;
CharAsciiArray[index] = Convert.ToChar((Convert.ToInt32(c)));
textBox2.Text += CharAsciiArray[index] + " ";
charCount++;
index++;
}
for (int NumberofBytes = 0; NumberofBytes < charCount; NumberofBytes++)
{
LettersIndex = 0;
// int currentChar = CharAsciiArray[index] - 65;
//textBox2.Text += currentChar;
int currentCharAscii = (CharAsciiArray[Aindex]);
int currentChar = currentCharAscii - 'A';
for (int NumberofBits = 0; NumberofBits < 5; NumberofBits++)
{
// textBox2.Text += currentChar;
WordArray[WordIndex + 3] = Letters[currentChar, LettersIndex];
textBox2.Text += WordArray[WordIndex] + " ";
LettersIndex++;
WordIndex++;
}
Aindex++;
}
SendingData = true;
//SendNextByte();
serialPort1.Write(WordArray, 0, WordArray.Length);
}
}
In the following loop
You apparently want to increase the index on each iteration but you’re resetting index to 0 every time.
Besides that, make up your mind on what pattern you want to follow when naming your variables. For instance:
Why is
AIndexnotAnIndexand how would you name the next index?AnotherIndex? Does it need to be global? Why doescharArraystart with a lowercase c andNumberOfByteswith an uppercase N? Write code as if you would have to explain it to your wife / husband (who knows?) and it’ll be easier to maintain / debug.