/// <summary> /// Create a USB Relay Device and open it by the serial number /// </summary> /// <param name="serialNumber">Device serial number</param> public UsbRelay8( String serialNumber ) { // Open the relay device by serial number // The serial number is always uniques, so the safest _device = new FTDI(); _status = _device.OpenBySerialNumber(serialNumber); if (_status != FTDI.FT_STATUS.FT_OK) { throw new UsbRelayDeviceNotFoundException(); } // Set the baud rate _status = _device.SetBaudRate(BaudRate); if (_status != FTDI.FT_STATUS.FT_OK) { throw new UsbRelayConfigurationException(); } // Set the bit mode _status = _device.SetBitMode(BitMask, BitMode); if (_status != FTDI.FT_STATUS.FT_OK) { throw new UsbRelayConfigurationException(); } // Clear all the relays // Note: From the Data Sheet, when in Sync Mode you can // only read the interface pins when writing. So start // start out with all the values cleared. _values = 0x00; SetRelays(_values); }
//------------------------------------------------------------------------------------------------- public FTDI.FT_STATUS InitializeFTDI() { // Create new instance of the FTDI device class SPI_Device= new FTDI(); uint ftdiDeviceCount = 0; int i; Initialize_SPI_Constants(); // Determine the number of FTDI devices connected to the machine ftStatus = SPI_Device.GetNumberOfDevices(ref ftdiDeviceCount); // Check status if (ftStatus != FTDI.FT_STATUS.FT_OK) { return (ftStatus); } // If no devices available, return if (ftdiDeviceCount == 0) { ftStatus = FTDI.FT_STATUS.FT_DEVICE_NOT_FOUND; return (ftStatus); } // Allocate storage for device info list FTDI.FT_DEVICE_INFO_NODE[] ftdiDeviceList = new FTDI.FT_DEVICE_INFO_NODE[ftdiDeviceCount]; // Populate our device list ftStatus = SPI_Device.GetDeviceList(ftdiDeviceList); if (ftStatus == FTDI.FT_STATUS.FT_OK) { for (i = 0; i < ftdiDeviceCount; i++) { //MessageBox.Show("Device Index: " + i.ToString()); //MessageBox.Show("Flags: " + String.Format("{0:x}", ftdiDeviceList[i].Flags)); //MessageBox.Show("Type: " + ftdiDeviceList[i].Type.ToString()); //MessageBox.Show("ID: " + String.Format("{0:x}", ftdiDeviceList[i].ID)); //MessageBox.Show("Location ID: " + String.Format("{0:x}", ftdiDeviceList[i].LocId)); //MessageBox.Show("Serial Number: " + ftdiDeviceList[i].SerialNumber.ToString()); //MessageBox.Show("Description: " + ftdiDeviceList[i].Description.ToString()); //MessageBox.Show(""); } } // Open first device in our list by serial number ftStatus = SPI_Device.OpenBySerialNumber(ftdiDeviceList[0].SerialNumber); if (ftStatus != FTDI.FT_STATUS.FT_OK) { return (ftStatus); } // Set latency timer ftStatus = SPI_Device.SetLatency(2); if (ftStatus != FTDI.FT_STATUS.FT_OK) { return (ftStatus); } // Reset the controller ftStatus = SPI_Device.SetBitMode(0, 0); if (ftStatus != FTDI.FT_STATUS.FT_OK) { return (ftStatus); } // Set synchronous bit bang mode ftStatus = SPI_Device.SetBitMode(FT232Routputs, 4); // Set device to mode 4 and sets outputs if (ftStatus != FTDI.FT_STATUS.FT_OK) { return (ftStatus); } // Set baud rate/bit clock settings ftStatus = SPI_Device.SetBaudRate(3000000); if (ftStatus != FTDI.FT_STATUS.FT_OK) { return (ftStatus); } presetShiftRegisterOutputs(); return (ftStatus); }
public FTDIComms() { // Create new instance of the FTDI device class myFtdiDevice = new FTDI(); // Determine the number of FTDI devices connected to the machine ftStatus = myFtdiDevice.GetNumberOfDevices(ref ftdiDeviceCount); // Check status if (ftStatus == FTDI.FT_STATUS.FT_OK) { Console.WriteLine("Number of FTDI devices: " + this.ftdiDeviceCount); Console.WriteLine(""); } else { Console.WriteLine("Failed to get number of devices (error " + this.ftStatus + ")"); return; } // If no devices available, return if (ftdiDeviceCount == 0) { Console.WriteLine("Failed to get number of devices (error " + this.ftStatus + ")"); } }
//------------------------------------------------------------------------------------------------- public FTDI.FT_STATUS checkPinState(ref byte pins) { ftStatus = SPI_Device.GetPinStates(ref pins); if (ftStatus != FTDI.FT_STATUS.FT_OK) { return (ftStatus); } return (ftStatus); }
//************************************************ // 装置通信クローズ //************************************************ public bool Close() { // デバイスをクローズする _ftStatus = _myFtdiDevice.Close(); bool result = false; if (_ftStatus == FTDI.FT_STATUS.FT_OK) { result = true; } return result; }
//************************************************ // 装置通信オープン //************************************************ public bool Open() { if (!_myFtdiDevice.IsOpen) { // シリアル番号を指定してデバイスをオープンする _ftStatus = _myFtdiDevice.OpenBySerialNumber("FTYMWDN1"); } bool result = false; if (_ftStatus == FTDI.FT_STATUS.FT_OK) { result = true; } return result; }
/// <summary> /// Find the FDTI chip, connect, set baud to 9600, set sync bit-bang mode /// </summary> /// <returns></returns> public bool connect() { // Determine the number of FTDI devices connected to the machine ftStatus = myFtdiDevice.GetNumberOfDevices(ref ftdiDeviceCount); // Check status if (ftStatus == FTDI.FT_STATUS.FT_OK) { Console.WriteLine("Number of FTDI devices: " + ftdiDeviceCount.ToString()); Console.WriteLine(""); } else { Console.WriteLine("Failed to get number of devices (error " + ftStatus.ToString() + ")"); return false; } if (ftdiDeviceCount == 0) { Console.WriteLine("Relay board not found, please try again"); return false; } else { // Allocate storage for device info list FTDI.FT_DEVICE_INFO_NODE[] ftdiDeviceList = new FTDI.FT_DEVICE_INFO_NODE[ftdiDeviceCount]; // Populate our device list ftStatus = myFtdiDevice.GetDeviceList(ftdiDeviceList); // Open first device in our list by serial number ftStatus = myFtdiDevice.OpenBySerialNumber(ftdiDeviceList[0].SerialNumber); if (ftStatus != FTDI.FT_STATUS.FT_OK) { Console.WriteLine("Error connecting to relay board"); return false; } // Set Baud rate to 9600 ftStatus = myFtdiDevice.SetBaudRate(9600); // Set FT245RL to synchronous bit-bang mode, used on sainsmart relay board myFtdiDevice.SetBitMode(0xFF, FTD2XX_NET.FTDI.FT_BIT_MODES.FT_BIT_MODE_SYNC_BITBANG); // Switch off all the relays myFtdiDevice.Write(startup, 1, ref bytesToSend); return true; } }
public static void Initialize() { String quadcam_serial; while ( true ) { quadcam_serial = WaitForQuadCam(0); // 0 = no timeout ftStatus = Program.ftdiDevice.OpenBySerialNumber(quadcam_serial); if ( ftStatus != FTDI.FT_STATUS.FT_OK ) { continue; } break; } Console.WriteLine("Found QuadCam #" + quadcam_serial); SetAsyncMode(); ftStatus = Program.ftdiDevice.SetLatency(2); // ftStatus = FtdiDevice.SetFlowControl(FTDI.FT_FLOW_CONTROL.FT_FLOW_RTS_CTS, 0, 0); ftStatus = Program.ftdiDevice.SetTimeouts(90, 200); }
public void ReadFromChip(char portName, ReadFunctionType call) { if (portName != 'A' && portName != 'B') throw new Exception("Invalid port name " + portName + ". Should be A or B."); FTDI rdPort = (portName == 'B') ? portB : portA; if (rdPort == null) throw new Exception("No port " + portName + " exists"); if (!rdPort.IsOpen) throw new Exception("Port " + portName + " is closed"); uint numBytesAvailable = 0; DateTime startClock = DateTime.Now; lock (rdPort) { // Nothing will be able to write to the chip until ReadFromChip has returned, // is this the desired behaviour? while (numBytesAvailable <= 0) { // Wait for 2 seconds for data, then throw error if ((DateTime.Now - startClock).TotalSeconds > 2) throw new Exception("2 seconds elapsed with no data. Was data expected?"); System.Threading.Thread.Sleep(20); if ((ftStatus = rdPort.GetRxBytesAvailable(ref numBytesAvailable)) != FTDI.FT_STATUS.FT_OK) { throw new FTDI.FT_EXCEPTION("Failed to get number of available bytes from " + portName + ". err: " + ftStatus.ToString()); } } byte[] readData = new byte[numBytesAvailable]; uint numBytesRead = 0; if ((ftStatus = rdPort.Read(readData, numBytesAvailable, ref numBytesRead)) != FTDI.FT_STATUS.FT_OK) { throw new FTDI.FT_EXCEPTION("Failed to read data from " + portName + ". err: " + ftStatus.ToString()); } if (readData.Length != numBytesRead) throw new Exception("Read length mismatch"); call(portName, readData.ToList()); // Notify all threads of a change in port status System.Threading.Monitor.PulseAll(rdPort); } }
public List<FTDI.FT_DEVICE_INFO_NODE> GetDeviceList() { // Allocate storage for device info list FTDI.FT_DEVICE_INFO_NODE[] ftdiDeviceList = new FTDI.FT_DEVICE_INFO_NODE[ftdiDeviceCount]; // Populate our device list ftStatus = myFtdiDevice.GetDeviceList(ftdiDeviceList); if (ftStatus == FTDI.FT_STATUS.FT_OK) { for (UInt32 i = 0; i < ftdiDeviceCount; i++) { Console.WriteLine("Device Index: " + i); Console.WriteLine("Flags: " + String.Format("{0:x}", ftdiDeviceList[i].Flags)); Console.WriteLine("Type: " + ftdiDeviceList[i].Type); Console.WriteLine("ID: " + String.Format("{0:x}", ftdiDeviceList[i].ID)); Console.WriteLine("Location ID: " + String.Format("{0:x}", ftdiDeviceList[i].LocId)); Console.WriteLine("Serial Number: " + ftdiDeviceList[i].SerialNumber); Console.WriteLine("Description: " + ftdiDeviceList[i].Description); Console.WriteLine(""); } } return ftdiDeviceList.ToList(); }
/// <summary> /// Close the port /// </summary> /// <returns></returns> public FTDI.FT_STATUS Close() { FTDI.FT_STATUS status = _ftdi.Close(); return(status); }
/// <summary> /// Metoda pro pripojeni zarizeni podle serioveho cisla /// </summary> /// <param name="serialNum">Seriove cislo vybraneho zarizeni</param> /// <returns>Vraci status zpravu o uspesnosti pripojeni</returns> public FTDI.FT_STATUS[] openDevice(string serialNum) { FTDI.FT_STATUS[] status = new FTDI.FT_STATUS[4] ; // priprava pole pro ulozeni status zprav pri pripojeni a nastaveni komunikace status[0] = ftDevice.OpenBySerialNumber(serialNum); // otevreni zarizeni podle serioveho cisla status[1] = ftDevice.SetBaudRate(9600); // nastaveni rychloseti prenosu status[2] = ftDevice.SetDataCharacteristics(FTDI.FT_DATA_BITS.FT_BITS_8, FTDI.FT_STOP_BITS.FT_STOP_BITS_2, FTDI.FT_PARITY.FT_PARITY_NONE); // nastaveni parametru komunikace status[3] = ftDevice.SetFlowControl(FTDI.FT_FLOW_CONTROL.FT_FLOW_NONE,0,0); return status; }
internal DeviceConnectionState Connect(bool Emulation, out string Message) { m_Emulation = Emulation; DeviceConnectionState state; Message = ""; m_Stop = false; if (m_Emulation) { IsConnected = true; state = DeviceConnectionState.ConnectionSuccess; return(state); } if (!m_MyFtdiDevice.IsOpen) { IsConnected = false; m_FtStatus = m_MyFtdiDevice.OpenByDescription(DESCRIPTION_NAME); if (m_FtStatus == FTDI.FT_STATUS.FT_OK) { m_FtStatus = m_MyFtdiDevice.SetBaudRate(115200); } if (m_FtStatus == FTDI.FT_STATUS.FT_OK) { m_FtStatus = m_MyFtdiDevice.SetDataCharacteristics(FTDI.FT_DATA_BITS.FT_BITS_8, FTDI.FT_STOP_BITS.FT_STOP_BITS_1, FTDI.FT_PARITY.FT_PARITY_NONE); } if (m_FtStatus == FTDI.FT_STATUS.FT_OK) { m_FtStatus = m_MyFtdiDevice.SetBitMode(DIR_MASK, FTDI.FT_BIT_MODES.FT_BIT_MODE_MPSSE); } if (m_FtStatus == FTDI.FT_STATUS.FT_OK) { LedRedSwitch(false); LedGreenSwitch(false); IsConnected = true; m_FtStatus = m_MyFtdiDevice.GetPinStates(ref m_BitMode); if (m_FtStatus == FTDI.FT_STATUS.FT_OK) { if ((m_BitMode & B2_MASK) == 0 && !m_Buttons[1]) { m_Buttons[1] = true; IsStopButtonPressed = m_Buttons[1]; Cache.Net.CallbackManager.GatewayButtonPressHandler(ComplexButtons.ButtonStopFTDI, m_Buttons[1]); } else if ((m_BitMode & B2_MASK) != 0 && m_Buttons[1]) { m_Buttons[1] = false; IsStopButtonPressed = m_Buttons[1]; Cache.Net.CallbackManager.GatewayButtonPressHandler(ComplexButtons.ButtonStopFTDI, m_Buttons[1]); } } state = DeviceConnectionState.ConnectionSuccess; ThreadPool.QueueUserWorkItem(PoolingRoutine); } else { m_MyFtdiDevice.Close(); Message = "FT status " + m_FtStatus; state = DeviceConnectionState.ConnectionFailed; } } else { state = DeviceConnectionState.ConnectionSuccess; } return(state); }
public void WriteToChip(char portName, List<byte> data) { if (!isOpen) throw new Exception("Ftdi not initialized"); uint bytesWritten = 0; uint bytesWaiting = 1; if (portName == 'A') { var dataReverse = new List<byte>(); dataReverse.InsertRange(0, data); dataReverse.Reverse(); lock (portA) { if ((ftStatus = this.portA.GetTxBytesWaiting(ref bytesWaiting)) != FTDI.FT_STATUS.FT_OK) { throw new FTDI.FT_EXCEPTION("Failed to get number of bytes waiting from port B. err: " + ftStatus.ToString()); } // If only one thread can read/write to the chip this will wait indefinitely. while (bytesWaiting > 0) { System.Threading.Monitor.Wait(portA); if ((ftStatus = this.portA.GetTxBytesWaiting(ref bytesWaiting)) != FTDI.FT_STATUS.FT_OK) { throw new FTDI.FT_EXCEPTION("Failed to get number of bytes waiting from port A. err: " + ftStatus.ToString()); } } if ((ftStatus = this.portA.Write(dataReverse.ToArray(), data.Count, ref bytesWritten)) != FTDI.FT_STATUS.FT_OK) { throw new FTDI.FT_EXCEPTION("Failed to write to port A. err: " + ftStatus.ToString()); } // Notify all threads of a change in port status System.Threading.Monitor.PulseAll(portA); } } else { // end Port A lock (portB) { if ((ftStatus = this.portB.GetTxBytesWaiting(ref bytesWaiting)) != FTDI.FT_STATUS.FT_OK) { throw new FTDI.FT_EXCEPTION("Failed to get number of bytes waiting from port B. err: " + ftStatus.ToString()); } // If only one thread can read/write to the chip this will wait indefinitely. while (bytesWaiting > 0) { System.Threading.Monitor.Wait(portB); if ((ftStatus = this.portB.GetTxBytesWaiting(ref bytesWaiting)) != FTDI.FT_STATUS.FT_OK) { throw new FTDI.FT_EXCEPTION("Failed to get number of bytes waiting from port B. err: " + ftStatus.ToString()); } } if ((ftStatus = this.portB.Write(data.ToArray(), data.Count, ref bytesWritten)) != FTDI.FT_STATUS.FT_OK) { throw new FTDI.FT_EXCEPTION("Failed to write to port B. err: " + ftStatus.ToString()); } // Notify all threads of a change in port status System.Threading.Monitor.PulseAll(portB); } } // end Port B if (data.Count != bytesWritten) throw new Exception("Write length mismatch"); }
public void SetupDevice( uint baudRate = 9600, byte dataBits = FTDI.FT_DATA_BITS.FT_BITS_8, byte stopBits = FTDI.FT_STOP_BITS.FT_STOP_BITS_1, byte parity = FTDI.FT_PARITY.FT_PARITY_NONE, ushort flowControl = FTDI.FT_FLOW_CONTROL.FT_FLOW_RTS_CTS, byte xon = 0x11, byte xoff = 0x13, uint readTimeout = 5000, uint writeTimeout = 0) { // Set up device data parameters // Set Baud rate to 9600 ftStatus = myFtdiDevice.SetBaudRate(baudRate); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press Console.WriteLine("Failed to set Baud rate (error " + this.ftStatus + ")"); return; } // Set data characteristics - Data bits, Stop bits, Parity ftStatus = myFtdiDevice.SetDataCharacteristics(dataBits, stopBits, parity); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press Console.WriteLine("Failed to set data characteristics (error " + this.ftStatus + ")"); return; } // Set flow control - set RTS/CTS flow control ftStatus = myFtdiDevice.SetFlowControl(flowControl, xon, xoff); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press Console.WriteLine("Failed to set flow control (error " + this.ftStatus + ")"); return; } // Set read timeout to 5 seconds, write timeout to infinite ftStatus = myFtdiDevice.SetTimeouts(readTimeout, writeTimeout); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press Console.WriteLine("Failed to set timeouts (error " + this.ftStatus + ")"); } }
//************************************************ // USBから読み込み //************************************************ public List<byte> Read() { UInt32 readAvailable = 0; //受け取る事のできるデータの数 UInt32 readLength = 0; //受けたデータの数 List<byte> data = new List<byte>(); List<byte> result; System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); while (true) { _ftStatus = _myFtdiDevice.GetRxBytesAvailable(ref readAvailable); if (_ftStatus == FTDI.FT_STATUS.FT_OK) { if (readAvailable > 0) { byte[] buf = new byte[readAvailable]; _myFtdiDevice.Read(buf, readAvailable, ref readLength); data.AddRange(buf); } else if (readAvailable == 0 && data.Count > 0) { if (IsRightData(data.ToArray())) { result = new List<byte>(data); break; } } } else { Close(); return null; } //time out if (sw.ElapsedMilliseconds > 15000) { _ftStatus = FTDI.FT_STATUS.FT_IO_ERROR; return null; } } //Close(); return result; }
static void Main(string[] args) { FTDI ftdi = new FTDI(); MAX7219 Display; uint devcount = 0; ftdi.GetNumberOfDevices(ref devcount); if (devcount > 0) { byte[] TransferBuffer = new byte[88]; uint NumBytesToTransfer; uint NumBytesTransfered = 0; Display = new MAX7219(TransferBuffer, WriteOut); //FTDI AN_108 3.8 Clock Divisor uint dwClockDivisor = 29; //Value of clock divisor, SCL Frequency = 60/((1+29)*2) (MHz) = 1Mhz FTDI.FT_DEVICE_INFO_NODE[] devices = new FTDI.FT_DEVICE_INFO_NODE[devcount]; string Buffer; FTDI.FT_STATUS s = ftdi.GetDeviceList(devices); for (uint ix = 0; ix < devcount; ix++) { ftdi.OpenBySerialNumber(devices[ix].SerialNumber); ftdi.GetCOMPort(out Buffer); Console.WriteLine(Buffer); ftdi.GetDescription(out Buffer); Console.WriteLine(Buffer); //FTDI Set Mode MPSSE s = ftdi.SetBitMode(0, FTDI.FT_BIT_MODES.FT_BIT_MODE_RESET); s |= ftdi.SetBitMode(0, FTDI.FT_BIT_MODES.FT_BIT_MODE_MPSSE); if (s != FTDI.FT_STATUS.FT_OK) { Console.WriteLine("Fehler SetBitMode"); ftdi.Close(); return; } //FTDI Sync MPSSE (Check) FTDI_AN114 Page 10 if (Sync_MPSSE(ref ftdi, TransferBuffer) != FTDI.FT_STATUS.FT_OK) { Console.WriteLine("Fehler Sync MPSSE"); ftdi.Close(); return; } //Init FTDI SPI See FTDI AN_108 NumBytesToTransfer = 0; TransferBuffer[NumBytesToTransfer++] = 0x8a; // Disable Clock divide /5 TransferBuffer[NumBytesToTransfer++] = 0x97; // Disable adaptiv clockink TransferBuffer[NumBytesToTransfer++] = 0x8d; // Disables 3 phase data clocking // I think is not nesacery //TransferBuffer[NumBytesToTransfer++] = 0x80; //TransferBuffer[NumBytesToTransfer++] = 0x08; //TransferBuffer[NumBytesToTransfer++] = 0x0b; TransferBuffer[NumBytesToTransfer++] = 0x86; //3.8 Clock Divisor TransferBuffer[NumBytesToTransfer++] = (byte)(dwClockDivisor & 0xff); TransferBuffer[NumBytesToTransfer++] = (byte)(dwClockDivisor >> 8); s = ftdi.Write(TransferBuffer, NumBytesToTransfer, ref NumBytesTransfered); NumBytesToTransfer = 0; Thread.Sleep(20); TransferBuffer[NumBytesToTransfer++] = 0x85; // Disable loopback s |= ftdi.Write(TransferBuffer, NumBytesToTransfer, ref NumBytesTransfered); NumBytesToTransfer = 0; if (s != FTDI.FT_STATUS.FT_OK) { Console.WriteLine("SPI Init Fehler"); ftdi.Close(); return; } Console.WriteLine("SPI Init OK"); Console.WriteLine("Press ESC to Exit"); //Init 7219 s = ftdi.Write(TransferBuffer, Display.Init(8), ref NumBytesTransfered); UInt32 count = 0; while (true) { //Data s |= ftdi.Write(TransferBuffer, Display.WriteDec(count, (byte)(1 << ((byte)(count++ % 8)))), ref NumBytesTransfered); Console.WriteLine("SPI {0} Bytes Write", NumBytesTransfered); Thread.Sleep(100); if (Console.KeyAvailable && (Console.ReadKey(true)).Key == ConsoleKey.Escape) { break; } } s |= ftdi.Write(TransferBuffer, Display.Clr(), ref NumBytesTransfered); if (s != FTDI.FT_STATUS.FT_OK) { Console.WriteLine("SPI Fehler Write Data"); ftdi.Close(); return; } ftdi.Close(); } } else { Console.WriteLine("Kein FTDI gefunden :-("); } }
// Function to output an entire frame to the USB3 Chip public bool Send_test_sequence(bool altOn) { FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OK; FTDI d3xxDevice = new FTDI(); bool bLoopbackFails = false; UInt32 words_per_line = 40; byte[] line_one = new byte[words_per_line]; byte[] line_two = new byte[words_per_line]; UInt32 bytesWritten = 0; bool TestResult = false; //var pOverlapped = new System.Threading.NativeOverlapped(); //if (!TestLoopbackPrepare.bBasicLoopbackWorking) //{ // Debug.WriteLine("ERROR: Basic Loopback failed, test will be skipped!"); // return TestResult; //} // Open our FTDI601 USB3 Chip ftStatus = d3xxDevice.OpenBySerialNumber(FTDI.FT_60XCONFIGURATION_DEFAULT_SERIALNUMBER); if (ftStatus != FTDI.FT_STATUS.FT_OK) { Debug.WriteLine("OpenByIndex failed! ftStatus={0}", ftStatus); return(TestResult); } /////////////////////////////////////////////// ////////////// Chip Configuration ///////////// /////////////////////////////////////////////// //// Set our config Values //var conf = new FTDI.FT_60XCONFIGURATION //{ // // Set default values // VendorID = FTDI.FT_60XCONFIGURATION_DEFAULT_VENDORID, // ProductID = FTDI.FT_60XCONFIGURATION_DEFAULT_PRODUCTID_601, // PowerAttributes = FTDI.FT_60XCONFIGURATION_DEFAULT_POWERATTRIBUTES, // PowerConsumption = FTDI.FT_60XCONFIGURATION_DEFAULT_POWERCONSUMPTION, // BatteryChargingGPIOConfig = FTDI.FT_60XCONFIGURATION_DEFAULT_BATTERYCHARGING, // OptionalFeatureSupport = FTDI.FT_60XCONFIGURATION_DEFAULT_OPTIONALFEATURE, // MSIO_Control = FTDI.FT_60XCONFIGURATION_DEFAULT_MSIOCONTROL, // GPIO_Control = FTDI.FT_60XCONFIGURATION_DEFAULT_GPIOCONTROL, // FlashEEPROMDetection = 0, // SerialNumber = FTDI.FT_60XCONFIGURATION_DEFAULT_SERIALNUMBER, // // Set custom values // FIFOMode = (byte)FTDI.FT_60XCONFIGURATION_FIFO_MODE.MODE_245, // //FIFOClock = (byte)FTDI.FT_60XCONFIGURATION_FIFO_CLK.CLK_100_MHZ: // FIFOClock = (byte)FTDI.FT_60XCONFIGURATION_FIFO_CLK.CLK_66_MHZ, // ChannelConfig = (byte)FTDI.FT_60XCONFIGURATION_CHANNEL_CONFIG.ONE_OUTPIPE, // Manufacturer = "Awesome Inc", // Description = "Being Awesome" //}; ////conf.SerialNumber = "123456789012345"; //ftStatus = d3xxDevice.SetChipConfiguration(conf); //if (ftStatus != FTDI.FT_STATUS.FT_OK) { Console.WriteLine("Fatal Error"); }; //// Need to close afterwards and wait at least 2s before re-opening (from datasheet) //ftStatus = d3xxDevice.Close(); //if (ftStatus != FTDI.FT_STATUS.FT_OK) { Console.WriteLine("Fatal Error"); }; //Thread.Sleep(2000); //ftStatus = d3xxDevice.OpenByIndex(0); //if (ftStatus != FTDI.FT_STATUS.FT_OK) { Console.WriteLine("OpenByIndex failed! ftStatus={0}", ftStatus); return TestResult; } //// Read what is set //ftStatus = d3xxDevice.GetChipConfiguration(conf); //if (ftStatus != FTDI.FT_STATUS.FT_OK) { Console.WriteLine("Fatal Error"); }; //// Print results //Console.WriteLine("\tChip Configuration"); //Console.WriteLine("\tVendorID : 0x{0:X4}", conf.VendorID); //Console.WriteLine("\tProductID : 0x{0:X4}", conf.ProductID); //Console.WriteLine("\tManufacturer : " + conf.Manufacturer); //Console.WriteLine("\tDescription : " + conf.Description); //Console.WriteLine("\tSerialNumber : " + conf.SerialNumber); //Console.WriteLine("\tPowerAttributes : 0x{0:X2}", conf.PowerAttributes); //Console.WriteLine("\tPowerConsumption : 0x{0:X4}", conf.PowerConsumption); //Console.WriteLine("\tFIFOClock : 0x{0:X4}", conf.FIFOClock); //Console.WriteLine("\tFIFOMode : 0x{0:X2}", conf.FIFOMode); //Console.WriteLine("\tChannelConfig : 0x{0:X2}", conf.ChannelConfig); //Console.WriteLine("\tOptionalFeatureSupport : 0x{0:X4}", conf.OptionalFeatureSupport); //Console.WriteLine("\tBatteryChargingGPIOConfig: 0x{0:X2}", conf.BatteryChargingGPIOConfig); //Console.WriteLine("\tMSIO_Control : 0x{0:X8}", conf.MSIO_Control); //Console.WriteLine("\tGPIO_Control : 0x{0:X8}", conf.GPIO_Control); //Console.WriteLine("\tFlashEEPROMDetection : 0x{0:X2}", conf.FlashEEPROMDetection); //if (conf.FlashEEPROMDetection > 0) //{ // bool bROM = (conf.FlashEEPROMDetection & (1 << (byte)FTDI.FT_60XCONFIGURATION_FLASH_ROM_BIT.ROM)) > 0; // Debug.WriteLine("\t\tMEMORY : {0}", bROM ? "Rom" : "Flash"); // if (bROM) // { // bool bMemoryExist = (conf.FlashEEPROMDetection & (1 << (byte)FTDI.FT_60XCONFIGURATION_FLASH_ROM_BIT.MEMORY_NOTEXIST)) > 0; // Debug.WriteLine("\t\tMEMORY_NOTEXIST : {0}", bMemoryExist ? "Invalid" : "Valid"); // } // bool bCustom = (conf.FlashEEPROMDetection & (1 << (byte)FTDI.FT_60XCONFIGURATION_FLASH_ROM_BIT.CUSTOM)) > 0; // Debug.WriteLine("\t\tVALUES : {0}", bCustom ? "Custom" : "Default"); // if (!bCustom) // { // Default configuration // bool bGPIO0 = (conf.FlashEEPROMDetection & (1 << (byte)FTDI.FT_60XCONFIGURATION_FLASH_ROM_BIT.GPIO_0)) > 0; // bool bGPIO1 = (conf.FlashEEPROMDetection & (1 << (byte)FTDI.FT_60XCONFIGURATION_FLASH_ROM_BIT.GPIO_1)) > 0; // Debug.WriteLine("\t\tGPIO_0 : {0}", bGPIO0 ? "High" : "Low"); Debug.WriteLine("\t\tGPIO_1 : {0}", bGPIO1 ? "High" : "Low"); // if (bGPIO0 && bGPIO1) // { // Debug.WriteLine("\t\tChannel : 4 channels, 600 mode"); // } // else if (!bGPIO0 && bGPIO1) // { // Debug.WriteLine("\t\tChannel : 2 channels, 600 mode"); // } // else if (bGPIO0 && !bGPIO1) // { // Debug.WriteLine("\t\tChannel : 1 channel, 600 mode"); // } // else if (!bGPIO0 && !bGPIO1) // { // Debug.WriteLine("\t\tChannel : 1 channel, 245 mode"); // } // } // else // { // Custom configuration // bool bInvalidData = (conf.FlashEEPROMDetection & (1 << (byte)FTDI.FT_60XCONFIGURATION_FLASH_ROM_BIT.CUSTOMDATA_INVALID)) > 0; // bool bInvalidDataChecksum = (conf.FlashEEPROMDetection & (1 << (byte)FTDI.FT_60XCONFIGURATION_FLASH_ROM_BIT.CUSTOMDATACHKSUM_INVALID)) > 0; // Debug.WriteLine("\t\tCUSTOMDATA : {0}", bInvalidData ? "Invalid" : "Valid"); Debug.WriteLine("\t\tCUSTOMDATACHKSUM: {0}", bInvalidDataChecksum ? "Invalid" : "Valid"); // } //} ////ftStatus = d3xxDevice.Close(); ////if (ftStatus != FTDI.FT_STATUS.FT_OK) { Console.WriteLine("Fatal Error"); }; // Disable Input Timeouts //d3xxDevice.SetPipeTimeout(0x82, 0); //PipeTimeout.Disable(d3xxDevice, 0x82); // Disable tiomeouts on our output pipe d3xxDevice.SetPipeTimeout(0x02, 0); //d3xxDevice.SetPipeTimeout(0x02, 500); // We drive the entire FPGA design off of the FIFO's 100MHz vlock, therefore we want clock to run all the time // Set a timeout of 0 to achieve this, without this, clock will only be on for 10 seconds d3xxDevice.SetSuspendTimeout(0); // Diagnostics Code System.Collections.Generic.List <FT_PIPE_INFORMATION> info = d3xxDevice.DataPipeInformation; //d3xxDevice.ResetChipConfiguration(); //var conf = new FTDI.FT_60XCONFIGURATION(); //FT_STATUS status = d3xxDevice.GetChipConfiguration(conf); // Setup GPIO UInt32 ulDirection = ((byte)FTDI.FT_GPIO_DIRECTION.OUT << (byte)FTDI.FT_GPIO.GPIO_0) | ((byte)FTDI.FT_GPIO_DIRECTION.OUT << (byte)FTDI.FT_GPIO.GPIO_1); //UInt32 ulMask = (UInt32)FTDI.FT_GPIO_MASK.GPIO_ALL; //ftStatus = d3xxDevice.EnableGPIO(ulMask, ulDirection); //if (ftStatus != FTDI.FT_STATUS.FT_OK) //{ // Debug.WriteLine("EnableGPIO failed! ftStatus={0}", ftStatus); // return TestResult; //} // Write next_frame_rdy signal //ftStatus = d3xxDevice.EnableGPIO((UInt32)FTDI.FT_GPIO_MASK.GPIO_ALL, ulDirection); //ftStatus = d3xxDevice.WriteGPIO((UInt32)FTDI.FT_GPIO_MASK.GPIO_1, 3); //ftStatus = d3xxDevice.WriteGPIO((UInt32)FTDI.FT_GPIO_MASK.GPIO_1, 0); //ftStatus = d3xxDevice.EnableGPIO((UInt32)0, ulDirection); //for (UInt32 i = 0; i < 100; i++) //{ ///////////////////////////////////////////// ///////////// Single Lines Test ///////////// ///////////////////////////////////////////// //// Line 1 //for (UInt32 j = 0; j < line_one.Length; j++) //{ // //line_one[j] = (byte)(0xAA); // line_one[j] = (byte)(j << 4); //} //// Line 2 //for (UInt32 j = 0; j < line_two.Length; j++) //{ // //line_two[j] = (byte)(0x55); // line_two[j] = (byte)(j << 4); //} //// Write Line1 //ftStatus = d3xxDevice.WritePipe(0x02, line_one, (UInt32)line_one.Length, ref bytesWritten); //// Write Line2 //ftStatus = d3xxDevice.WritePipe(0x02, line_two, (UInt32)line_two.Length, ref bytesWritten); /////////////////////////////////////////// /////////// Entire Image Test ///////////// /////////////////////////////////////////// //bool altOn = true; //altOn = false; //uint lines_per_frame = 1280; // Just use 50 lines for now (less than 8kb, 1 buffer, until get to the bottom of the USB FIFO issue) //uint lines_per_frame = 256+2+3;// 1280;// 1304;// 66;// 1304;// 1280; //uint lines_per_frame = 256+2+3; //uint lines_per_frame = 512 - 4; // This can varyu, no idea why or how uint lines_per_frame = 1280;// 32;// 512;// 1280;//512;// 256;// 64;//32;// 64;// 2;// 16;// 6;// 64; // This can varyu, no idea why or how uint bytes_per_line = words_per_line * 4; uint total_bytes_per_frame = lines_per_frame * bytes_per_line; byte[] Frame1 = new byte[total_bytes_per_frame]; // Load up all of our 32-bit words with alternating data // Iterate through 8 bytes at a time for (int curr_byte = 0; curr_byte < (total_bytes_per_frame - 7); curr_byte += 8) { if (altOn) { //// Pattern on even 32-bit words //Frame1[curr_byte + 0] = 0xAA; //Frame1[curr_byte + 1] = 0xAA; //Frame1[curr_byte + 2] = 0xAA; //Frame1[curr_byte + 3] = 0xAA; //// Pattern on odd 32-bit words //Frame1[curr_byte + 4] = 0x55; //Frame1[curr_byte + 5] = 0x55; //Frame1[curr_byte + 6] = 0x55; //Frame1[curr_byte + 7] = 0x55; //// Pattern on even 32-bit words //Frame1[curr_byte + 0] = 0xFF; //Frame1[curr_byte + 1] = 0xFF; //Frame1[curr_byte + 2] = 0xFF; //Frame1[curr_byte + 3] = 0xFF; //// Pattern on odd 32-bit words //Frame1[curr_byte + 4] = 0x00; //Frame1[curr_byte + 5] = 0x00; //Frame1[curr_byte + 6] = 0x00; //Frame1[curr_byte + 7] = 0x00; //// Counting //Frame1[curr_byte + 0] = 0x01; //Frame1[curr_byte + 1] = 0x02; //Frame1[curr_byte + 2] = 0x03; //Frame1[curr_byte + 3] = 0x04; //Frame1[curr_byte + 4] = 0x05; //Frame1[curr_byte + 5] = 0x06; //Frame1[curr_byte + 6] = 0x07; //Frame1[curr_byte + 7] = 0x08; // Counting remembering we only get to write to half of pixels.... Frame1[curr_byte + 0] = 0x01; Frame1[curr_byte + 1] = 0x02; Frame1[curr_byte + 2] = 0xFF; Frame1[curr_byte + 3] = 0xFF; Frame1[curr_byte + 4] = 0x03; Frame1[curr_byte + 5] = 0x04; Frame1[curr_byte + 6] = 0xFF; Frame1[curr_byte + 7] = 0xFF; //// All Off //Frame1[curr_byte + 0] = 0x00; //Frame1[curr_byte + 1] = 0x00; //Frame1[curr_byte + 2] = 0x00; //Frame1[curr_byte + 3] = 0x00; //Frame1[curr_byte + 4] = 0x00; //Frame1[curr_byte + 5] = 0x00; //Frame1[curr_byte + 6] = 0x00; //Frame1[curr_byte + 7] = 0x00; } else { //// Pattern on even 32-bit words //Frame1[curr_byte + 0] = 0x55; //Frame1[curr_byte + 1] = 0x55; //Frame1[curr_byte + 2] = 0x55; //Frame1[curr_byte + 3] = 0x55; //// Pattern on odd 32-bit words //Frame1[curr_byte + 4] = 0xAA; //Frame1[curr_byte + 5] = 0xAA; //Frame1[curr_byte + 6] = 0xAA; //Frame1[curr_byte + 7] = 0xAA; //// Global Counting //Frame1[curr_byte + 0] = (byte)(curr_byte+0); //Frame1[curr_byte + 1] = (byte)(curr_byte+1); //Frame1[curr_byte + 2] = (byte)(curr_byte+2); //Frame1[curr_byte + 3] = (byte)(curr_byte+3); //Frame1[curr_byte + 4] = (byte)(curr_byte+4); //Frame1[curr_byte + 5] = (byte)(curr_byte+5); //Frame1[curr_byte + 6] = (byte)(curr_byte+6); //Frame1[curr_byte + 7] = (byte)(curr_byte+7); //// Corners Test Image //Frame1[curr_byte + 0] = TestImages.corners[curr_byte + 0]; //Frame1[curr_byte + 1] = TestImages.corners[curr_byte + 1]; //Frame1[curr_byte + 2] = TestImages.corners[curr_byte + 2]; //Frame1[curr_byte + 3] = TestImages.corners[curr_byte + 3]; //Frame1[curr_byte + 4] = TestImages.corners[curr_byte + 4]; //Frame1[curr_byte + 5] = TestImages.corners[curr_byte + 5]; //Frame1[curr_byte + 6] = TestImages.corners[curr_byte + 6]; //Frame1[curr_byte + 7] = TestImages.corners[curr_byte + 7]; //// All-on Test Image //Frame1[curr_byte + 0] = TestImages.all_on[curr_byte + 0]; //Frame1[curr_byte + 1] = TestImages.all_on[curr_byte + 1]; //Frame1[curr_byte + 2] = TestImages.all_on[curr_byte + 2]; //Frame1[curr_byte + 3] = TestImages.all_on[curr_byte + 3]; //Frame1[curr_byte + 4] = TestImages.all_on[curr_byte + 4]; //Frame1[curr_byte + 5] = TestImages.all_on[curr_byte + 5]; //Frame1[curr_byte + 6] = TestImages.all_on[curr_byte + 6]; //Frame1[curr_byte + 7] = TestImages.all_on[curr_byte + 7]; //// Incrementing Words //Frame1[curr_byte + 0] = TestImages.incr_words[curr_byte + 0]; //Frame1[curr_byte + 1] = TestImages.incr_words[curr_byte + 1]; //Frame1[curr_byte + 2] = TestImages.incr_words[curr_byte + 2]; //Frame1[curr_byte + 3] = TestImages.incr_words[curr_byte + 3]; //Frame1[curr_byte + 4] = TestImages.incr_words[curr_byte + 4]; //Frame1[curr_byte + 5] = TestImages.incr_words[curr_byte + 5]; //Frame1[curr_byte + 6] = TestImages.incr_words[curr_byte + 6]; //Frame1[curr_byte + 7] = TestImages.incr_words[curr_byte + 7]; // Smiley Face Frame1[curr_byte + 0] = TestImages.smiley_face[curr_byte + 0]; Frame1[curr_byte + 1] = TestImages.smiley_face[curr_byte + 1]; Frame1[curr_byte + 2] = TestImages.smiley_face[curr_byte + 2]; Frame1[curr_byte + 3] = TestImages.smiley_face[curr_byte + 3]; Frame1[curr_byte + 4] = TestImages.smiley_face[curr_byte + 4]; Frame1[curr_byte + 5] = TestImages.smiley_face[curr_byte + 5]; Frame1[curr_byte + 6] = TestImages.smiley_face[curr_byte + 6]; Frame1[curr_byte + 7] = TestImages.smiley_face[curr_byte + 7]; } } // Run in streaming mode for max performance with fixed block sizes ftStatus = d3xxDevice.SetStreamPipe(0x02, total_bytes_per_frame); if (ftStatus != FTDI.FT_STATUS.FT_OK) { Debug.WriteLine("Couldnt set to streaming mode! ftStatus={0}", ftStatus); d3xxDevice.AbortPipe(0x02); bLoopbackFails = true; } // Output Frame //ftStatus = d3xxDevice.WritePipe(0x02, Frame1, (UInt32)total_bytes_per_frame, ref bytesWritten); NativeOverlapped pOverlapped = new NativeOverlapped(); //for (int i = 0; i < 1280; i++) //{ //ftStatus = d3xxDevice.WritePipe(0x02, Frame1, (UInt32)total_bytes_per_frame, ref bytesWritten); Thread.Sleep(10); // Write ftStatus = d3xxDevice.WritePipeAsync(0x02, Frame1, (UInt32)total_bytes_per_frame, ref bytesWritten, ref pOverlapped); // Async wait ftStatus = d3xxDevice.WaitAsync(ref pOverlapped, ref bytesWritten, true); Thread.Sleep(10); if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (bytesWritten != total_bytes_per_frame)) { Console.WriteLine("Error with async transfer"); } ; // Print Transfer Details Console.WriteLine("Bytes: " + bytesWritten.ToString() + " Status: " + ftStatus.ToString()); //// Just send 32 lines at a time, 40 times //for(int i=0; i<40; i++) //{ // ftStatus = d3xxDevice.WritePipe(0x02, Frame1, (UInt32)total_bytes_per_frame, ref bytesWritten); // Thread.Sleep(10); // if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (bytesWritten != total_bytes_per_frame)) // { // Console.WriteLine("Error with async transfer"); // }; // // Print Transfer Details // Console.WriteLine("Bytes: " + bytesWritten.ToString() + " Status: " + ftStatus.ToString()); //} //ftStatus = d3xxDevice.WritePipe(0x02, Frame1, (UInt32)total_bytes_per_frame, ref bytesWritten); ////Thread.Sleep(10); //// Write ////ftStatus = d3xxDevice.WritePipeAsync(0x02, Frame1, (UInt32)total_bytes_per_frame, ref bytesWritten, ref pOverlapped); //// Async wait ////ftStatus = d3xxDevice.WaitAsync(ref pOverlapped, ref bytesWritten, true); ////Thread.Sleep(1); //if ((ftStatus != FTDI.FT_STATUS.FT_OK) || (bytesWritten != total_bytes_per_frame)) //{ // Console.WriteLine("Error with async transfer"); //}; //// Print Transfer Details //Console.WriteLine("Bytes: " + bytesWritten.ToString() + " Status: " + ftStatus.ToString()); // Print Pipe State //foreach (var desc in d3xxDevice.DataPipeInformation) //{ // Console.WriteLine("\tPIPE INFORMATION"); // Console.WriteLine("\tPipeType : {0:d} ({1})", desc.PipeType, desc.PipeType.ToString()); // Console.WriteLine("\tPipeId : 0x{0:X2}", desc.PipeId); // Console.WriteLine("\tMaximumPacketSize : 0x{0:X4}", desc.MaximumPacketSize); // Console.WriteLine("\tInterval : 0x{0:X2}", desc.Interval); //} //Frame1[row].ToList().ForEach(i => Console.WriteLine(i.ToString())); //Thread.Sleep(1); //} //// Pump all our lines, lots of data!! //for (int row = 0; row < lines_per_frame; row++) //{ // //ftStatus = d3xxDevice.WritePipe(0x02, Frame1[row], (UInt32)bytes_per_line, ref bytesWritten); // // Write // ftStatus = d3xxDevice.WritePipeAsync(0x02, Frame1[row], (UInt32)bytes_per_line, ref bytesWritten, ref pOverlapped); // // Async wait // ftStatus = d3xxDevice.WaitAsync(ref pOverlapped, ref bytesWritten, true); // if (ftStatus != FTDI.FT_STATUS.FT_OK || bytesWritten != bytes_per_line){ Console.WriteLine("Error with async transfer"); }; // // Print Transfer Details // Console.WriteLine("Bytes: " + bytesWritten.ToString() + " Status: " + ftStatus.ToString() ); // // Print Pipe State // foreach (var desc in d3xxDevice.DataPipeInformation) // { // Console.WriteLine("\tPIPE INFORMATION"); // Console.WriteLine("\tPipeType : {0:d} ({1})", desc.PipeType, desc.PipeType.ToString()); // Console.WriteLine("\tPipeId : 0x{0:X2}", desc.PipeId); // Console.WriteLine("\tMaximumPacketSize : 0x{0:X4}", desc.MaximumPacketSize); // Console.WriteLine("\tInterval : 0x{0:X2}", desc.Interval); // } // //Frame1[row].ToList().ForEach(i => Console.WriteLine(i.ToString())); // //Thread.Sleep(100); //} if (ftStatus != FTDI.FT_STATUS.FT_OK) { Debug.WriteLine("WritePipe failed! ftStatus={0}", ftStatus); d3xxDevice.AbortPipe(0x02); bLoopbackFails = true; //break; } //if (bytesWritten != writeBytes.Length) //{ // Debug.WriteLine("WritePipe failed! bytesWritten={0} != writeBytes.Length={1}", bytesWritten, writeBytes.Length); // bLoopbackFails = true; // break; //} //Debug.WriteLine("\t[{0:d}] WritePipe {1:d}", i, bytesWritten); // Write next_line_rdy signal //ftStatus = d3xxDevice.EnableGPIO((UInt32)FTDI.FT_GPIO_MASK.GPIO_ALL, ulDirection); //ftStatus = d3xxDevice.WriteGPIO((UInt32)FTDI.FT_GPIO_MASK.GPIO_0, 3); //ftStatus = d3xxDevice.WriteGPIO((UInt32)FTDI.FT_GPIO_MASK.GPIO_0, 0); //ftStatus = d3xxDevice.EnableGPIO((UInt32)0, ulDirection); // UInt32 bytesRead = 0; // while (true) // { // ftStatus = d3xxDevice.ReadPipe(0x82, readBytes, (UInt32)readBytes.Length, ref bytesRead); // if (ftStatus != FTDI.FT_STATUS.FT_OK) // { // Debug.WriteLine("ReadPipe failed! ftStatus={0}", ftStatus); // d3xxDevice.AbortPipe(0x82); // bLoopbackFails = true; // break; // } // if (bytesRead == 0) // { // Debug.WriteLine("ReadPipe bytesRead == 0, retry"); // continue; // } // else if (bytesRead != readBytes.Length) // { // Debug.WriteLine("ReadPipe failed! bytesRead={0} != readBytes.Length={1}", bytesRead, readBytes.Length); // bLoopbackFails = true; // break; // } // break; // } // Debug.WriteLine("\t[{0:d}] ReadPipe {1:d}", i, bytesRead); // bool same = writeBytes.SequenceEqual(readBytes); // if (same == false) // { // Debug.WriteLine("Loopback fails! SequenceEqual fails!"); // bLoopbackFails = true; // break; // } //} Thread.Sleep(200); d3xxDevice.AbortPipe(0x02); Thread.Sleep(200); Thread.Sleep(200); d3xxDevice.FlushPipe(0x02); Thread.Sleep(200); ftStatus = d3xxDevice.Close(); //d3xxDevice.ResetDevicePort(); if (ftStatus != FTDI.FT_STATUS.FT_OK) { Debug.WriteLine("Close failed! ftStatus={0}", ftStatus); return(TestResult); } if (!bLoopbackFails) { TestResult = true; } return(TestResult); }
public FTDI.FT_STATUS setLowRange() { FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OK; ftStatus = setFlowmeterRange(lowRange); return(ftStatus); }
void runMethod() { try { FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OK; FTDI myFtdiDevice = new FTDI(); ftStatus = myFtdiDevice.OpenBySerialNumber(FTDISerialNumber[DeviceIndex]); if (ftStatus != FTDI.FT_STATUS.FT_OK) { MessageBox.Show("error :" + ftStatus.ToString()); return; } ftStatus = myFtdiDevice.ResetDevice(); if (ftStatus != FTDI.FT_STATUS.FT_OK) { MessageBox.Show("error :" + ftStatus.ToString()); return; } ftStatus = myFtdiDevice.SetBaudRate(300); if (ftStatus != FTDI.FT_STATUS.FT_OK) { MessageBox.Show("error :" + ftStatus.ToString()); return; } ftStatus = myFtdiDevice.SetTimeouts(30000, 30000); if (ftStatus != FTDI.FT_STATUS.FT_OK) { MessageBox.Show("error :" + ftStatus.ToString()); return; } byte[] txbuf = new byte[100]; txbuf[0] = 0xf0; ftStatus = myFtdiDevice.Write(txbuf, 1, ref numBytesRead); if (ftStatus != FTDI.FT_STATUS.FT_OK) { MessageBox.Show("error :" + ftStatus.ToString()); return; } Thread.Sleep(200); txbuf[0] = 0x30; txbuf[1] = 0x00; for (int i = 0; i < 8; i++) { txbuf[2 + i] = psw[i]; } txbuf[10] = WFNetLib.Verify.GetVerify_byteSum(txbuf, 10); ftStatus = myFtdiDevice.Write(txbuf, 11, ref numBytesRead); if (ftStatus != FTDI.FT_STATUS.FT_OK) { MessageBox.Show("error :" + ftStatus.ToString()); return; } rxbuf = new byte[100]; ftStatus = myFtdiDevice.Read(rxbuf, 11, ref numBytesRead); if (ftStatus != FTDI.FT_STATUS.FT_OK) { MessageBox.Show("error :" + ftStatus.ToString()); return; } ftStatus = myFtdiDevice.Close(); if (ftStatus != FTDI.FT_STATUS.FT_OK) { MessageBox.Show("error :" + ftStatus.ToString()); return; } } catch (System.Exception ex) { } finally { bFind = true; } }
/// <summary> /// Connects to the FTDI device. /// </summary> /// <param name="deviceNode">A FTDI device info node to connect.</param> public virtual void Connect(FTDI.FT_DEVICE_INFO_NODE deviceNode) { this.DeviceNode = deviceNode; // Open device by serial number FTDI.FT_STATUS status = this.DeviceManager.OpenBySerialNumber(this.DeviceNode.SerialNumber); if (status != FTDI.FT_STATUS.FT_OK) { throw new InvalidOperationException("Unable to connect to FTDI device with serial number '" + this.DeviceNode.SerialNumber + "' (Result: '" + status + "')."); } //// Set up device data parameters //// Set Baud rate to 9600 //ftStatus = myFtdiDevice.SetBaudRate(9600); //if (ftStatus != FTDI.FT_STATUS.FT_OK) //{ // // Wait for a key press // Console.WriteLine("Failed to set Baud rate (error " + ftStatus.ToString() + ")"); // Console.ReadKey(); // return; //} //// Set data characteristics - Data bits, Stop bits, Parity //ftStatus = myFtdiDevice.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) //{ // // Wait for a key press // Console.WriteLine("Failed to set data characteristics (error " + ftStatus.ToString() + ")"); // Console.ReadKey(); // return; //} //// Set flow control - set RTS/CTS flow control //ftStatus = myFtdiDevice.SetFlowControl(FTDI.FT_FLOW_CONTROL.FT_FLOW_RTS_CTS, 0x11, 0x13); //if (ftStatus != FTDI.FT_STATUS.FT_OK) //{ // // Wait for a key press // Console.WriteLine("Failed to set flow control (error " + ftStatus.ToString() + ")"); // Console.ReadKey(); // return; //} //// Set read timeout to 5 seconds, write timeout to infinite //ftStatus = myFtdiDevice.SetTimeouts(5000, 0); //if (ftStatus != FTDI.FT_STATUS.FT_OK) //{ // // Wait for a key press // Console.WriteLine("Failed to set timeouts (error " + ftStatus.ToString() + ")"); // Console.ReadKey(); // return; //} //// Perform loop back - make sure loop back connector is fitted to the device //// Write string data to the device //string dataToWrite = "Hello world!"; //UInt32 numBytesWritten = 0; //// Note that the Write method is overloaded, so can write string or byte array data //ftStatus = myFtdiDevice.Write(dataToWrite, dataToWrite.Length, ref numBytesWritten); //if (ftStatus != FTDI.FT_STATUS.FT_OK) //{ // // Wait for a key press // Console.WriteLine("Failed to write to device (error " + ftStatus.ToString() + ")"); // Console.ReadKey(); // return; //} //// Check the amount of data available to read //// In this case we know how much data we are expecting, //// so wait until we have all of the bytes we have sent. //UInt32 numBytesAvailable = 0; //do //{ // ftStatus = myFtdiDevice.GetRxBytesAvailable(ref numBytesAvailable); // if (ftStatus != FTDI.FT_STATUS.FT_OK) // { // // Wait for a key press // Console.WriteLine("Failed to get number of bytes available to read (error " + ftStatus.ToString() + ")"); // Console.ReadKey(); // return; // } // Thread.Sleep(10); //} while (numBytesAvailable < dataToWrite.Length); //// Now that we have the amount of data we want available, read it //string readData; //UInt32 numBytesRead = 0; //// Note that the Read method is overloaded, so can read string or byte array data //ftStatus = myFtdiDevice.Read(out readData, numBytesAvailable, ref numBytesRead); //if (ftStatus != FTDI.FT_STATUS.FT_OK) //{ // // Wait for a key press // Console.WriteLine("Failed to read data (error " + ftStatus.ToString() + ")"); // Console.ReadKey(); // return; //} }
// //////////////////////////////////////////////////////////// public bool Initialize() { SystemInitialized = false; UInt32 index = 0; // this is the index of the Lambda device found in the list of USB devices connected // Determine the number of FTDI devices connected to the machine ftStatus = myFtdiDevice.GetNumberOfDevices(ref ftdiDeviceCount); // Check if devices found if (ftStatus == FTDI.FT_STATUS.FT_OK) { if (ftdiDeviceCount == 0) { PostError("No USB devices found (Thor Light Controller)"); return(false); // no devices found } } // Allocate storage for device info list FTDI.FT_DEVICE_INFO_NODE[] ftdiDeviceList = new FTDI.FT_DEVICE_INFO_NODE[ftdiDeviceCount]; // Populate our device list ftStatus = myFtdiDevice.GetDeviceList(ftdiDeviceList); // Search list for Thor device if (ftStatus == FTDI.FT_STATUS.FT_OK) { index = 100; for (UInt32 i = 0; i < ftdiDeviceCount; i++) { if (ftdiDeviceList[i].Description.ToString().Contains("FT232R")) { index = i; } } if (index == 100) { PostError("No Thor Light Controller found"); return(false); // no Thor devices found } } else { PostError("FTDI didn't load correctly and Thor Device is not initilized"); return(false); } // Open the Thor device found ftStatus = myFtdiDevice.OpenBySerialNumber(ftdiDeviceList[index].SerialNumber); if (ftStatus != FTDI.FT_STATUS.FT_OK) { PostError("Failed to open Thor Light Controller"); return(false); // failed to open device } // Set up device data parameters // Set Baud rate to 19200 ftStatus = myFtdiDevice.SetBaudRate(19200); if (ftStatus != FTDI.FT_STATUS.FT_OK) { PostError("Failed to set Thor Light Controller buad rate"); return(false); // failed to set baud rate } // Set data characteristics - Data bits, Stop bits, Parity ftStatus = myFtdiDevice.SetDataCharacteristics(FTDI.FT_DATA_BITS.FT_BITS_8, FTDI.FT_STOP_BITS.FT_STOP_BITS_1, FTDI.FT_PARITY.FT_PARITY_EVEN); if (ftStatus != FTDI.FT_STATUS.FT_OK) { PostError("Failed to set Thor Light Controller data characteristics"); return(false); // failed to set data characteristics (data bits, stop bits, parity) } // Set flow control - set RTS/CTS flow control ftStatus = myFtdiDevice.SetFlowControl(FTDI.FT_FLOW_CONTROL.FT_FLOW_NONE, 0x00, 0x00); if (ftStatus != FTDI.FT_STATUS.FT_OK) { PostError("Failed to set Thor Light Controller flow control"); return(false); // failed to set flow control } // Set read timeout to 5 seconds, write timeout to infinite ftStatus = myFtdiDevice.SetTimeouts(5000, 0); if (ftStatus != FTDI.FT_STATUS.FT_OK) { PostError("Failed to set Thor Light Controller read/write timeout durations"); return(false); // failed to set read/write timeout durations } SystemInitialized = true; PostMessage("Thor Light Controller initialized"); return(true); }
public static void Init(ref List <byte> configurationString) { // Check device UInt32 numOfDevices = 0; ftStatus = FT_CreateDeviceInfoList(ref numOfDevices); if (numOfDevices > 0) { byte[] sernum = new byte[16]; byte[] desc = new byte[64]; ftStatus = FT_GetDeviceInfoDetail(0, ref devInfo.Flags, ref devInfo.Type, ref devInfo.ID, ref devInfo.LocId, sernum, desc, ref devInfo.ftHandle); devInfo.SerialNumber = Encoding.ASCII.GetString(sernum, 0, 16); devInfo.Description = Encoding.ASCII.GetString(desc, 0, 64); devInfo.SerialNumber = devInfo.SerialNumber.Substring(0, devInfo.SerialNumber.IndexOf("\0")); devInfo.Description = devInfo.Description.Substring(0, devInfo.Description.IndexOf("\0")); Console.WriteLine("Device Number: {0}", numOfDevices); } else { Console.WriteLine("No FTDI device"); Console.WriteLine("NG! Press Enter to continue."); return; } // Open device ftStatus = FT_OpenEx(devInfo.LocId, FT_OPEN_BY_LOCATION, ref ftHandle); if (ftStatus != FTDI.FT_STATUS.FT_OK) { Console.WriteLine("Open NG: {0}", ftStatus); Console.WriteLine("NG! Press Enter to continue."); return; } // Set FT4222 clock FT4222_ClockRate ft4222_Clock = FT4222_ClockRate.SYS_CLK_24; ft42Status = FT4222_SetClock(ftHandle, FT4222_ClockRate.SYS_CLK_24); if (ft42Status != FT4222_STATUS.FT4222_OK) { Console.WriteLine("SetClock NG: {0}. Press Enter to continue.", ft42Status); return; } else { Console.WriteLine("SetClock OK"); ft42Status = FT4222_GetClock(ftHandle, ref ft4222_Clock); if (ft42Status != FT4222_STATUS.FT4222_OK) { Console.WriteLine("GetClock NG: {0}. Press Enter to continue.", ft42Status); return; } else { Console.WriteLine("GetClock:" + ft4222_Clock); } } // Init FT4222 SPI Master ft42Status = FT4222_SPIMaster_Init(ftHandle, FT4222_SPIMode.SPI_IO_SINGLE, FT4222_SPIClock.CLK_DIV_16, FT4222_SPICPOL.CLK_IDLE_LOW, FT4222_SPICPHA.CLK_TRAILING, 0x01); if (ft42Status != FT4222_STATUS.FT4222_OK) { Console.WriteLine("Open NG: {0}", ft42Status); Console.WriteLine("NG! Press Enter to continue."); return; } else { Console.WriteLine("Init FT4222 SPI Master OK"); } ft42Status = FT4222_SPI_SetDrivingStrength(ftHandle, SPI_DrivingStrength.DS_12MA, SPI_DrivingStrength.DS_12MA, SPI_DrivingStrength.DS_16MA); if (ft42Status != FT4222_STATUS.FT4222_OK) { Console.WriteLine("SetDrivingStrength NG: {0}", ft42Status); Console.WriteLine("NG! Press Enter to continue."); return; } }
/// <summary> /// Constructor /// </summary> /// <see cref="http://www.ftdichip.com/Support/Documents/AppNotes/AN_108_Command_Processor_for_MPSSE_and_MCU_Host_Bus_Emulation_Modes.pdf"/> /// <param name="dev_index"></param> /// <returns></returns> public FTDI.FT_STATUS ResetDevice() { FTDI.FT_STATUS status = _ftdi.ResetDevice(); return(status); }
static void Main(string[] args) { UInt32 ftdiDeviceCount = 0; FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OK; // Create new instance of the FTDI device class FTDI myFtdiDevice = new FTDI(); // Determine the number of FTDI devices connected to the machine ftStatus = myFtdiDevice.GetNumberOfDevices(ref ftdiDeviceCount); // Check status if (ftStatus == FTDI.FT_STATUS.FT_OK) { Console.WriteLine("Number of FTDI devices: " + ftdiDeviceCount.ToString()); Console.WriteLine(""); } else { // Wait for a key press Console.WriteLine("Failed to get number of devices (error " + ftStatus.ToString() + ")"); Console.ReadKey(); return; } // If no devices available, return if (ftdiDeviceCount == 0) { // Wait for a key press Console.WriteLine("Failed to get number of devices (error " + ftStatus.ToString() + ")"); Console.ReadKey(); return; } // Allocate storage for device info list FTDI.FT_DEVICE_INFO_NODE[] ftdiDeviceList = new FTDI.FT_DEVICE_INFO_NODE[ftdiDeviceCount]; // Populate our device list ftStatus = myFtdiDevice.GetDeviceList(ftdiDeviceList); if (ftStatus == FTDI.FT_STATUS.FT_OK) { for (UInt32 i = 0; i < ftdiDeviceCount; i++) { Console.WriteLine("Device Index: " + i.ToString()); Console.WriteLine("Flags: " + String.Format("{0:x}", ftdiDeviceList[i].Flags)); Console.WriteLine("Type: " + ftdiDeviceList[i].Type.ToString()); Console.WriteLine("ID: " + String.Format("{0:x}", ftdiDeviceList[i].ID)); Console.WriteLine("Location ID: " + String.Format("{0:x}", ftdiDeviceList[i].LocId)); Console.WriteLine("Serial Number: " + ftdiDeviceList[i].SerialNumber.ToString()); Console.WriteLine("Description: " + ftdiDeviceList[i].Description.ToString()); Console.WriteLine(""); } } // Open first device in our list by serial number ftStatus = myFtdiDevice.OpenBySerialNumber(ftdiDeviceList[0].SerialNumber); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press Console.WriteLine("Failed to open device (error " + ftStatus.ToString() + ")"); Console.ReadKey(); return; } // Create our device EEPROM structure based on the type of device we have open if (ftdiDeviceList[0].Type == FTDI.FT_DEVICE.FT_DEVICE_232R) { // We have an FT232R or FT245R so use FT232R EEPROM structure FTDI.FT232R_EEPROM_STRUCTURE myEEData = new FTDI.FT232R_EEPROM_STRUCTURE(); // Read the device EEPROM // This can throw an exception if trying to read a device type that does not // match the EEPROM structure being used, so should always use a // try - catch block when calling try { ftStatus = myFtdiDevice.ReadFT232REEPROM(myEEData); } catch (FTDI.FT_EXCEPTION) { Console.WriteLine("Exception thrown when calling ReadFT232REEPROM"); } if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press Console.WriteLine("Failed to read device EEPROM (error " + ftStatus.ToString() + ")"); Console.ReadKey(); // Close the device myFtdiDevice.Close(); return; } // Write common EEPROM elements to our console Console.WriteLine("EEPROM Contents for device at index 0:"); Console.WriteLine("Vendor ID: " + String.Format("{0:x}", myEEData.VendorID)); Console.WriteLine("Product ID: " + String.Format("{0:x}", myEEData.ProductID)); Console.WriteLine("Manufacturer: " + myEEData.Manufacturer.ToString()); Console.WriteLine("Manufacturer ID: " + myEEData.ManufacturerID.ToString()); Console.WriteLine("Description: " + myEEData.Description.ToString()); Console.WriteLine("Serial Number: " + myEEData.SerialNumber.ToString()); Console.WriteLine("Max Power: " + myEEData.MaxPower.ToString() + "mA"); Console.WriteLine("Self Powered: " + myEEData.SelfPowered.ToString()); Console.WriteLine("Remote Wakeup Enabled: " + myEEData.RemoteWakeup.ToString()); Console.WriteLine(""); // Change our serial number to write back to device // By setting to an empty string, we allow the FTD2XX DLL // to generate a serial number myEEData.SerialNumber = String.Empty; // Write our modified data structure back to the device EEPROM // This can throw an exception if trying to write a device type that does not // match the EEPROM structure being used, so should always use a // try - catch block when calling try { ftStatus = myFtdiDevice.WriteFT232REEPROM(myEEData); } catch (FTDI.FT_EXCEPTION) { Console.WriteLine("Exception thrown when calling WriteFT232REEPROM"); } if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press Console.WriteLine("Failed to write device EEPROM (error " + ftStatus.ToString() + ")"); Console.ReadKey(); // Close the device myFtdiDevice.Close(); return; } } else if (ftdiDeviceList[0].Type == FTDI.FT_DEVICE.FT_DEVICE_2232) { // We have an FT2232 so use FT2232 EEPROM structure FTDI.FT2232_EEPROM_STRUCTURE myEEData = new FTDI.FT2232_EEPROM_STRUCTURE(); // Read the device EEPROM ftStatus = myFtdiDevice.ReadFT2232EEPROM(myEEData); // This can throw an exception if trying to read a device type that does not // match the EEPROM structure being used, so should always use a // try - catch block when calling try { ftStatus = myFtdiDevice.ReadFT2232EEPROM(myEEData); } catch (FTDI.FT_EXCEPTION) { Console.WriteLine("Exception thrown when calling ReadFT2232EEPROM"); } if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press Console.WriteLine("Failed to read device EEPROM (error " + ftStatus.ToString() + ")"); Console.ReadKey(); // Close the device myFtdiDevice.Close(); return; } // Write common EEPROM elements to our console Console.WriteLine("EEPROM Contents for device at index 0:"); Console.WriteLine("Vendor ID: " + String.Format("{0:x}", myEEData.VendorID)); Console.WriteLine("Product ID: " + String.Format("{0:x}", myEEData.ProductID)); Console.WriteLine("Manufacturer: " + myEEData.Manufacturer.ToString()); Console.WriteLine("Manufacturer ID: " + myEEData.ManufacturerID.ToString()); Console.WriteLine("Description: " + myEEData.Description.ToString()); Console.WriteLine("Serial Number: " + myEEData.SerialNumber.ToString()); Console.WriteLine("Max Power: " + myEEData.MaxPower.ToString() + "mA"); Console.WriteLine("Self Powered: " + myEEData.SelfPowered.ToString()); Console.WriteLine("Remote Wakeup Enabled: " + myEEData.RemoteWakeup.ToString()); Console.WriteLine(""); // Change our serial number to write back to device // By setting to an empty string, we allow the FTD2XX DLL // to generate a serial number myEEData.SerialNumber = String.Empty; // Write our modified data structure back to the device EEPROM // This can throw an exception if trying to write a device type that does not // match the EEPROM structure being used, so should always use a // try - catch block when calling try { ftStatus = myFtdiDevice.WriteFT2232EEPROM(myEEData); } catch (FTDI.FT_EXCEPTION) { Console.WriteLine("Exception thrown when calling WriteFT2232EEPROM"); } if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press Console.WriteLine("Failed to write device EEPROM (error " + ftStatus.ToString() + ")"); Console.ReadKey(); // Close the device myFtdiDevice.Close(); return; } } else if (ftdiDeviceList[0].Type == FTDI.FT_DEVICE.FT_DEVICE_BM) { // We have an FT232B or FT245B so use FT232B EEPROM structure FTDI.FT232B_EEPROM_STRUCTURE myEEData = new FTDI.FT232B_EEPROM_STRUCTURE(); // Read the device EEPROM ftStatus = myFtdiDevice.ReadFT232BEEPROM(myEEData); // This can throw an exception if trying to read a device type that does not // match the EEPROM structure being used, so should always use a // try - catch block when calling try { ftStatus = myFtdiDevice.ReadFT232BEEPROM(myEEData); } catch (FTDI.FT_EXCEPTION) { Console.WriteLine("Exception thrown when calling ReadFT232BEEPROM"); } if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press Console.WriteLine("Failed to read device EEPROM (error " + ftStatus.ToString() + ")"); Console.ReadKey(); // Close the device myFtdiDevice.Close(); return; } // Write common EEPROM elements to our console Console.WriteLine("EEPROM Contents for device at index 0:"); Console.WriteLine("Vendor ID: " + String.Format("{0:x}", myEEData.VendorID)); Console.WriteLine("Product ID: " + String.Format("{0:x}", myEEData.ProductID)); Console.WriteLine("Manufacturer: " + myEEData.Manufacturer.ToString()); Console.WriteLine("Manufacturer ID: " + myEEData.ManufacturerID.ToString()); Console.WriteLine("Description: " + myEEData.Description.ToString()); Console.WriteLine("Serial Number: " + myEEData.SerialNumber.ToString()); Console.WriteLine("Max Power: " + myEEData.MaxPower.ToString() + "mA"); Console.WriteLine("Self Powered: " + myEEData.SelfPowered.ToString()); Console.WriteLine("Remote Wakeup Enabled: " + myEEData.RemoteWakeup.ToString()); Console.WriteLine(""); // Change our serial number to write back to device // By setting to an empty string, we allow the FTD2XX DLL // to generate a serial number myEEData.SerialNumber = String.Empty; // Write our modified data structure back to the device EEPROM // This can throw an exception if trying to write a device type that does not // match the EEPROM structure being used, so should always use a // try - catch block when calling try { ftStatus = myFtdiDevice.WriteFT232BEEPROM(myEEData); } catch (FTDI.FT_EXCEPTION) { Console.WriteLine("Exception thrown when calling WriteFT232BEEPROM"); } if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press Console.WriteLine("Failed to write device EEPROM (error " + ftStatus.ToString() + ")"); Console.ReadKey(); // Close the device myFtdiDevice.Close(); return; } } // Use cycle port to force a re-enumeration of the device. // In the FTD2XX_NET class library, the cycle port method also // closes the open handle so no need to call the Close method separately. ftStatus = myFtdiDevice.CyclePort(); UInt32 newFtdiDeviceCount = 0; do { // Wait for device to be re-enumerated // The device will have the same location since it has not been // physically unplugged, so we will keep trying to open it until it succeeds ftStatus = myFtdiDevice.OpenByLocation(ftdiDeviceList[0].LocId); Thread.Sleep(1000); } while (ftStatus != FTDI.FT_STATUS.FT_OK); // Close the device myFtdiDevice.Close(); // Re-create our device list ftStatus = myFtdiDevice.GetNumberOfDevices(ref newFtdiDeviceCount); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press Console.WriteLine("Failed to get number of devices (error " + ftStatus.ToString() + ")"); Console.ReadKey(); return; } // Re-populate our device list ftStatus = myFtdiDevice.GetDeviceList(ftdiDeviceList); if (ftStatus == FTDI.FT_STATUS.FT_OK) { for (UInt32 i = 0; i < ftdiDeviceCount; i++) { Console.WriteLine("Device Index: " + i.ToString()); Console.WriteLine("Flags: " + String.Format("{0:x}", ftdiDeviceList[i].Flags)); Console.WriteLine("Type: " + ftdiDeviceList[i].Type.ToString()); Console.WriteLine("ID: " + String.Format("{0:x}", ftdiDeviceList[i].ID)); Console.WriteLine("Location ID: " + String.Format("{0:x}", ftdiDeviceList[i].LocId)); Console.WriteLine("Serial Number: " + ftdiDeviceList[i].SerialNumber.ToString()); Console.WriteLine("Description: " + ftdiDeviceList[i].Description.ToString()); Console.WriteLine(""); } } // Wait for a key press Console.WriteLine("Press any key to continue."); Console.ReadKey(); return; }
static void Main(string[] args) { UInt32 ftdiDeviceCount = 0; FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OK; // Create new instance of the FTDI device class FTDI myFtdiDevice = new FTDI(); // Determine the number of FTDI devices connected to the machine ftStatus = myFtdiDevice.GetNumberOfDevices(ref ftdiDeviceCount); // Check status if (ftStatus == FTDI.FT_STATUS.FT_OK) { Console.WriteLine("Number of FTDI devices: " + ftdiDeviceCount.ToString()); Console.WriteLine(""); } else { // Wait for a key press Console.WriteLine("Failed to get number of devices (error " + ftStatus.ToString() + ")"); Console.ReadKey(); return; } // If no devices available, return if (ftdiDeviceCount == 0) { // Wait for a key press Console.WriteLine("Failed to get number of devices (error " + ftStatus.ToString() + ")"); Console.ReadKey(); return; } // Allocate storage for device info list FTDI.FT_DEVICE_INFO_NODE[] ftdiDeviceList = new FTDI.FT_DEVICE_INFO_NODE[ftdiDeviceCount]; // Populate our device list ftStatus = myFtdiDevice.GetDeviceList(ftdiDeviceList); if (ftStatus == FTDI.FT_STATUS.FT_OK) { for (UInt32 i = 0; i < ftdiDeviceCount; i++) { Console.WriteLine("Device Index: " + i.ToString()); Console.WriteLine("Flags: " + String.Format("{0:x}", ftdiDeviceList[i].Flags)); Console.WriteLine("Type: " + ftdiDeviceList[i].Type.ToString()); Console.WriteLine("ID: " + String.Format("{0:x}", ftdiDeviceList[i].ID)); Console.WriteLine("Location ID: " + String.Format("{0:x}", ftdiDeviceList[i].LocId)); Console.WriteLine("Serial Number: " + ftdiDeviceList[i].SerialNumber.ToString()); Console.WriteLine("Description: " + ftdiDeviceList[i].Description.ToString()); Console.WriteLine(""); } } // Open first device in our list by serial number ftStatus = myFtdiDevice.OpenBySerialNumber(ftdiDeviceList[0].SerialNumber); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press Console.WriteLine("Failed to open device (error " + ftStatus.ToString() + ")"); Console.ReadKey(); return; } else { // ZJ Console.WriteLine(ftdiDeviceList[0].Description.ToString()); Console.WriteLine("Open OK: "); } ftStatus = myFtdiDevice.ResetDevice(); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press Console.WriteLine("Failed to Reset Device (error " + ftStatus.ToString() + ")"); Console.ReadKey(); return; } else { Console.WriteLine("Reset OK: "); } // you can define control commands (see Programmer's Guide - page 4) byte[] cmd_res = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00 }; byte[] cmd_ctrl = new byte[] { 0x04, 0x23, 0x00, 0x00, 0x00 }; // time interval, A<->B, 1 s range byte[] cmd_en = new byte[] { 0x03, 0x04, 0x00, 0x00, 0x00 }; // Ihibit byte[] cmd_wr_s = new byte[] { 0x02, 0xee, 0x04, 0x00, 0x00 }; // set START A, STOP B, slope rise (both), internal clock ON byte[] cmd_wr_dac = new byte[] { 0x05, 0x8f, 0x8f, 0x00, 0x00 }; // threshold 0.5 V to START/STOP. byte[] cmd_rd_s = new byte[] { 0xF2, 0x01, 0x00, 0x00, 0x00 }; byte[] cmd_meas = new byte[] { 0x01, 0x01, 0x00, 0x00, 0x00 }; byte[] cmd_rd_meas_no = new byte[] { 0xF1, 0x01, 0x00, 0x00, 0x00 }; byte[] cmd_rd_f_data = new byte[] { 0xF0, 0x02, 0x00, 0x00, 0x00 }; byte[] read_buffer = new byte[4 * 1024]; // set the size of buffer UInt32 numBytesRead = 0; UInt32 data = 0; UInt32 numBytesWritten = 5; Boolean calibrated = false; Boolean Meas_Ready = false; ftStatus = myFtdiDevice.Write(cmd_ctrl, cmd_ctrl.Length, ref numBytesWritten); ftStatus = myFtdiDevice.Write(cmd_en, cmd_en.Length, ref numBytesWritten); ftStatus = myFtdiDevice.Write(cmd_wr_s, cmd_wr_s.Length, ref numBytesWritten); ftStatus = myFtdiDevice.Write(cmd_wr_dac, cmd_wr_dac.Length, ref numBytesWritten); // wait on finish of calibration Console.WriteLine("Wait on calibration"); ftStatus = myFtdiDevice.Write(cmd_res, 5, ref numBytesWritten); do { Console.Write("."); ftStatus = myFtdiDevice.Write(cmd_rd_s, cmd_rd_s.Length, ref numBytesWritten); ftStatus = myFtdiDevice.Read(read_buffer, 4, ref numBytesRead); data = BitConverter.ToUInt32(read_buffer, 0); if ((data & 0x800) == 0x800) { calibrated = true; } } while (!calibrated); Console.WriteLine(""); Console.WriteLine("Calibration done"); // read the offset value - the simpliest version without averaging (you should read more consecutive data to calculate average value of OFFSET, see page 2.7) Double Offset = 0.000000000000000; Double Meas = 0.000000000000000; UInt64 Count = 0; UInt32 A = 0; UInt32 B = 0; cmd_rd_f_data[1] = 0x02; // number of 32-bit data = 2 ftStatus = myFtdiDevice.Write(cmd_rd_f_data, 5, ref numBytesWritten); do { ftStatus = myFtdiDevice.GetRxBytesAvailable(ref numBytesRead); } while (numBytesRead < 8); ftStatus = myFtdiDevice.Read(read_buffer, 8, ref numBytesRead); data = BitConverter.ToUInt32(read_buffer, 0); // first 32-bit word Count = data >> 20; A = data & 0x3FF; B = (data >> 10) & 0x3FF; data = BitConverter.ToUInt32(read_buffer, 4); // second 32-bit word Count = (data << 12) | Count; Offset = 4 * ((double)Count + (((double)A - (double)B) / 1024)); Console.WriteLine("Offset = " + Offset.ToString() + " ns"); Offset = Offset / 1000000000; // Measurement loop (in sequence: Start single measurement -> read the result) // refresh settings (the settings are not restored after calibration) ftStatus = myFtdiDevice.Write(cmd_ctrl, cmd_ctrl.Length, ref numBytesWritten); ftStatus = myFtdiDevice.Write(cmd_en, cmd_en.Length, ref numBytesWritten); ftStatus = myFtdiDevice.Write(cmd_wr_s, cmd_wr_s.Length, ref numBytesWritten); ftStatus = myFtdiDevice.Write(cmd_wr_dac, cmd_wr_dac.Length, ref numBytesWritten); Thread.Sleep(20); //wait for DAC Console.WriteLine(""); Console.WriteLine("Press CTRL C to intrrupt"); Console.WriteLine(""); cmd_meas = new byte[] { 0x01, 0x01, 0x00, 0x00, 0x00 }; // number of measurements to do = 1 do { ftStatus = myFtdiDevice.Write(cmd_meas, 5, ref numBytesWritten); // start measuring process Meas_Ready = false; do //check the value of RD_MEAS_NO register { ftStatus = myFtdiDevice.Write(cmd_rd_meas_no, 5, ref numBytesWritten); ftStatus = myFtdiDevice.Read(read_buffer, 4, ref numBytesRead); data = BitConverter.ToUInt32(read_buffer, 0); if (data > 0) { Meas_Ready = true; } } while (!Meas_Ready); // READ RESULTS cmd_rd_f_data = new byte[] { 0xF0, 0x02, 0x00, 0x00, 0x00 }; // how many words do you want to read? (2) ftStatus = myFtdiDevice.Write(cmd_rd_f_data, 5, ref numBytesWritten); do { ftStatus = myFtdiDevice.GetRxBytesAvailable(ref numBytesRead); } while (numBytesRead < 8); numBytesRead = 0; ftStatus = myFtdiDevice.Read(read_buffer, 8, ref numBytesRead); data = BitConverter.ToUInt32(read_buffer, 0); // the first 32-bit word Count = data >> 20; A = data & 0x3FF; B = (data >> 10) & 0x3FF; data = BitConverter.ToUInt32(read_buffer, 4); // the second 32-bit word Count = (data << 12) | Count; Meas = 4 * ((double)Count + (((double)A - (double)B) / 1024)); Meas = Meas / 1000000000; Meas = Meas - Offset; Console.WriteLine("Time interval = " + Meas.ToString()); // you should write something to exit the loop } while (true); // Close our device ftStatus = myFtdiDevice.Close(); return; }
public void OpenDeviceBySerialNumber(string serialNumber) { // Open first device in our list by serial number ftStatus = myFtdiDevice.OpenBySerialNumber(serialNumber); if (ftStatus != FTDI.FT_STATUS.FT_OK) { Console.WriteLine("Failed to open device (error " + this.ftStatus + ")"); } }
protected FTDI OpenChannel(string channelName, uint baudRate) { var res = new FTDI(); FTDI.FT_STATUS status = FTDI.FT_STATUS.FT_OTHER_ERROR; FTDI.FT_DEVICE_INFO_NODE[] devicelist = new FTDI.FT_DEVICE_INFO_NODE[255]; status = res.GetDeviceList(devicelist); // ON LINUX RUN APP WITH SUDO OR CONFIGURE ACCESS TO USB FTDI DEVICES Console.WriteLine($"getdevicelist status is {status}"); devicelist = devicelist.Where(x => x != null).ToArray(); if (!devicelist.Any()) { throw new Exception("No FTDI devices found."); } foreach (var device in devicelist) { Console.WriteLine($"Description is '{device.Description}'"); Console.WriteLine($"SerialNumber is '{device.SerialNumber}'"); Console.WriteLine($"ID is '{device.ID}'"); Console.WriteLine($"LocId is '{device.LocId}'"); Console.WriteLine($"Type is '{device.Type}'"); Console.WriteLine($"------"); } status = res.OpenBySerialNumber(channelName); Debug.Assert(status == FTDI.FT_STATUS.FT_OK); res.ResetDevice(); Debug.Assert(status == FTDI.FT_STATUS.FT_OK); // for (int i = 0; i < 60; i++) // { // status = res.OpenBySerialNumber(channelName); // if ( // status != FTD2XX_NET.FTDI.FT_STATUS.FT_DEVICE_NOT_FOUND && // status != FTD2XX_NET.FTDI.FT_STATUS.FT_DEVICE_NOT_OPENED // ) // break; // Thread.Sleep(1000); // res = new FTDI(); // FTDI.FT_DEVICE_INFO_NODE[] list = new FTDI.FT_DEVICE_INFO_NODE[200]; // status = res.GetDeviceList(list); // } Debug.Assert(status == FTDI.FT_STATUS.FT_OK); status = res.SetBaudRate(baudRate); Debug.Assert(status == FTDI.FT_STATUS.FT_OK); status = res.SetLatency(0); Debug.Assert(status == FTDI.FT_STATUS.FT_OK); // enable async bitbang mode for all 8 pins status = res.SetBitMode(0b11111111, FTDI.FT_BIT_MODES.FT_BIT_MODE_ASYNC_BITBANG); Debug.Assert(status == FTDI.FT_STATUS.FT_OK); status = res.SetTimeouts(1, 1); Debug.Assert(status == FTDI.FT_STATUS.FT_OK); return(res); }
private void ShowRxData() { logger.Info(">ShowRx Ready: " + Name); FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OTHER_ERROR; UInt32 numBytesAvailable = 0; byte[] resp = new byte[4]; byte cod = 0; byte seq = 0; byte cnt = 0; byte chk = 0; USBMsg msg = null; UInt32 numBytesRead = 0; try { ManualResetEventSlim hdl = new ManualResetEventSlim(false); while (!cts.IsCancellationRequested) { ftStatus = myFtdiDevice.GetRxBytesAvailable(ref numBytesAvailable); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press logger.Error("Failed to get number of bytes available to read:" + Name + " (error " + ftStatus.ToString() + ")"); return; } if (numBytesAvailable > 3) { ftStatus = myFtdiDevice.Read(resp, numBytesAvailable, ref numBytesRead); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press logger.Error("Failed to read data:" + Name + " (error " + ftStatus.ToString() + ")"); } cod = resp[0]; seq = resp[1]; cnt = resp[2]; chk = resp[3]; logger.Info(string.Format("Recv: {4}: {0:x2} {1:x2} {2:x2} {3:x2}", cod, seq, cnt, chk, Name)); switch (cod) { case 0x80: if (sentMsgs.TryPeek(out msg)) { if (msg.seq == seq) { if (sentMsgs.TryDequeue(out msg)) { bufrPool.Add(msg); } } } avl = cnt; if (avl > maxavl) { maxavl = avl; } break; case 0x90: avl = cnt; if (avl > maxavl) { maxavl = avl; } break; default: logger.Error(string.Format(">Invalid resp: {4}: {0:x2} {1:x2} {2:x2} {3:x2}", cod, seq, cnt, chk, Name)); break; } } else { //using (EventWaitHandle hdl = new EventWaitHandle(false, EventResetMode.ManualReset)) //{ // myFtdiDevice.SetEventNotification(0, hdl); // hdl.WaitOne(500); //} hdl.Reset(); //myFtdiDevice.SetEventNotification(FTD2XX_NET.FTDI.FT_EVENTS.FT_EVENT_RXCHAR, hdl.WaitHandle); hdl.Wait(-1, tkn); WaitHandle.WaitAny(new WaitHandle[] { hdl.WaitHandle, tkn.WaitHandle }, -1); } } } finally { } }
public byte ReadByte() { byte[] testArray = new byte[5]; ftStatus = myFtdiDevice.Read(testArray, 1, ref test); return(testArray[0]); }
private void Open(FTDI port, string description) { uint deviceCount = 0; if (port == null) throw new Exception(description + "is not initialized"); if (port.IsOpen) { Global.ShowError(description + " is already open"); return; } // Determine the number of FTDI devices connected to the machine if ((ftStatus = port.GetNumberOfDevices(ref deviceCount)) != FTDI.FT_STATUS.FT_OK) { throw new FTDI.FT_EXCEPTION("Failed to get number of devices. err: " + ftStatus.ToString()); } // If no devices available, return if (deviceCount == 0) throw new Exception("No devices on " + description); // Allocate storage for device info list FTDI.FT_DEVICE_INFO_NODE[] ftdiDeviceList = new FTDI.FT_DEVICE_INFO_NODE[deviceCount]; // Populate our device list if ((ftStatus = port.GetDeviceList(ftdiDeviceList)) != FTDI.FT_STATUS.FT_OK) { throw new FTDI.FT_EXCEPTION("Failed to get device list. err " + ftStatus.ToString()); } int foundIndex = -1; for (int i = 0; i < deviceCount; i++) { if (ftdiDeviceList[i].Description.ToString().Contains(description)) { foundIndex = i; } /* Console.WriteLine("Device Index: " + i.ToString()); Console.WriteLine("Flags: " + String.Format("{0:x}", ftdiDeviceList[i].Flags)); Console.WriteLine("Type: " + ftdiDeviceList[i].Type.ToString()); Console.WriteLine("ID: " + String.Format("{0:x}", ftdiDeviceList[i].ID)); Console.WriteLine("Location ID: " + String.Format("{0:x}", ftdiDeviceList[i].LocId)); Console.WriteLine("Serial Number: " + ftdiDeviceList[i].SerialNumber.ToString()); Console.WriteLine("Description: " + ftdiDeviceList[i].Description.ToString()); Console.WriteLine(""); */ } if (foundIndex < 0) { throw new Exception("Failed to find device with description " + description); } if ((ftStatus = port.OpenByIndex((uint) foundIndex)) != FTDI.FT_STATUS.FT_OK) { throw new FTDI.FT_EXCEPTION("Failed to open device. err: " + ftStatus.ToString()); } }
public void SetBaudrate(uint r) { ftStatus = myFtdiDevice.SetBaudRate(r); }
public static void ESLPass() { UInt32 numBytesRead = 0; int retryMax = 10; int retry = retryMax; while (Global.bRun) { bCalc = false; autoResetEvent.WaitOne(); bCalc = true; while (true) { bool bOK = false; ESLQueueData eq = ESLQueueDataDBOption.GetFirst(); if (eq == null) { break; } ESLWorkLogData elog = new ESLWorkLogData(); elog.Pass = eq.Pass; elog.IP = eq.IP; elog.sTime = eq.sTime; elog.DeviceID = eq.DeviceID; try { byte[] bPass = WFNetLib.StringFunc.StringsFunction.strToHexByte(eq.Pass, ""); byte[] rxbuf = new byte[100]; retry = retryMax; while (retry != 0) { retry--; try { UInt32 ftdiDeviceCount = 0; FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OK; FTDI myFtdiDevice = new FTDI(); // ftStatus = myFtdiDevice.GetNumberOfDevices(ref ftdiDeviceCount); // if (ftStatus != FTDI.FT_STATUS.FT_OK) // { // continue; // } // if (ftdiDeviceCount == 0) // { // continue; // } // FTDI.FT_DEVICE_INFO_NODE[] ftdiDeviceList = new FTDI.FT_DEVICE_INFO_NODE[ftdiDeviceCount]; // ftStatus = myFtdiDevice.GetDeviceList(ftdiDeviceList); // if (ftStatus == FTDI.FT_STATUS.FT_OK) // { // bool bFind = false; // for (int i = 0; i < ftdiDeviceCount;i++ ) // { // if (ftdiDeviceList[i].SerialNumber.ToString() == "001054") // { // ftStatus = myFtdiDevice.OpenBySerialNumber(ftdiDeviceList[i].SerialNumber.ToString()); // if (ftStatus != FTDI.FT_STATUS.FT_OK) // { // //continue; // break; // } // bFind = true; // break; // } // } // if(!bFind) // continue; // } // else // { // continue; // } ftStatus = myFtdiDevice.OpenBySerialNumber("DA00UTH1"); if (ftStatus != FTDI.FT_STATUS.FT_OK) { continue; } ftStatus = myFtdiDevice.ResetDevice(); if (ftStatus != FTDI.FT_STATUS.FT_OK) { continue; } ftStatus = myFtdiDevice.SetBaudRate(300); if (ftStatus != FTDI.FT_STATUS.FT_OK) { continue; } ftStatus = myFtdiDevice.SetTimeouts(30000, 30000); if (ftStatus != FTDI.FT_STATUS.FT_OK) { continue; } byte[] txbuf = new byte[100]; txbuf[0] = 0xf0; ftStatus = myFtdiDevice.Write(txbuf, 1, ref numBytesRead); if (ftStatus != FTDI.FT_STATUS.FT_OK) { continue; } Thread.Sleep(200); txbuf[0] = 0x30; txbuf[1] = 0x00; for (int i = 0; i < 8; i++) { txbuf[2 + i] = bPass[i]; } txbuf[10] = WFNetLib.Verify.GetVerify_byteSum(txbuf, 10); ftStatus = myFtdiDevice.Write(txbuf, 11, ref numBytesRead); if (ftStatus != FTDI.FT_STATUS.FT_OK) { continue; } ftStatus = myFtdiDevice.Read(rxbuf, 11, ref numBytesRead); if (ftStatus != FTDI.FT_STATUS.FT_OK) { continue; } ftStatus = myFtdiDevice.Close(); if (ftStatus != FTDI.FT_STATUS.FT_OK) { continue; } if (rxbuf[2] == 0x80 && rxbuf[3] == 0x00 && rxbuf[4] == 0x00 && rxbuf[5] == 0x00 && rxbuf[6] == 0x00 && rxbuf[7] == 0x00 && rxbuf[8] == 0x00 && rxbuf[9] == 0x00) { Thread.Sleep(5000); continue; } if (rxbuf[2] == 0x00 && rxbuf[3] == 0x00 && rxbuf[4] == 0x00 && rxbuf[5] == 0x00 && rxbuf[6] == 0x00 && rxbuf[7] == 0x00 && rxbuf[8] == 0x00 && rxbuf[9] == 0x00) { Thread.Sleep(5000); continue; } bOK = true; break; } catch { } } if (bOK) { ESLRecodeData esl = new ESLRecodeData(); esl.Pass = eq.Pass; esl.Ret = WFNetLib.StringFunc.StringsFunction.byteToHexStr(rxbuf, 2, 8, ""); ESLRecodeDataDBOption.Insert(esl); elog.Ret = esl.Ret; } else { elog.Ret = "err"; } ESLWorkLogDataDBOption.Insert(elog); ESLQueueDataDBOption.delete(eq.Pass, eq.IP, eq.DeviceID, eq.sTime.ToString()); } catch (System.Exception ex) { elog.Ret = "err"; ESLWorkLogDataDBOption.Insert(elog); ESLQueueDataDBOption.delete(eq.Pass, eq.IP, eq.DeviceID, eq.sTime.ToString()); TextLog.AddTextLog("Thread_Unkown:" + ex.Message, Global.txtLogFolder + "ESLPass.txt", true); } } } }
public void SetTimeouts(uint a, uint b) { ftStatus = myFtdiDevice.SetTimeouts(a, b); }
public SetupDialogForm() { InitializeComponent(); UInt32 ftdiDeviceCount = 0; FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OK; // Create new instance of the FTDI device class FTDI tempFtdiDevice = new FTDI(); // Determine the number of FTDI devices connected to the machine ftStatus = tempFtdiDevice.GetNumberOfDevices(ref ftdiDeviceCount); // Check status if (ftStatus == FTDI.FT_STATUS.FT_OK) { AvailableDevicesListBox.Items.Add("# of FTDI devices = " + ftdiDeviceCount.ToString()); } else { throw new ASCOM.InvalidValueException("Error getting count FTDI devices"); } if (ftdiDeviceCount > 0) { // Allocate storage for device info list FTDI.FT_DEVICE_INFO_NODE[] ftdiDeviceList = new FTDI.FT_DEVICE_INFO_NODE[ftdiDeviceCount]; // Populate our device list ftStatus = tempFtdiDevice.GetDeviceList(ftdiDeviceList); //Show device properties if (ftStatus == FTDI.FT_STATUS.FT_OK) { for (UInt32 i = 0; i < ftdiDeviceCount; i++) { if (ftdiDeviceList[i].SerialNumber.Contains("CAM8")) { AvailableDevicesListBox.Items.Add("Device Index: " + i.ToString()); AvailableDevicesListBox.Items.Add("Flags: " + String.Format("{0:x}", ftdiDeviceList[i].Flags)); AvailableDevicesListBox.Items.Add("Type: " + ftdiDeviceList[i].Type.ToString()); AvailableDevicesListBox.Items.Add("ID: " + String.Format("{0:x}", ftdiDeviceList[i].ID)); AvailableDevicesListBox.Items.Add("Location ID: " + String.Format("{0:x}", ftdiDeviceList[i].LocId)); AvailableDevicesListBox.Items.Add("Serial Number: " + ftdiDeviceList[i].SerialNumber.ToString()); AvailableDevicesListBox.Items.Add("Description: " + ftdiDeviceList[i].Description.ToString()); AvailableDevicesListBox.Items.Add(""); } } } else { throw new ASCOM.InvalidValueException("Error getting parameters from FTDI devices"); } } //Close device ftStatus = tempFtdiDevice.Close(); // Initialise current values of user settings from the ASCOM Profile chkTrace.Checked = Camera.traceState; coolerCheckBox.Checked = Camera.coolerEnabledState; //find available com ports in system string[] comPorts; comPorts = SerialPort.GetPortNames(); int j; for (j = 0; j < comPorts.Length; j++) { coolerComPortComboBox.Items.Add(comPorts[j]); if (comPorts[j] == Camera.coolerComPortState) { coolerComPortComboBox.SelectedIndex = j; } } }
public void ClearBuffer() { ftStatus = myFtdiDevice.Purge(0); ftStatus = myFtdiDevice.Purge(1); }
/// <summary> /// Low lever Write wrapper /// </summary> /// <param name="dataBuffer"></param> /// <param name="numBytes"></param> /// <param name="numBytesWritten"></param> /// <returns></returns> public FTDI.FT_STATUS Write(byte[] dataBuffer, int numBytes, ref uint numBytesWritten) { FTDI.FT_STATUS status = _ftdi.Write(dataBuffer, numBytes, ref numBytesWritten); return(status); }
private void AttemptConnect() { connected = false; UInt32 DeviceCount = 0; FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OK; // Create new instance of the FTDI device class ftdi = new FTDI(); // Determine the number of FTDI devices connected to the machine ftStatus = ftdi.GetNumberOfDevices(ref DeviceCount); // Check status if (ftStatus != FTDI.FT_STATUS.FT_OK || DeviceCount == 0) { commStat = CommStatus.NoDevice; return; } commStat = CommStatus.NoElev8; // Allocate storage for device info list FTDI.FT_DEVICE_INFO_NODE[] DeviceList = new FTDI.FT_DEVICE_INFO_NODE[DeviceCount]; try { // Populate our device list ftStatus = ftdi.GetDeviceList(DeviceList); bool FoundElev8 = false; for (int i = 0; i < DeviceCount && FoundElev8 == false; i++) { if (DeviceList[i].Type != FTDI.FT_DEVICE.FT_DEVICE_X_SERIES) { continue; } for (int baud = 0; baud < 2; baud++) { ftStatus = ftdi.OpenBySerialNumber(DeviceList[i].SerialNumber); if (ftStatus == FTDI.FT_STATUS.FT_OK) { string portName; ftdi.GetCOMPort(out portName); if (portName == null || portName == "") { ftdi.Close(); continue; } if (baud == 0) { ftdi.SetBaudRate(115200); // try this first } else { ftdi.SetBaudRate(57600); // then try this (xbee) } ftdi.SetDataCharacteristics(8, 1, 0); ftdi.SetFlowControl(FTDI.FT_FLOW_CONTROL.FT_FLOW_NONE, 0, 0); txBuffer[0] = (byte)'E'; txBuffer[1] = (byte)'l'; txBuffer[2] = (byte)'v'; txBuffer[3] = (byte)'8'; uint written = 0; for (int j = 0; j < 10 && FoundElev8 == false && !quit; j++) // Keep pinging until it replies, or we give up { ftdi.Write(txBuffer, 4, ref written); System.Threading.Thread.Sleep(50); uint bytesAvail = 0; ftdi.GetRxBytesAvailable(ref bytesAvail); // How much data is available from the serial port? if (bytesAvail > 0) { int TestVal = 0; while (bytesAvail > 0 && !quit) { uint bytesRead = 0; ftdi.Read(rxBuffer, 1, ref bytesRead); if (bytesRead == 1) { TestVal = (TestVal << 8) | rxBuffer[0]; if (TestVal == (int)(('E' << 0) | ('l' << 8) | ('v' << 16) | ('8' << 24))) { FoundElev8 = true; commStat = CommStatus.Connected; break; } } if (bytesRead == 0) { break; } } } } if (FoundElev8) { connected = true; if (ConnectionStarted != null) { ConnectionStarted(); } break; } else { ftdi.Close(); } } } } } catch (Exception) { return; } }
/// <summary> /// Close the port /// </summary> /// <returns></returns> public FTDI.FT_STATUS Rescan() { FTDI.FT_STATUS status = _ftdi.Rescan(); return(status); }
public static int eraseEpcsDev(FTDI myFtdiDevice) { int status = 0; // Set FTDI to Bit-bang mode ftStatus = myFtdiDevice.SetBitMode(0x4f, 0x1); //0x4f -- 01001111 ftStatus = myFtdiDevice.SetBaudRate(153600); // Reset PINs; uint numByteWr = 0; byte[] byteWr = new byte[1]; byteWr[0] = DEF_VALUE; ftStatus = myFtdiDevice.Write(byteWr, 1, ref numByteWr); //Set NCS to 0 string strFtWr = strFtDataSetBit(NCS, 0); // Send Write enable strFtWr += strFtDataMsb(AS_WRITE_ENABLE); // Set NCS to 1 strFtWr += strFtDataSetBit(NCS, 1); //Set NCS to 0 strFtWr += strFtDataSetBit(NCS, 0); // Send Erase bulk strFtWr += strFtDataMsb(AS_ERASE_BULK); //Set NCS to 1 strFtWr += strFtDataSetBit(NCS, 1); //Set NCS to 0 strFtWr += strFtDataSetBit(NCS, 0); // Send Read status strFtWr += strFtDataMsb(AS_READ_STATUS); uint numFtWr = 0; ftStatus = myFtdiDevice.Write(strFtWr, strFtWr.Length, ref numFtWr); // Read status byte byteStatusReg = 0; ftStatus = ftByteRead(ref byteStatusReg, myFtdiDevice); byteStatusReg = byteReverse(byteStatusReg); while ((byteStatusReg & 0x01) == 1) { byteStatusReg = 0; ftStatus = ftByteRead(ref byteStatusReg, myFtdiDevice); byteStatusReg = byteReverse(byteStatusReg); } //Set NCS to 1 ftStatus = myFtdiDevice.Write(strFtDataSetBit(NCS, 1), 1, ref numFtWr); if (ftStatus == FTDI.FT_STATUS.FT_OK) { status = 0; } else { status = -1; } return(status); }
private void fdti_init() { // Determine the number of FTDI devices connected to the machine ftStatus = myFtdiDevice.GetNumberOfDevices(ref ftdiDeviceCount); // Check status if (ftStatus == FTDI.FT_STATUS.FT_OK) { // MessageBox.Show("Number of FTDI devices: " + ftdiDeviceCount.ToString()); // richTextBox1.AppendText("Number of FTDI devices: " + ftdiDeviceCount.ToString()); } else { // Wait for a key press MessageBox.Show("Failed to get number of devices (error " + ftStatus.ToString() + ")"); //this.Close(); // return; } // If no devices available, return if (ftdiDeviceCount == 0) { // Wait for a key press MessageBox.Show("Failed to get number of devices (error " + ftStatus.ToString() + ")"); // this.Close(); return; } // Allocate storage for device info list FTDI.FT_DEVICE_INFO_NODE[] ftdiDeviceList = new FTDI.FT_DEVICE_INFO_NODE[ftdiDeviceCount]; // Populate our device list ftStatus = myFtdiDevice.GetDeviceList(ftdiDeviceList); if (ftStatus == FTDI.FT_STATUS.FT_OK) { //for (UInt32 i = 0; i < ftdiDeviceCount; i++) //{ // // + Environment.NewLine // richTextBox1.Text += ("Device Index: " + i.ToString()); // richTextBox1.Text += ("Flags: " + String.Format("{0:x}", ftdiDeviceList[i].Flags)); // richTextBox1.Text += ("Type: " + ftdiDeviceList[i].Type.ToString()); // richTextBox1.Text += ("ID: " + String.Format("{0:x}", ftdiDeviceList[i].ID)); // richTextBox1.Text += ("Location ID: " + String.Format("{0:x}", ftdiDeviceList[i].LocId)); // richTextBox1.Text += ("Serial Number: " + ftdiDeviceList[i].SerialNumber.ToString()); // richTextBox1.Text += ("Description: " + ftdiDeviceList[i].Description.ToString()); // richTextBox1.Text += (""); //} MessageBox.Show("FT_OK"); } // Open first device in our list by serial number ftStatus = myFtdiDevice.OpenBySerialNumber(ftdiDeviceList[0].SerialNumber); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press MessageBox.Show("Failed to open device (error " + ftStatus.ToString() + ")"); return; } ftStatus = myFtdiDevice.SetBitMode(0xFF, FTDI.FT_BIT_MODES.FT_BIT_MODE_RESET); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press MessageBox.Show("Failed to set Reset mode (error " + ftStatus.ToString() + ")"); return; } // Thread.Sleep(10); ftStatus = myFtdiDevice.SetBitMode(0xFF, FTDI.FT_BIT_MODES.FT_BIT_MODE_SYNC_FIFO); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press MessageBox.Show("Failed to set FIFO mode (error " + ftStatus.ToString() + ")"); return; } // Set flow control - set RTS/CTS flow control if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press MessageBox.Show("Failed to set flow control (error " + ftStatus.ToString() + ")"); return; } //++++++++++++++++++++++++++++++++++++++++++ ftStatus = myFtdiDevice.SetLatency(0); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press MessageBox.Show("Failed to st latency (error " + ftStatus.ToString() + ")"); return; } //++++++++++++++++++++++++++++++++++++++++++ //++++++++++++++++++++++++++++++++++++++++++ // Set read timeout to 5 seconds, write timeout to infinite ftStatus = myFtdiDevice.SetTimeouts(2000, 500); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press MessageBox.Show("Failed to set timeouts (error " + ftStatus.ToString() + ")"); return; } ftdiInitISactive = true; }
static void Main(string[] args) { //var timer = new Timer(CheckStatus, null, 500, 250); //Console.WriteLine(timer.GetLifetimeService()); UInt32 ftdiDeviceCount = 0; FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OK; // Create new instance of the FTDI device class FTDI myFtdiDevice = new FTDI(); // Open first device in our list by serial number ftStatus = myFtdiDevice.OpenBySerialNumber("A99C59XB"); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press Console.WriteLine("Failed to open device (error " + ftStatus.ToString() + ")"); Console.ReadKey(); return; } // Set up device data parameters // Set Baud rate to 9600 ftStatus = myFtdiDevice.SetBaudRate(9600); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press Console.WriteLine("Failed to set Baud rate (error " + ftStatus.ToString() + ")"); Console.ReadKey(); return; } // Set data characteristics - Data bits, Stop bits, Parity ftStatus = myFtdiDevice.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) { // Wait for a key press Console.WriteLine("Failed to set data characteristics (error " + ftStatus.ToString() + ")"); Console.ReadKey(); return; } Console.WriteLine("Ready for write"); Console.ReadKey(); // Perform loop back - make sure loop back connector is fitted to the device // Write string data to the device //string dataToWrite = "Hello world!"; byte[] greating = { 1, 159 }; UInt32 numBytesWritten = 0; // Note that the Write method is overloaded, so can write string or byte array data ftStatus = myFtdiDevice.Write(greating, greating.Length, ref numBytesWritten); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press Console.WriteLine("Failed to write to device (error " + ftStatus.ToString() + ")"); Console.ReadKey(); return; } //Check the amount of data available to read // In this case we know how much data we are expecting, // so wait until we have all of the bytes we have sent. UInt32 numBytesAvailable = 0; do { ftStatus = myFtdiDevice.GetRxBytesAvailable(ref numBytesAvailable); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press Console.WriteLine("Failed to get number of bytes available to read (error " + ftStatus.ToString() + ")"); Console.ReadKey(); return; } Thread.Sleep(10); } while (numBytesAvailable < greating.Length); //// Now that we have the amount of data we want available, read it //string readData; byte[] inbuf = new byte[2]; UInt32 numBytesRead = 0; // Note that the Read method is overloaded, so can read string or byte array data ftStatus = myFtdiDevice.Read(inbuf, numBytesAvailable, ref numBytesRead); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press Console.WriteLine("Failed to read data (error " + ftStatus.ToString() + ")"); Console.ReadKey(); return; } foreach (var readData in inbuf) { Console.WriteLine(readData); } // Close our device ftStatus = myFtdiDevice.Close(); // Wait for a key press Console.WriteLine("Press any key to continue."); Console.ReadKey(); Console.ReadKey(); }
public USBCntrl(XElement el) { Name = (string)el.Attribute("nm"); Serial = (string)el.Attribute("serial"); strands.AddRange(from strnd in el.Elements("Strand") select new GECEStrand(strnd, this)); if (!Global.Instance.Settings.BypassUSBControllers) { myFtdiDevice = new FTDI(); do { // Open first device by serial number FTDI.FT_STATUS ftStatus = myFtdiDevice.OpenBySerialNumber(Serial); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press logger.Error("Failed to open device:" + Name + " (error " + ftStatus.ToString() + ")"); break; } ftStatus = myFtdiDevice.Purge(FTDI.FT_PURGE.FT_PURGE_RX + FTDI.FT_PURGE.FT_PURGE_TX); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press logger.Error("Failed to purge device:" + Name + " (error " + ftStatus.ToString() + ")"); break; } ftStatus = myFtdiDevice.InTransferSize(64); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press logger.Error("Failed to set InTransferSize device:" + Name + " (error " + ftStatus.ToString() + ")"); break; } Console.WriteLine("Set to set timeouts"); // Set read timeout to 5 seconds, write timeout to infinite ftStatus = myFtdiDevice.SetTimeouts(5000, 0); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press logger.Error("Failed to set timeouts:" + Name + " (error " + ftStatus.ToString() + ")"); break; } Console.WriteLine("clear the data"); UInt32 numBytesAvailable = 0; ftStatus = myFtdiDevice.GetRxBytesAvailable(ref numBytesAvailable); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press logger.Error("Failed to get number of bytes available to read:" + Name + " (error " + ftStatus.ToString() + ")"); break; } if (numBytesAvailable > 0) { byte[] readData = new byte[numBytesAvailable]; UInt32 numBytesRead = 0; ftStatus = myFtdiDevice.Read(readData, numBytesAvailable, ref numBytesRead); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press logger.Error("Failed to read data:" + Name + " (error " + ftStatus.ToString() + ")"); break; } for (int i = 0; i < numBytesRead; i++) { Console.Write(readData[i].ToString("x") + " "); } } byte[] dataToWrite = { // command sequence length chksum (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, //Resync (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, // (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, // (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, // (byte)0x84, (byte)0x00, (byte)0x01, (byte)0xff, //Stop (byte)0x81, (byte)0x00, (byte)0x02, (byte)0xff, //Set time (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, // <the time> (byte)0x85, (byte)0x00, (byte)0x01, (byte)0xff, //ReSeq (byte)0x82, (byte)0x00, (byte)0x01, (byte)0xff }; //Run uint numBytesWritten = 0; ftStatus = myFtdiDevice.Write(dataToWrite, dataToWrite.Length, ref numBytesWritten); cts = new CancellationTokenSource(); tkn = cts.Token; rxTsk = Task.Factory.StartNew(() => ShowRxData(), tkn); txTsk = Task.Factory.StartNew(() => SendTxData(), tkn); state = 0; } while (false); } for (int ndx = 0; ndx < bufrPool.BoundedCapacity; ndx++) { bufrPool.Add(new USBMsg()); } }
public void Start() { Logging.Info("Starting OpenDmx"); Device device = _data.Device; var deviceFound = false; if (device != null) { var i = FindDeviceIndex(device); if (i >= 0) { deviceFound = true; Logging.Info($"Specified OpenDMX device {device} found at index: {i}"); } } if (device == null || !deviceFound) { device = GetDefaultDevice(); if (device != null) { deviceFound = true; _data.Device = device; Logging.Info($"Using default OpenDMX device {device}"); } } //try to open the device if (deviceFound) { Logging.Info($"Attempting to open OpenDMX device {device}"); Logging.Info($"Attempting to open by serial number {device.SerialNumber}"); _status = _openDmxConnection.OpenBySerialNumber(device.SerialNumber); } else { Logging.Error("No devices found to open."); var message = "No devices found to open."; throw new Exception(message); } if (_status != FTDI.FT_STATUS.FT_OK) //failure { Logging.Error($"Error opening the OpenDMX device {device} : {_status}"); var message = "Failed to open OpenDMX device. Error from Driver: " + _status; throw new Exception(message); } //Initialize the universe and start code to all 0s InitOpenDmx(); for (var i = 0; i < 513; i++) { SetDmxValue(i, 0); } //Create and start the thread that sends the output data to the driver var thread = new Thread(WriteData); thread.Start(); Logging.Info($"Open OpenDMX device {device} successful"); }
static void Main(string[] args) { string deviceSerialNumber = "33VRWQARA"; FTDI.FT_STATUS status = new FTDI.FT_STATUS(); FTDI device = new FTDI(); UInt32 numberOfDevices = 0; int sleepTime = 100; status = device.GetNumberOfDevices(ref numberOfDevices); FTDI.FT_DEVICE_INFO_NODE[] devicelist = new FTDI.FT_DEVICE_INFO_NODE[numberOfDevices]; status = device.GetDeviceList(devicelist); Thread.Sleep(sleepTime); if (status == FTDI.FT_STATUS.FT_OK) Console.WriteLine("We have {0} devices", numberOfDevices); else Console.WriteLine("Failed to get number of devices"); status = device.OpenBySerialNumber(deviceSerialNumber); Thread.Sleep(sleepTime); if(status == FTDI.FT_STATUS.FT_OK) Console.WriteLine("Device {0} is opened", deviceSerialNumber); else Console.WriteLine("Failed to open {0} device", deviceSerialNumber); status = device.SetBitMode(0xff, FTDI.FT_BIT_MODES.FT_BIT_MODE_RESET); Thread.Sleep(sleepTime); if (status == FTDI.FT_STATUS.FT_OK) Console.WriteLine("BitMode is resetted"); else Console.WriteLine("Failed to reset BitMode"); status = device.SetBitMode(0xff, FTDI.FT_BIT_MODES.FT_BIT_MODE_SYNC_FIFO); Thread.Sleep(sleepTime); if (status == FTDI.FT_STATUS.FT_OK) Console.WriteLine("BitMode is {0}", FTDI.FT_BIT_MODES.FT_BIT_MODE_SYNC_FIFO); else Console.WriteLine("Failed to set BitMode"); byte latency = 2; device.SetLatency(latency); Thread.Sleep(sleepTime); if (status == FTDI.FT_STATUS.FT_OK) Console.WriteLine("Latency timer value is {0}", latency); else Console.WriteLine("Failed to set latency"); uint inTransferSize = 0x10000; device.InTransferSize(inTransferSize); Thread.Sleep(sleepTime); if (status == FTDI.FT_STATUS.FT_OK) Console.WriteLine("inTransferSize value is {0}", inTransferSize); else Console.WriteLine("Failed to set inTransferSize"); device.SetFlowControl(FTDI.FT_FLOW_CONTROL.FT_FLOW_RTS_CTS, 0x00, 0x00); Thread.Sleep(sleepTime); if (status == FTDI.FT_STATUS.FT_OK) Console.WriteLine("FlowControl is {0}", FTDI.FT_FLOW_CONTROL.FT_FLOW_RTS_CTS); else Console.WriteLine("Failed to set FlowControl"); device.Purge(FTDI.FT_PURGE.FT_PURGE_RX); uint numBytes = 0; //int cycles = 0; using(FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) { using (BinaryWriter bw = new BinaryWriter(fs)) { while (Console.KeyAvailable == false) { device.GetRxBytesAvailable(ref numBytes); if (numBytes >= 1) { //cycles++; byte[] bBuf = new byte[numBytes]; device.Read(bBuf, numBytes, ref numBytes); bw.Write(bBuf); //if (cycles == 1) //{ // cycles = 0; // Console.WriteLine("{0}", bBuf.Length); //} } if (numBytes >= 0x10000) { Console.WriteLine("Buffer overload!"); } } //Console.WriteLine("Press 'p' to erase control bytes, 'q' to quite"); //ConsoleKeyInfo cki = Console.ReadKey(false); //if (cki.Key == ConsoleKey.Q) // Environment.Exit(-1); //if (cki.Key == ConsoleKey.P) //{ //} } } Console.WriteLine("Key is pressed, end of file writting"); }
public byte[] ReadI2cData(byte address, byte readCount) { SetI2CLinesIdle(); // Set idle line condition SetI2CStart(); // Send the start condition bool bSucceed = SendAddrAndCheckACK(address, true);// Send the general call address 0x00 wr (I2C = 0x00) //if (DataSent != null) //{ // DataSentEventArgs e = new DataSentEventArgs(new byte[] { (byte)(address * 2 + 1) }); // data for read // DataSent(this, e); //} System.Diagnostics.Debug.Print(bSucceed.ToString()); if (!bSucceed) { SetI2CStop(); throw new Exception("I2C Read Data Error"); } dwNumBytesToSend = 0; //Clear output buffer for (int i = 0; i < readCount - 1; i++) { // Read the first byte of data over I2C and ACK it //Clock one byte in OutputBuffer[dwNumBytesToSend++] = 0x20; // Command to clock data byte in MSB first on clock rising edge OutputBuffer[dwNumBytesToSend++] = 0x00; OutputBuffer[dwNumBytesToSend++] = 0x00; // Data length of 0x0000 means 1 byte data to clock in // Clock out one bit...send ack bit as '0' OutputBuffer[dwNumBytesToSend++] = 0x13; // Command to clock data bit out MSB first on clock falling edge OutputBuffer[dwNumBytesToSend++] = 0x00; // Length of 0x00 means 1 bit OutputBuffer[dwNumBytesToSend++] = 0x00; // Data value to clock out is in bit 7 of this value // Put I2C line back to idle (during transfer) state... Clock line driven low, Data line high (open drain) OutputBuffer[dwNumBytesToSend++] = 0x80; // Command to set lower 8 bits of port (ADbus 0-7 on the FT232H) OutputBuffer[dwNumBytesToSend++] = 0xFE; // Set the value of the pins (only affects those set as output) OutputBuffer[dwNumBytesToSend++] = 0xFB; // Set the directions - all pins as output except Bit2(data_in) } OutputBuffer[dwNumBytesToSend++] = 0x20; // Command to clock data byte in MSB first on clock rising edge OutputBuffer[dwNumBytesToSend++] = 0x00; OutputBuffer[dwNumBytesToSend++] = 0x00; // Data length of 0x0000 means 1 byte data to clock in // Clock out one bit...send ack bit as '0' OutputBuffer[dwNumBytesToSend++] = 0x13; // Command to clock data bit out MSB first on clock falling edge OutputBuffer[dwNumBytesToSend++] = 0x00; // Length of 0x00 means 1 bit OutputBuffer[dwNumBytesToSend++] = 0xff; // Data value to clock out is in bit 7 of this value // Put I2C line back to idle (during transfer) state... Clock line driven low, Data line high (open drain) OutputBuffer[dwNumBytesToSend++] = 0x80; // Command to set lower 8 bits of port (ADbus 0-7 on the FT232H) OutputBuffer[dwNumBytesToSend++] = 0xFE; // Set the value of the pins (only affects those set as output) OutputBuffer[dwNumBytesToSend++] = 0xFB; // Set the directions - all pins as output except Bit2(data_in) // This command then tells the MPSSE to send any results gathered back immediately OutputBuffer[dwNumBytesToSend++] = 0x87; // Send answer back immediate command ftStatus = mDevice.Write(OutputBuffer, dwNumBytesToSend, ref dwNumBytesSent); //Send off the commands // =============================================================== // Now wait for the 3 bytes which we read to come back to the host PC // =============================================================== dwNumInputBuffer = 0; ReadTimeoutCounter = 0; ftStatus |= mDevice.GetRxBytesAvailable(ref dwNumInputBuffer); // Get number of bytes in the input buffer while ((dwNumInputBuffer < readCount) && (ftStatus == FT_OK) && (ReadTimeoutCounter < 500)) { // Sit in this loop until // (1) we receive the 3 bytes expected // or (2) a hardware error occurs causing the GetQueueStatus to return an error code // or (3) we have checked 500 times and the expected byte is not coming ftStatus |= mDevice.GetRxBytesAvailable(ref dwNumInputBuffer); // Get number of bytes in the input buffer ReadTimeoutCounter++; Sleep(1); // short delay } // If the loop above exited due to the bytes coming back (not an error code and not a timeout) // then read the bytes available and return True to indicate success if ((ftStatus == FT_OK) && (ReadTimeoutCounter < 500)) { byte [] ByteDataRead = new byte[readCount]; ftStatus = mDevice.Read(ByteDataRead , dwNumInputBuffer, ref dwNumBytesRead); // Now read the data Sleep(10); SetI2CStop(); return ByteDataRead; // Indicate success } else { Sleep(10); SetI2CStop(); throw new Exception("I2C Read Data Error"); } }
public string ReadData() { // Check the amount of data available to read // In this case we know how much data we are expecting, // so wait until we have all of the bytes we have sent. UInt32 numBytesAvailable = 0; do { ftStatus = myFtdiDevice.GetRxBytesAvailable(ref numBytesAvailable); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press Console.WriteLine("Failed to get number of bytes available to read (error " + this.ftStatus + ")"); return string.Empty; } Thread.Sleep(1); } while (numBytesAvailable < 18); //32byte data packet? // Now that we have the amount of data we want available, read it string readData; UInt32 numBytesRead = 0; // Note that the Read method is overloaded, so can read string or byte array data ftStatus = myFtdiDevice.Read(out readData, 18, ref numBytesRead); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press Console.WriteLine("Failed to read data (error " + this.ftStatus + ")"); return string.Empty; } Console.Write(readData); return readData; }
// ############################################################################################################## // Function to write 1 byte, and check if it returns an ACK or NACK by clocking in one bit // We clock one byte out to the I2C Slave // We then clock in one bit from the Slave which is the ACK/NAK bit // Put lines back to the idle state (idle between start and stop is clock low, data high (open-drain) // Returns TRUE if the write was ACKed // ############################################################################################################## bool SendByteAndCheckACK(byte dwDataSend) { dwNumBytesToSend = 0; // Clear output buffer FTDI.FT_STATUS ftStatus = FT_OK; OutputBuffer[dwNumBytesToSend++] = 0x11; // command to clock data bytes out MSB first on clock falling edge OutputBuffer[dwNumBytesToSend++] = 0x00; // OutputBuffer[dwNumBytesToSend++] = 0x00; // Data length of 0x0000 means 1 byte data to clock out OutputBuffer[dwNumBytesToSend++] = dwDataSend; // Actual byte to clock out // Put I2C line back to idle (during transfer) state... Clock line driven low, Data line high (open drain) OutputBuffer[dwNumBytesToSend++] = 0x80; // Command to set lower 8 bits of port (ADbus 0-7 on the FT232H) OutputBuffer[dwNumBytesToSend++] = 0xFE; // Set the value of the pins (only affects those set as output) OutputBuffer[dwNumBytesToSend++] = 0xFB; // Set the directions - all pins as output except Bit2(data_in) // AD0 (SCL) is output driven low // AD1 (DATA OUT) is output high (open drain) // AD2 (DATA IN) is input (therefore the output value specified is ignored) // AD3 to AD7 are inputs driven high (not used in this application) OutputBuffer[dwNumBytesToSend++] = 0x22; // Command to clock in bits MSB first on clock rising edge OutputBuffer[dwNumBytesToSend++] = 0x00; // Length of 0x00 means to scan in 1 bit // This command then tells the MPSSE to send any results gathered back immediately OutputBuffer[dwNumBytesToSend++] = 0x87; //Send answer back immediate command ftStatus = mDevice.Write(OutputBuffer, dwNumBytesToSend, ref dwNumBytesSent); //Send off the commands Sleep(1); // =============================================================== // Now wait for the byte which we read to come back to the host PC // =============================================================== dwNumInputBuffer = 0; ReadTimeoutCounter = 0; ftStatus |= mDevice.GetRxBytesAvailable(ref dwNumInputBuffer); // Get number of bytes in the input buffer while ((dwNumInputBuffer < 1) && (ftStatus == FT_OK) && (ReadTimeoutCounter < 500)) { // Sit in this loop until // (1) we receive the one byte expected // or (2) a hardware error occurs causing the GetQueueStatus to return an error code // or (3) we have checked 500 times and the expected byte is not coming ftStatus |= mDevice.GetRxBytesAvailable(ref dwNumInputBuffer); // Get number of bytes in the input buffer ReadTimeoutCounter++; Sleep(10); // short delay } // If the loop above exited due to the byte coming back (not an error code and not a timeout) if ((ftStatus == FT_OK) && (ReadTimeoutCounter < 500)) { ftStatus = mDevice.Read(InputBuffer, dwNumInputBuffer, ref dwNumBytesRead); // Now read the data if (((InputBuffer[0] & 0x01) == 0x00)) //Check ACK bit 0 on data byte read out { return true; // Return True if the ACK was received } else { //printf("Failed to get ACK from I2C Slave \n"); return false; //Error, can't get the ACK bit } } else { return false; // Failed to get any data back or got an error code back } }
public void WriteData(string data) { // Perform loop back - make sure loop back connector is fitted to the device // Write string data to the device UInt32 numBytesWritten = 0; // Note that the Write method is overloaded, so can write string or byte array data ftStatus = myFtdiDevice.Write(data, data.Length, ref numBytesWritten); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press Console.WriteLine("Failed to write to device (error " + this.ftStatus + ")"); } }
// ############################################################################################################## // Function to write 1 byte, and check if it returns an ACK or NACK by clocking in one bit // This function combines the data and the Read/Write bit to make a single 8-bit value // We clock one byte out to the I2C Slave // We then clock in one bit from the Slave which is the ACK/NAK bit // Put lines back to the idle state (idle between start and stop is clock low, data high (open-drain) // Returns TRUE if the write was ACKed by the slave // ############################################################################################################## bool SendAddrAndCheckACK(byte dwDataSend, bool Read) { dwNumBytesToSend = 0; // Clear output buffer FTDI.FT_STATUS ftStatus = FT_OK; // Combine the Read/Write bit and the actual data to make a single byte with 7 data bits and the R/W in the LSB if (Read == true) { dwDataSend = (byte)((dwDataSend << 1) | 0x01); } else { dwDataSend = (byte)((dwDataSend << 1) & 0xFE); } OutputBuffer[dwNumBytesToSend++] = 0x11; // command to clock data bytes out MSB first on clock falling edge OutputBuffer[dwNumBytesToSend++] = 0x00; // OutputBuffer[dwNumBytesToSend++] = 0x00; // Data length of 0x0000 means 1 byte data to clock out OutputBuffer[dwNumBytesToSend++] = dwDataSend; // Actual byte to clock out // Put I2C line back to idle (during transfer) state... Clock line driven low, Data line high (open drain) OutputBuffer[dwNumBytesToSend++] = 0x80; // Command to set lower 8 bits of port (ADbus 0-7 on the FT232H) OutputBuffer[dwNumBytesToSend++] = 0xFE; // Set the value of the pins (only affects those set as output) OutputBuffer[dwNumBytesToSend++] = 0xFB; // Set the directions - all pins as output except Bit2(data_in) // AD0 (SCL) is output driven low // AD1 (DATA OUT) is output high (open drain) // AD2 (DATA IN) is input (therefore the output value specified is ignored) // AD3 to AD7 are inputs driven high (not used in this application) OutputBuffer[dwNumBytesToSend++] = 0x22; // Command to clock in bits MSB first on clock rising edge OutputBuffer[dwNumBytesToSend++] = 0x00; // Length of 0x00 means to scan in 1 bit // This command then tells the MPSSE to send any results gathered back immediately OutputBuffer[dwNumBytesToSend++] = 0x87; //Send answer back immediate command ftStatus = mDevice.Write(OutputBuffer, dwNumBytesToSend, ref dwNumBytesSent); //Send off the commands Sleep(10); //Check if ACK bit received by reading the byte sent back from the FT232H containing the ACK bit ftStatus = mDevice.Read(InputBuffer, 1, ref dwNumBytesRead); //Read one byte from device receive buffer if ((ftStatus != FT_OK) || (dwNumBytesRead == 0)) { //printf("Failed to get ACK from I2C Slave \n"); return false; //Error, can't get the ACK bit } else { if (((InputBuffer[0] & 0x01) != 0x00)) //Check ACK bit 0 on data byte read out { //printf("Failed to get ACK from I2C Slave \n"); return false; //Error, can't get the ACK bit } } return true; // Return True if the ACK was received }
public void Close() { // Close our device ftStatus = myFtdiDevice.Close(); }
//------------------------------------------------------------------------------------------------- public FTDI.FT_STATUS readSPIPacket(ref byte[] inPacket, ref uint inLength) { uint RxQueue = 0; ftStatus = SPI_Device.GetRxBytesAvailable(ref RxQueue); if (ftStatus != FTDI.FT_STATUS.FT_OK) { return (ftStatus); } // get the input data // read the input data ftStatus = SPI_Device.Read(inPacket, RxQueue, ref inLength); if (ftStatus != FTDI.FT_STATUS.FT_OK) { return (ftStatus); } return (ftStatus); }
static void Main(string[] args) { string deviceSerialNumber = "33VRWQARA"; FTDI.FT_STATUS status = new FTDI.FT_STATUS(); FTDI device = new FTDI(); UInt32 numberOfDevices = 0; int sleepTime = 100; status = device.GetNumberOfDevices(ref numberOfDevices); FTDI.FT_DEVICE_INFO_NODE[] devicelist = new FTDI.FT_DEVICE_INFO_NODE[numberOfDevices]; status = device.GetDeviceList(devicelist); Thread.Sleep(sleepTime); if (status == FTDI.FT_STATUS.FT_OK) Console.WriteLine("We have {0} devices", numberOfDevices); else Console.WriteLine("Failed to get number of devices"); status = device.OpenBySerialNumber(deviceSerialNumber); Thread.Sleep(sleepTime); if (status == FTDI.FT_STATUS.FT_OK) Console.WriteLine("Device {0} is opened", deviceSerialNumber); else Console.WriteLine("Failed to open {0} device", deviceSerialNumber); status = device.SetBitMode(0xff, FTDI.FT_BIT_MODES.FT_BIT_MODE_RESET); Thread.Sleep(sleepTime); if (status == FTDI.FT_STATUS.FT_OK) Console.WriteLine("BitMode is resetted"); else Console.WriteLine("Failed to reset BitMode"); status = device.SetBitMode(0xff, FTDI.FT_BIT_MODES.FT_BIT_MODE_SYNC_FIFO); Thread.Sleep(sleepTime); if (status == FTDI.FT_STATUS.FT_OK) Console.WriteLine("BitMode is {0}", FTDI.FT_BIT_MODES.FT_BIT_MODE_SYNC_FIFO); else Console.WriteLine("Failed to set BitMode"); byte latency = 2; device.SetLatency(latency); Thread.Sleep(sleepTime); if (status == FTDI.FT_STATUS.FT_OK) Console.WriteLine("Latency timer value is {0}", latency); else Console.WriteLine("Failed to set latency"); uint inTransferSize = 0x10000; device.InTransferSize(inTransferSize); Thread.Sleep(sleepTime); if (status == FTDI.FT_STATUS.FT_OK) Console.WriteLine("inTransferSize value is {0}", inTransferSize); else Console.WriteLine("Failed to set inTransferSize"); device.SetFlowControl(FTDI.FT_FLOW_CONTROL.FT_FLOW_RTS_CTS, 0x00, 0x00); Thread.Sleep(sleepTime); if (status == FTDI.FT_STATUS.FT_OK) Console.WriteLine("FlowControl is {0}", FTDI.FT_FLOW_CONTROL.FT_FLOW_RTS_CTS); else Console.WriteLine("Failed to set FlowControl"); device.Purge(FTDI.FT_PURGE.FT_PURGE_RX); using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None)) { using (BinaryReader br = new BinaryReader(fs)) { int chunkLendth = 0x10000; byte[] chunk; uint numBytesWritten = 0; //uint TxQueue = 0; while (((chunk = br.ReadBytes(chunkLendth)).Length > 0) && (Console.KeyAvailable == false)) { //status = device.GetTxBytesWaiting(ref TxQueue); //if (status != FTDI.FT_STATUS.FT_OK) // Console.WriteLine("status!=ok"); //while (TxQueue != 0) // status = device.GetTxBytesWaiting(ref TxQueue); status = device.Write(chunk, chunk.Length, ref numBytesWritten); if (numBytesWritten != chunk.Length) Console.WriteLine("Error writting to the device,\r\nchunk.Length={0}\r\nnumBytesWritten={1}", chunk.Length, numBytesWritten); } } } Console.WriteLine("Key is pressed, end of file writting"); }
private void WorkingThread() { try { // opóźnienie startu Thread.Sleep(3000); // skasowanie listy urządzeń Globals.Instance.ClearDevices(); List <string> serialNumbers = new List <string>(); FTDI.FT_STATUS result = FTDI.FT_STATUS.FT_OK; FTDI ftdi = new FTDI(); while (!_stop) { // łączenie z FSUIPC if (!FS.FSUIPC.FS.IsConnected) { FS.FSUIPC.FS.Connect(); } uint devCount = 0; try { result = ftdi.GetNumberOfDevices(ref devCount); } catch { } if (result == FTDI.FT_STATUS.FT_OK) { FTDI.FT_DEVICE_INFO_NODE[] deviceList = new FTDI.FT_DEVICE_INFO_NODE[devCount]; if (devCount > 0) { try { result = ftdi.GetDeviceList(deviceList); } catch (Exception) { } } else { result = FTDI.FT_STATUS.FT_OK; } if (result == FTDI.FT_STATUS.FT_OK) { // usunięcie urządzeń niepodpiętych Device[] _devices = Globals.Instance.Devices; { int index = _devices.Length; while (index-- > 0) { Device device = _devices[index]; if (device.SerialNumber != "FAKE" && Array.Find <FTDI.FT_DEVICE_INFO_NODE>(deviceList, delegate(FTDI.FT_DEVICE_INFO_NODE o) { return(o.SerialNumber == device.SerialNumber); }) == null) { Globals.Instance.RemoveDevice(_devices[index]); serialNumbers.Remove(device.SerialNumber); device.TurnOff(); } } } for (int i = 0; i < deviceList.Length; i++) { if (deviceList[i].Type == FTDI.FT_DEVICE.FT_DEVICE_232R) { string sn = deviceList[i].SerialNumber; if (!serialNumbers.Contains(sn)) { serialNumbers.Add(sn); // otwarcie połączenia z urządzeniem FTD2XX_NET.FTDI driver = new FTDI(); FTD2XX_NET.FTDI.FT_STATUS status = driver.OpenBySerialNumber(sn); if (status != FTD2XX_NET.FTDI.FT_STATUS.FT_OK) { driver.Close(); driver = null; continue; } // odczytanie EEPROM FTD2XX_NET.FTDI.FT232R_EEPROM_STRUCTURE eeprom = new FTD2XX_NET.FTDI.FT232R_EEPROM_STRUCTURE(); status = driver.ReadFT232REEPROM(eeprom); if (status != FTD2XX_NET.FTDI.FT_STATUS.FT_OK) { driver.Close(); driver = null; continue; } // odczytanie producenta "simPROJECT" if (eeprom.Manufacturer.ToUpperInvariant() != "SIMPROJECT") { driver.Close(); driver = null; continue; } driver.Close(); driver = null; Device device = DeviceFactory.CreateDevice(deviceList[i]); if (device != null) { Globals.Instance.AddDevice(device); device.SetPlane(Globals.Instance.CurrentPlane); device.TurnOn(); } } } } } } Thread.Sleep(3000); } } catch (ThreadAbortException) { } catch (Exception ex) { Debug.WriteLine(string.Format("Błąd w wątku śledzącym urządzenia: {0}", ex)); } finally { } }
// ############################################################################################################## // Function to set the I2C Stop state on the I2C clock and data lines // It takes the clock line high whilst keeping data low, and then takes both lines high // It also sends a GPIO command to set bit 6 of ACbus high to turn off the LED. This acts as an activity indicator // Turns on (low) during the I2C Start and off (high) during the I2C stop condition, giving a short blink. // ############################################################################################################## void SetI2CStop() { dwNumBytesToSend = 0; //Clear output buffer uint dwCount; // Initial condition for the I2C Stop - Pull data low (Clock will already be low and is kept low) for(dwCount=0; dwCount<4; dwCount++) // Repeat commands to ensure the minimum period of the stop setup time is achieved { OutputBuffer[dwNumBytesToSend++] = 0x80; // Command to set directions of ADbus and data values for pins set as o/p OutputBuffer[dwNumBytesToSend++] = 0xFC; // put data and clock low OutputBuffer[dwNumBytesToSend++] = 0xFB; // Set all pins as output except bit 2 which is the data_in } // Clock now goes high (open drain) for(dwCount=0; dwCount<4; dwCount++) // Repeat commands to ensure the minimum period of the stop setup time is achieved { OutputBuffer[dwNumBytesToSend++] = 0x80; // Command to set directions of ADbus and data values for pins set as o/p OutputBuffer[dwNumBytesToSend++] = 0xFD; // put data low, clock remains high (open drain, pulled up externally) OutputBuffer[dwNumBytesToSend++] = 0xFB; // Set all pins as output except bit 2 which is the data_in } // Data now goes high too (both clock and data now high / open drain) for(dwCount=0; dwCount<4; dwCount++) // Repeat commands to ensure the minimum period of the stop hold time is achieved { OutputBuffer[dwNumBytesToSend++] = 0x80; // Command to set directions of ADbus and data values for pins set as o/p OutputBuffer[dwNumBytesToSend++] = 0xFF; // both clock and data now high (open drain, pulled up externally) OutputBuffer[dwNumBytesToSend++] = 0xFB; // Set all pins as output except bit 2 which is the data_in } // Turn the LED off by setting port AC6 high. OutputBuffer[dwNumBytesToSend++] = 0x82; // Command to set directions of upper 8 pins and force value on bits set as output OutputBuffer[dwNumBytesToSend++] = 0xFF; // All lines high (including bit 6 which drives the LED) OutputBuffer[dwNumBytesToSend++] = 0x40; // Only bit 6 is output ftStatus = mDevice.Write(OutputBuffer, dwNumBytesToSend, ref dwNumBytesSent); //Send off the commands }
/// <summary> /// initialize device /// </summary> /// <returns></returns> public bool Init() { FTDI.FT_STATUS ftStatus = mDevice.ResetDevice(); ftStatus |= mDevice.GetRxBytesAvailable(ref dwNumInputBuffer);// Get number of bytes in the input buffer if ((ftStatus == FTDI.FT_STATUS.FT_OK) && (dwNumInputBuffer > 0)) { mDevice.Read(InputBuffer, dwNumInputBuffer, ref dwNumBytesRead); } ftStatus |= mDevice.InTransferSize(65536); // Set USB request transfer sizes ftStatus |= mDevice.SetCharacters(0, false, 0, false); // Disable event and error characters ftStatus |= mDevice.SetTimeouts(5000, 5000); // Set the read and write timeouts to 5 seconds ftStatus |= mDevice.SetLatency(16); // Keep the latency timer at default of 16ms ftStatus |= mDevice.SetBitMode(0x0, 0x00); // Reset the mode to whatever is set in EEPROM ftStatus |= mDevice.SetBitMode(0x0, 0x02); // Enable MPSSE mode // Inform the user if any errors were encountered if (ftStatus != FT_OK) { return false; } Sleep(50); SynchroniseMPSSEbyAA(); SynchroniseMPSSEbyAB(); ConfigMPSSE_Setting(); ConfigMPSSE_IO_Pins(); return (ftStatus == FTDI.FT_STATUS.FT_OK); }
//------------------------------------------------------------------------------------------------- public FTDI.FT_STATUS writeSPIPacket(byte[] outPacket, uint outLength) { uint lBytesDone = 0; ftStatus = SPI_Device.Purge(0x03); if (ftStatus != FTDI.FT_STATUS.FT_OK) { return (ftStatus); } ftStatus = SPI_Device.Write(outPacket, (int)outLength, ref lBytesDone); if (ftStatus != FTDI.FT_STATUS.FT_OK) { return (ftStatus); } return (ftStatus); }
public bool Initialize(out string message) // Desc: Initilize USB communication // Output: message: Message // bool: true = success, false = fail { uint ftdiDeviceCount = 0; uint i; uint myDeviceNum = 0; FTDI.FT_DEVICE_INFO_NODE[] ftdiDeviceList; FTDI.FT2232H_EEPROM_STRUCTURE myEEData = new FTDI.FT2232H_EEPROM_STRUCTURE(); // Determine the number of FTDI devices connected to the machine ftStatus = myFtdiDevice.GetNumberOfDevices(ref ftdiDeviceCount); if (ftStatus != FTDI.FT_STATUS.FT_OK) { message = "FTDI GetNumberOfDevices Failed"; return(false); } if (ftdiDeviceCount == 0) { message = "No device found"; return(false); } // Get device info ftdiDeviceList = new FTDI.FT_DEVICE_INFO_NODE[ftdiDeviceCount]; ftStatus = myFtdiDevice.GetDeviceList(ftdiDeviceList); if (ftStatus != FTDI.FT_STATUS.FT_OK) { message = "FTDI GetDeviceList Failed"; return(false); } if (ftdiDeviceList[0] == null) { message = "FTDI GetDeviceList Failed"; return(false); } // Determine which device to use for (i = 0; i < ftdiDeviceCount; i++) { if (ftdiDeviceList[i].Description == "TTL232R") { myDeviceNum = i; break; } } if (i == ftdiDeviceCount) { message = "FTDI devices doesn't fit the description"; return(false); } // Open the selected device ftStatus = myFtdiDevice.OpenBySerialNumber(ftdiDeviceList[myDeviceNum].SerialNumber); if (ftStatus != FTDI.FT_STATUS.FT_OK) { message = "FTDI OpenBySerialNumber Failed"; return(false); } // Setup baud rate ftStatus = myFtdiDevice.SetBaudRate(1250000); // 9600 if (ftStatus != FTDI.FT_STATUS.FT_OK) { message = "FTDI SetBaudRate Failed"; return(false); } // Set data characteristics - Data bits, Stop bits, Parity ftStatus = myFtdiDevice.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) { message = "FTDI SetDataCharacteristics Failed"; return(false); } // Set flow control - set RTS/CTS flow control ftStatus = myFtdiDevice.SetFlowControl(FTDI.FT_FLOW_CONTROL.FT_FLOW_NONE, 0x00, 0x00); if (ftStatus != FTDI.FT_STATUS.FT_OK) { message = "FTDI SetFlowControl Failed"; return(false); } // Set read timeout, write timeout ftStatus = myFtdiDevice.SetTimeouts(3000, 3000); if (ftStatus != FTDI.FT_STATUS.FT_OK) { message = "FTDI SetTimeouts Failed"; return(false); } // Show result message = "Initialization complete"; initialized = true; return(true); }
// ############################################################################################################## // Function to set all lines to idle states // For I2C lines, it releases the I2C clock and data lines to be pulled high externally // For the remainder of port AD, it sets AD3/4/5/6/7 as inputs as they are unused in this application // For the LED control, it sets AC6 as an output with initial state high (LED off) // For the remainder of port AC, it sets AC0/1/2/3/4/5/7 as inputs as they are unused in this application // ############################################################################################################## private void SetI2CLinesIdle() { dwNumBytesToSend = 0; //Clear output buffer // Set the idle states for the AD lines OutputBuffer[dwNumBytesToSend++] = 0x80; // Command to set directions of ADbus and data values for pins set as o/p OutputBuffer[dwNumBytesToSend++] = 0xFF; // Set all 8 lines to high level (only affects pins which are output) OutputBuffer[dwNumBytesToSend++] = 0xFB; // Set all pins as output except bit 2 which is the data_in // IDLE line states are ... // AD0 (SCL) is output high (open drain, pulled up externally) // AD1 (DATA OUT) is output high (open drain, pulled up externally) // AD2 (DATA IN) is input (therefore the output value specified is ignored) // AD3 to AD7 are inputs (not used in this application) // Set the idle states for the AC lines OutputBuffer[dwNumBytesToSend++] = 0x82; // Command to set directions of ACbus and data values for pins set as o/p OutputBuffer[dwNumBytesToSend++] = 0xFF; // Set all 8 lines to high level (only affects pins which are output) OutputBuffer[dwNumBytesToSend++] = 0x40; // Only bit 6 is output // IDLE line states are ... // AC6 (LED) is output driving high // AC0/1/2/3/4/5/7 are inputs (not used in this application) ftStatus = mDevice.Write(OutputBuffer, dwNumBytesToSend, ref dwNumBytesSent); //Send off the commands }
// ############################################################################################################## // Function to set the I2C Start state on the I2C clock and data lines // It pulls the data line low and then pulls the clock line low to produce the start condition // It also sends a GPIO command to set bit 6 of ACbus low to turn on the LED. This acts as an activity indicator // Turns on (low) during the I2C Start and off (high) during the I2C stop condition, giving a short blink. // ############################################################################################################## void SetI2CStart() { dwNumBytesToSend = 0; //Clear output buffer uint dwCount; // Pull Data line low, leaving clock high (open-drain) for(dwCount=0; dwCount < 4; dwCount++) // Repeat commands to ensure the minimum period of the start hold time is achieved { OutputBuffer[dwNumBytesToSend++] = 0x80; // Command to set directions of ADbus and data values for pins set as o/p OutputBuffer[dwNumBytesToSend++] = 0xFD; // Bring data out low (bit 1) OutputBuffer[dwNumBytesToSend++] = 0xFB; // Set all pins as output except bit 2 which is the data_in } // Pull Clock line low now, making both clcok and data low for(dwCount=0; dwCount < 4; dwCount++) // Repeat commands to ensure the minimum period of the start setup time is achieved { OutputBuffer[dwNumBytesToSend++] = 0x80; // Command to set directions of ADbus and data values for pins set as o/p OutputBuffer[dwNumBytesToSend++] = 0xFC; // Bring clock line low too to make clock and data low OutputBuffer[dwNumBytesToSend++] = 0xFB; // Set all pins as output except bit 2 which is the data_in } // Turn the LED on by setting port AC6 low. OutputBuffer[dwNumBytesToSend++] = 0x82; // Command to set directions of upper 8 pins and force value on bits set as output OutputBuffer[dwNumBytesToSend++] = 0xBF; // Bit 6 is going low OutputBuffer[dwNumBytesToSend++] = 0x40; // Only bit 6 is output ftStatus = mDevice.Write(OutputBuffer, dwNumBytesToSend, ref dwNumBytesSent); //Send off the commands }