У меня есть проблема с чтением данных о температуре в реальном времени от датчика DS18B20+ на устройстве DLPIO20. Я использую обертку ftd2xx.dll .net (версия 1.0.14) на платформе Windows (согласно ссылке: http://www.ftdichip.com/support/softwar ... 1.0.14.zip) . < /p>
Приложение для тестирования, чтобы продемонстрировать проблему ниже. < /p>
2.2.1 При довольно постоянной температуре окружающей среды (допустим, 20 ° C) имеют несколько чтений температуры, чтобы увидеть последовательные результаты в режиме отладки (точка разрыва в конце цикла чтения температуры на строка 55). < /p>
2.2.2 />2.3. Запустите еще два или три цикла температурных показаний. < /P>
Первое чтение, которое я получаю после того Третьи циклы чтения У меня есть реалистичные результаты около 28 ° C. Я выпустил Convert Command перед прочтением, я сразу же получаю результат в режиме реального времени. С помощью этой программы и управляемого класса обертки .NET я также отправляю команду конверта перед чтением, но безрезультатно. Большая разница в том, что IO20DEMO не использует класс управляемой обертки, но использует ftd2xx.lib напрямую. < /P>
Не могли бы вы помочь мне понять, что я здесь делаю не так? Как я могу получить данные о температуре в реальном времени, используя управляемый класс обертки .NET? < /p>
Ваша помощь очень ценится! < /p>
///
/// Program for DLPIO20 device to read temperature data from DS18B20+
/// digital temperature sensor attached to one of its channels.
///
class Program
{
static void Main(string[] args)
{
FTDI FtdiWrapper = null;
// DLPIO20 channel where the DS18B20+ sensor is attached
byte sensorChannel = 0x06;
try
{
// create new instance of the FTDI device class
FtdiWrapper = ConnectToFirstFtdiDevice();
if (FtdiWrapper == null || !FtdiWrapper.IsOpen)
{
throw new Exception("Error connection to FTDI device.");
}
// didn't helped at all for 85dC issue
//PurgeRxBuffer(FtdiWrapper);
// helped avoid 85dC issue at first read
ConvertSensorData(FtdiWrapper, sensorChannel);
// send read sensor command
float? degreesC = null;
for (int i = 0; i < 100; i++)
{
// calling Convert just before ReadTemperatureSensor causes
// IO20Demo (using FTD2XX.lib) to return real temperature
// but it doesn't help when using .NET wrapper
ConvertSensorData(FtdiWrapper, sensorChannel);
// other failed attempts to get real time sensor data
// previous value returned:
//PurgeRxBuffer(FtdiWrapper);
// read but only initiate conversion on success
degreesC = ReadTemperatureSensor(FtdiWrapper, sensorChannel);
if (degreesC == null)
{
throw new Exception("Error converting raw data to Celsius");
}
var message = string.Format("Success! {0}° Celsius.", degreesC);
Console.WriteLine(message);
}
Console.WriteLine("Press any key to exit ...");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.WriteLine("Press any key to exit ...");
Console.ReadKey();
}
finally
{
if (FtdiWrapper != null && FtdiWrapper.IsOpen)
{
FtdiWrapper.Close();
}
}
}
< /code>
Это код, используемый для подключения к первым устройству FTDI < /p>
static private FTDI ConnectToFirstFtdiDevice()
{
FTDI FtdiWrapper = new FTDI();
UInt32 ftdiDeviceCount = 0;
FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OTHER_ERROR;
// Determine the number of FTDI devices connected to the machine
ftStatus = FtdiWrapper.GetNumberOfDevices(ref ftdiDeviceCount);
// Check status
if (ftStatus != FTDI.FT_STATUS.FT_OK)
throw new Exception(string.Format("Error after GetNumberOfDevices(), ftStatus: {0}", ftStatus));
if (ftdiDeviceCount == 0)
throw new Exception("No FTDI device found");
// Allocate storage for device info list
var ftdiDeviceList = new FTDI.FT_DEVICE_INFO_NODE[ftdiDeviceCount];
// Populate our device list
ftStatus = FtdiWrapper.GetDeviceList(ftdiDeviceList);
if (ftStatus == FTDI.FT_STATUS.FT_OK)
{
// Open first device in our list by serial number
ftStatus = FtdiWrapper.OpenBySerialNumber(ftdiDeviceList[0].SerialNumber);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
throw new Exception(string.Format("Error opening first device, ftStatus: {0}", ftStatus));
ftStatus = FtdiWrapper.SetBaudRate(9600);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
throw new Exception(string.Format("Error to set Baud rate, ftStatus: {0}", ftStatus));
// Set data characteristics - Data bits, Stop bits, Parity
ftStatus = FtdiWrapper.SetDataCharacteristics(FTDI.FT_DATA_BITS.FT_BITS_8, FTDI.FT_STOP_BITS.FT_STOP_BITS_1, FTDI.FT_PARITY.FT_PARITY_NONE);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
throw new Exception(string.Format("Error to set data characteristics , ftStatus: {0}", ftStatus));
// Set flow control - set RTS/CTS flow control
ftStatus = FtdiWrapper.SetFlowControl(FTDI.FT_FLOW_CONTROL.FT_FLOW_RTS_CTS, 0x11, 0x13);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
throw new Exception(string.Format("Error to set flow control , ftStatus: {0}", ftStatus));
// Set read timeout to 5 seconds, write timeout to infinite
ftStatus = FtdiWrapper.SetTimeouts(5000, 0);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
throw new Exception(string.Format("Error to set timeouts, ftStatus: {0}", ftStatus));
}
return FtdiWrapper;
}
< /code>
Метод преобразования необработанных данных датчика < /p>
static private void ConvertSensorData(FTDI FtdiWrapper, byte sensorChannel)
{
FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OTHER_ERROR;
UInt32 numBytesWritten = 0;
byte[] convertCommand = new byte[] { 0x03, 0x40, sensorChannel };
ftStatus = FtdiWrapper.Write(convertCommand, convertCommand.Length, ref numBytesWritten);
bool isAllBytesWritten = numBytesWritten == convertCommand.Length;
if (ftStatus != FTDI.FT_STATUS.FT_OK && isAllBytesWritten)
throw new Exception(string.Format("Failed to write Convert command to device; Status: {0}, isAllBytesWritten: {1}", ftStatus.ToString(), isAllBytesWritten));
}
< /code>
Метод считывания температуры датчика < /p>
static private float? ReadTemperatureSensor(FTDI FtdiWrapper, byte sensorChannel)
{
float? degreesC = null;
FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OTHER_ERROR;
UInt32 numBytesWritten = 0;
byte[] readSensorCommand = new byte[] { 0x03, 0x41, sensorChannel };
ftStatus = FtdiWrapper.Write(readSensorCommand, readSensorCommand.Length, ref numBytesWritten);
bool isAllBytesWritten = numBytesWritten == readSensorCommand.Length;
if (ftStatus != FTDI.FT_STATUS.FT_OK && isAllBytesWritten)
throw new Exception(string.Format("Failed to write readSensorCommand to device; Status: {0}, isAllBytesWritten: {1}", ftStatus.ToString(), isAllBytesWritten));
// Read back response
UInt32 numBytesAvailable = 0;
UInt32 numBytesExpected = 2; // read sensor command expected to return 2 bytes
while (numBytesAvailable == 0)
{
Thread.Sleep(40); // value of 40 taken from DLP IO20 demo solution
ftStatus = FtdiWrapper.GetRxBytesAvailable(ref numBytesAvailable);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
throw new Exception("Failed to get number of bytes available to read; error: " + ftStatus);
} //while (numBytesAvailable < numBytesExpected);
if (numBytesAvailable != numBytesExpected)
throw new Exception("Error: Invalid data in buffer. (1350)");
UInt32 numBytesRead = 0;
byte[] rawData = new byte[numBytesExpected];
ftStatus = FtdiWrapper.Read(rawData, numBytesAvailable, ref numBytesRead);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
throw new Exception("Failed to read data from device after command has been sent; error: " + ftStatus);
//convert raw response data to degrees Celsius
degreesC = ConvertTemperature(rawData);
return degreesC;
}
< /code>
Метод для очистки буфера передачи < /p>
static private void PurgeRxBuffer(FTDI FtdiWrapper)
{
UInt32 numBytesAvailable = 0;
UInt32 numBytesRead = 0;
FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OTHER_ERROR;
byte[] rx = new byte[1001]; //allocate large enough space to read from device
Thread.Sleep(5);
ftStatus = FtdiWrapper.GetRxBytesAvailable(ref numBytesAvailable);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
throw new Exception("Failed to get number of bytes available to read; error: " + ftStatus);
if (numBytesAvailable > 1000)
numBytesAvailable = 1000;
while (numBytesAvailable > 0)
{
//read the data from the buffer
numBytesRead = 0;
ftStatus = FtdiWrapper.Read(rx, numBytesAvailable, ref numBytesRead);
ftStatus = FtdiWrapper.GetRxBytesAvailable(ref numBytesAvailable);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
throw new Exception("Failed to get number of bytes available to read; error: " + ftStatus);
if (numBytesAvailable > 1000)
numBytesAvailable = 1000;
Thread.Sleep(5);
}
}
< /code>
Метод преобразования температуры из необработанных данных в Celsius < /p>
static private float? ConvertTemperature(byte[] rawData)
{
float? tempCelsius = null;
bool isnegative = false;
//check input
if (rawData.Length < 2)
throw new Exception(string.Format("Input parameter rawData for temperature conversion must be 2 bytes, actual length is: {0}", rawData.Length));
int temp = rawData[0] | (rawData[1]
Подробнее здесь: https://stackoverflow.com/questions/189 ... ature-data
Использование FTD2XX_NET Управляемое .NET CRAPPER Class для чтения данных о температуре в реальном времени ⇐ C#
Место общения программистов C#
1739009320
Anonymous
У меня есть проблема с чтением данных о температуре в реальном времени от датчика DS18B20+ на устройстве DLPIO20. Я использую обертку ftd2xx.dll .net (версия 1.0.14) на платформе Windows (согласно ссылке: http://www.ftdichip.com/support/softwareexamples/codeexamples/csharp/ftd2xx_net_v1.0.14.zip) . < /p>
Приложение для тестирования, чтобы продемонстрировать проблему ниже. < /p>
2.2.1 При довольно постоянной температуре окружающей среды (допустим, 20 ° C) имеют несколько чтений температуры, чтобы увидеть последовательные результаты в режиме отладки (точка разрыва в конце цикла чтения температуры на строка 55). < /p>
2.2.2 />2.3. Запустите еще два или три цикла температурных показаний. < /P>
Первое чтение, которое я получаю после того Третьи циклы чтения У меня есть реалистичные результаты около 28 ° C. Я выпустил Convert Command перед прочтением, я сразу же получаю результат в режиме реального времени. С помощью этой программы и управляемого класса обертки .NET я также отправляю команду конверта перед чтением, но безрезультатно. Большая разница в том, что IO20DEMO не использует класс управляемой обертки, но использует ftd2xx.lib напрямую. < /P>
Не могли бы вы помочь мне понять, что я здесь делаю не так? Как я могу получить данные о температуре в реальном времени, используя управляемый класс обертки .NET? < /p>
Ваша помощь очень ценится! < /p>
///
/// Program for DLPIO20 device to read temperature data from DS18B20+
/// digital temperature sensor attached to one of its channels.
///
class Program
{
static void Main(string[] args)
{
FTDI FtdiWrapper = null;
// DLPIO20 channel where the DS18B20+ sensor is attached
byte sensorChannel = 0x06;
try
{
// create new instance of the FTDI device class
FtdiWrapper = ConnectToFirstFtdiDevice();
if (FtdiWrapper == null || !FtdiWrapper.IsOpen)
{
throw new Exception("Error connection to FTDI device.");
}
// didn't helped at all for 85dC issue
//PurgeRxBuffer(FtdiWrapper);
// helped avoid 85dC issue at first read
ConvertSensorData(FtdiWrapper, sensorChannel);
// send read sensor command
float? degreesC = null;
for (int i = 0; i < 100; i++)
{
// calling Convert just before ReadTemperatureSensor causes
// IO20Demo (using FTD2XX.lib) to return real temperature
// but it doesn't help when using .NET wrapper
ConvertSensorData(FtdiWrapper, sensorChannel);
// other failed attempts to get real time sensor data
// previous value returned:
//PurgeRxBuffer(FtdiWrapper);
// read but only initiate conversion on success
degreesC = ReadTemperatureSensor(FtdiWrapper, sensorChannel);
if (degreesC == null)
{
throw new Exception("Error converting raw data to Celsius");
}
var message = string.Format("Success! {0}° Celsius.", degreesC);
Console.WriteLine(message);
}
Console.WriteLine("Press any key to exit ...");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.WriteLine("Press any key to exit ...");
Console.ReadKey();
}
finally
{
if (FtdiWrapper != null && FtdiWrapper.IsOpen)
{
FtdiWrapper.Close();
}
}
}
< /code>
Это код, используемый для подключения к первым устройству FTDI < /p>
static private FTDI ConnectToFirstFtdiDevice()
{
FTDI FtdiWrapper = new FTDI();
UInt32 ftdiDeviceCount = 0;
FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OTHER_ERROR;
// Determine the number of FTDI devices connected to the machine
ftStatus = FtdiWrapper.GetNumberOfDevices(ref ftdiDeviceCount);
// Check status
if (ftStatus != FTDI.FT_STATUS.FT_OK)
throw new Exception(string.Format("Error after GetNumberOfDevices(), ftStatus: {0}", ftStatus));
if (ftdiDeviceCount == 0)
throw new Exception("No FTDI device found");
// Allocate storage for device info list
var ftdiDeviceList = new FTDI.FT_DEVICE_INFO_NODE[ftdiDeviceCount];
// Populate our device list
ftStatus = FtdiWrapper.GetDeviceList(ftdiDeviceList);
if (ftStatus == FTDI.FT_STATUS.FT_OK)
{
// Open first device in our list by serial number
ftStatus = FtdiWrapper.OpenBySerialNumber(ftdiDeviceList[0].SerialNumber);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
throw new Exception(string.Format("Error opening first device, ftStatus: {0}", ftStatus));
ftStatus = FtdiWrapper.SetBaudRate(9600);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
throw new Exception(string.Format("Error to set Baud rate, ftStatus: {0}", ftStatus));
// Set data characteristics - Data bits, Stop bits, Parity
ftStatus = FtdiWrapper.SetDataCharacteristics(FTDI.FT_DATA_BITS.FT_BITS_8, FTDI.FT_STOP_BITS.FT_STOP_BITS_1, FTDI.FT_PARITY.FT_PARITY_NONE);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
throw new Exception(string.Format("Error to set data characteristics , ftStatus: {0}", ftStatus));
// Set flow control - set RTS/CTS flow control
ftStatus = FtdiWrapper.SetFlowControl(FTDI.FT_FLOW_CONTROL.FT_FLOW_RTS_CTS, 0x11, 0x13);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
throw new Exception(string.Format("Error to set flow control , ftStatus: {0}", ftStatus));
// Set read timeout to 5 seconds, write timeout to infinite
ftStatus = FtdiWrapper.SetTimeouts(5000, 0);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
throw new Exception(string.Format("Error to set timeouts, ftStatus: {0}", ftStatus));
}
return FtdiWrapper;
}
< /code>
Метод преобразования необработанных данных датчика < /p>
static private void ConvertSensorData(FTDI FtdiWrapper, byte sensorChannel)
{
FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OTHER_ERROR;
UInt32 numBytesWritten = 0;
byte[] convertCommand = new byte[] { 0x03, 0x40, sensorChannel };
ftStatus = FtdiWrapper.Write(convertCommand, convertCommand.Length, ref numBytesWritten);
bool isAllBytesWritten = numBytesWritten == convertCommand.Length;
if (ftStatus != FTDI.FT_STATUS.FT_OK && isAllBytesWritten)
throw new Exception(string.Format("Failed to write Convert command to device; Status: {0}, isAllBytesWritten: {1}", ftStatus.ToString(), isAllBytesWritten));
}
< /code>
Метод считывания температуры датчика < /p>
static private float? ReadTemperatureSensor(FTDI FtdiWrapper, byte sensorChannel)
{
float? degreesC = null;
FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OTHER_ERROR;
UInt32 numBytesWritten = 0;
byte[] readSensorCommand = new byte[] { 0x03, 0x41, sensorChannel };
ftStatus = FtdiWrapper.Write(readSensorCommand, readSensorCommand.Length, ref numBytesWritten);
bool isAllBytesWritten = numBytesWritten == readSensorCommand.Length;
if (ftStatus != FTDI.FT_STATUS.FT_OK && isAllBytesWritten)
throw new Exception(string.Format("Failed to write readSensorCommand to device; Status: {0}, isAllBytesWritten: {1}", ftStatus.ToString(), isAllBytesWritten));
// Read back response
UInt32 numBytesAvailable = 0;
UInt32 numBytesExpected = 2; // read sensor command expected to return 2 bytes
while (numBytesAvailable == 0)
{
Thread.Sleep(40); // value of 40 taken from DLP IO20 demo solution
ftStatus = FtdiWrapper.GetRxBytesAvailable(ref numBytesAvailable);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
throw new Exception("Failed to get number of bytes available to read; error: " + ftStatus);
} //while (numBytesAvailable < numBytesExpected);
if (numBytesAvailable != numBytesExpected)
throw new Exception("Error: Invalid data in buffer. (1350)");
UInt32 numBytesRead = 0;
byte[] rawData = new byte[numBytesExpected];
ftStatus = FtdiWrapper.Read(rawData, numBytesAvailable, ref numBytesRead);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
throw new Exception("Failed to read data from device after command has been sent; error: " + ftStatus);
//convert raw response data to degrees Celsius
degreesC = ConvertTemperature(rawData);
return degreesC;
}
< /code>
Метод для очистки буфера передачи < /p>
static private void PurgeRxBuffer(FTDI FtdiWrapper)
{
UInt32 numBytesAvailable = 0;
UInt32 numBytesRead = 0;
FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OTHER_ERROR;
byte[] rx = new byte[1001]; //allocate large enough space to read from device
Thread.Sleep(5);
ftStatus = FtdiWrapper.GetRxBytesAvailable(ref numBytesAvailable);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
throw new Exception("Failed to get number of bytes available to read; error: " + ftStatus);
if (numBytesAvailable > 1000)
numBytesAvailable = 1000;
while (numBytesAvailable > 0)
{
//read the data from the buffer
numBytesRead = 0;
ftStatus = FtdiWrapper.Read(rx, numBytesAvailable, ref numBytesRead);
ftStatus = FtdiWrapper.GetRxBytesAvailable(ref numBytesAvailable);
if (ftStatus != FTDI.FT_STATUS.FT_OK)
throw new Exception("Failed to get number of bytes available to read; error: " + ftStatus);
if (numBytesAvailable > 1000)
numBytesAvailable = 1000;
Thread.Sleep(5);
}
}
< /code>
Метод преобразования температуры из необработанных данных в Celsius < /p>
static private float? ConvertTemperature(byte[] rawData)
{
float? tempCelsius = null;
bool isnegative = false;
//check input
if (rawData.Length < 2)
throw new Exception(string.Format("Input parameter rawData for temperature conversion must be 2 bytes, actual length is: {0}", rawData.Length));
int temp = rawData[0] | (rawData[1]
Подробнее здесь: [url]https://stackoverflow.com/questions/18900862/using-ftd2xx-net-managed-net-wrapper-class-to-read-real-time-temperature-data[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия