我需要读取电子天平的重量,我可以发送命令来恢复我的体重,但天平没有响应。我开心 这是旧款HB TRADE。
这是为Windows 10开发的,以前有一个用Visual Fox Pro制作的代码,但是很老,客户想要升级。
显然我可以连接到天平并发送命令来恢复我的体重,但天平永远不会响应。
private async void Button_Click(object sender, RoutedEventArgs e)
{
try
{
var deviceSelector = SerialDevice.GetDeviceSelector("COM5");
var devices = await DeviceInformation.FindAllAsync(deviceSelector);
if (devices.Any())
{
var deviceId = devices.First().Id;
serialPort = await SerialDevice.FromIdAsync(deviceId);
if (serialPort != null)
{
serialPort.BaudRate = 9600;
serialPort.StopBits = SerialStopBitCount.One;
serialPort.DataBits = 8;
serialPort.Parity = SerialParity.None;
serialPort.Handshake = SerialHandshake.None;
dataWriteObject = new DataWriter(serialPort.OutputStream);
await WriteAsync(WriteCancellationTokenSource.Token);
dataReaderObject = new DataReader(serialPort.InputStream);
await ReadAsync(ReadCancellationTokenSource.Token);
}
}
}
catch (Exception ex)
{
TxtRespuesta.Text = ex.Message;
}
finally
{
serialPort.Dispose();
serialPort = null;
}
}
private async Task ReadAsync(CancellationToken cancellationToken)
{
Task<UInt32> loadAsyncTask;
uint ReadBufferLength = 1024;
// Don't start any IO if we canceled the task
lock (ReadCancelLock)
{
cancellationToken.ThrowIfCancellationRequested();
// Cancellation Token will be used so we can stop the task operation explicitly
// The completion function should still be called so that we can properly handle a canceled task
dataReaderObject.InputStreamOptions = InputStreamOptions.Partial;
loadAsyncTask = dataReaderObject.LoadAsync(ReadBufferLength).AsTask(cancellationToken);
}
UInt32 bytesRead = await loadAsyncTask;
if (bytesRead > 0)
{
TxtRespuesta.Text += dataReaderObject.ReadString(bytesRead);
}
//rootPage.NotifyUser("Read completed - " + bytesRead.ToString() + " bytes were read", NotifyType.StatusMessage);
}
private async Task WriteAsync(CancellationToken cancellationToken)
{
Task<UInt32> storeAsyncTask;
String cadena = "@GI;23;";
char[] buffer = cadena.ToArray();
cadena.CopyTo(0, buffer, 0, cadena.Length);
String InputString = new string(buffer);
dataWriteObject.WriteString(InputString);
// Don't start any IO if we canceled the task
lock (WriteCancelLock)
{
cancellationToken.ThrowIfCancellationRequested();
storeAsyncTask = dataWriteObject.StoreAsync().AsTask(cancellationToken);
}
UInt32 bytesWritten = await storeAsyncTask;
if (bytesWritten > 0)
{
}
//rootPage.NotifyUser("Write completed - " + bytesWritten.ToString() + " bytes written", NotifyType.StatusMessage);
}
答案 0 :(得分:0)
首先,您的应用程序必须声明它正在应用程序清单中进行串行通信:
<DeviceCapability Name="serialcommunication">
<Device Id="vidpid:xxxx xxxx">
<Function Type="name:serialPort"/>
</Device>
</DeviceCapability>
这可能是缺失的吗?