16,473
社区成员
发帖
与我相关
我的任务
分享
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include "ftd2xx.h"
int main(int argc, char* argv[])
{
FT_HANDLE fthandle;
FT_STATUS res;
LONG COMPORT;
char COMx[5];
int n;
DCB dcb;
HANDLE hCommPort;
BOOL fSuccess;
/***********************************************************************
//Find the com port that has been assigned to your device.
/***********************************************************************/
res = FT_Open(0, &fthandle);
if(res != FT_OK){
printf("opening failed! with error %d\n", res);
return 1;
}
res = FT_GetComPortNumber(fthandle,&COMPORT);
if(res != FT_OK){
printf("get com port failed %d\n", res);
return 1;
}
if (COMPORT == -1){
printf("no com port installed \n");
}
else{
printf("com port number is %d\n", COMPORT);
}
FT_Close(fthandle);
/********************************************************/
// Open the com port assigned to your device
/********************************************************/
n = sprintf_s(COMx, "COM%d",COMPORT);
hCommPort = CreateFile(
COMx,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL
);
if (hCommPort == INVALID_HANDLE_VALUE)
{
printf("Help - failed to open\n");
return(1);
}
printf("Hello World!\n");
/********************************************************/
// Configure the UART interface parameters
/********************************************************/
fSuccess = GetCommState(hCommPort, &dcb);
if (!fSuccess)
{
printf("GetCommStateFailed \n", GetLastError());
return (2);
}
//set parameters.
dcb.BaudRate = 8000000;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
fSuccess = SetCommState(hCommPort, &dcb);
if (!fSuccess)
{
printf("SetCommStateFailed \n", GetLastError());
return (3);
}
printf("Port configured \n");
/********************************************************/
// Writing data to the USB to UART converter
/********************************************************/
DWORD dwwritten = 0, dwErr;
char data_out[12] = "HELLO WORLD";
DWORD w_data_len = 12;
fSuccess = WriteFile(hCommPort, &data_out, w_data_len, &dwwritten, NULL);
if (!fSuccess)
{
dwErr = GetLastError();
printf("Write Failed \n", GetLastError());
return (4);
}
printf("bytes written = %d\n", dwwritten);
/********************************************************/
//Reading data from the USB to UART converter
/********************************************************/
char buf[256];
DWORD dwRead;
memset(buf,0,256);
if (ReadFile(hCommPort, buf, w_data_len, &dwRead, NULL))
{
printf("data read = %s\n", buf);
}
/********************************************************/
//Closing the device at the end of the program
/********************************************************/
CloseHandle(hCommPort);
getchar();
return 0;
}