I am using Raspberry Pi 3 Model B. I have installed Windows 10 IOT Core in it. I am using Visual Studio 15 to develop a UWP App in C# and deployed an App on the board. It reads GPS data through UART pins 8 and 10 from Neo6mv2 GPS module and displays the raw data in a text box. Simple.
I have configured the UART port using the function below:
public async void UART_Config()
{
string selector = SerialDevice.GetDeviceSelector("UART0");
DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(selector);
if (devices.Count > 0)
{
DeviceInformation deviceInfo = devices[0];
serialDevice = await SerialDevice.FromIdAsync(deviceInfo.Id);
dataReader = new DataReader(serialDevice.InputStream);
dataWriter = new DataWriter(serialDevice.OutputStream);
bytesToRead = await dataReader.LoadAsync(maxReadLength);
}
else
{
}
}
I read the data inside a tick Timer function which is called at an interval of 1 second. The GPS sensor gives a series of string lines with '\n' at the end of each line. So I am separating the lines using a while loop and updating each line in the text box Location.Text.
public void AcQ_Tick(object sender, object e)
{
rxBuffer = ""; // string rxBuffer
try
{
while (dataReader.ReadString(1) != "\n")
{
rxBuffer += dataReader.ReadString(1);
}
Location.Text = rxBuffer;
}
catch (Exception e1)
{
Status.Text = e1.ToString();
}
}
The problem is, after a few lines of successful data output every time I reload the program, the raspberry pi throws an exception at "dataReader.ReadString(1) " function inside while loop . It never reads data after that.
The exception thrown which looks like:
"System.Runtime.InteropServices.COMException (0x8000000B): The operation attempted to access data outside the valid range\r\n\r\nThe operation attempted to access data outside the valid range\r\n\r\n at Windows.Storage.Streams.DataReader.ReadString(UInt32 codeUnitCount)\r\n"
I checked the output of the GPS sensor through putty. I can see the values coming continuously. So no problem with the sensor. Since I can see a few lines of data from the raspberry pi at the beginning, I understood that there is no wrong in connection.
Anyone know where I went wrong?
Thank you for your time.
Please try with the following code. Keep reading until we consume the complete stream.
public void AcQ_Tick(object sender, object e)
{
rxBuffer = ""; // string rxBuffer
try
{
while (dataReader.UnconsumedBufferLength > 0)
{
uint bytesToRead = dataReader.ReadUInt32();
rxBuffer += dataReader.ReadString(bytesToRead);
if( strRead.EndWith("\n") )
{
rxBuffer += dataReader.ReadString(1);
}
}
Location.Text = rxBuffer;
}
catch (Exception e1)
{
Status.Text = e1.ToString();
}
}
The call to ReadString requires a length of "code units" to read. This is the reason each string is preceded by its length when "on the wire". There is an complete sample about RPi Using The UART with C#, you can google it.
User contributions licensed under CC BY-SA 3.0