public Int16 ReadRegister(byte slave_addr) { _ftdi.Purge(FTDI.FT_PURGE.FT_PURGE_RX | FTDI.FT_PURGE.FT_PURGE_TX); List <byte> buffer = new List <byte>(); // Frame 1 - Slave addr buffer.AddRange(formStart()); // Start buffer.AddRange(formSlaveAddrFrame(slave_addr, FTI2C.RW.READ)); // Slave addr + R/W // SDA tristate, SCL low buffer.AddRange(formSetDataBits(BUS.ADBUS, 0x02, 0x01)); // Read Byte buffer.Add(0x20); buffer.Add(0x00); buffer.Add(0x00); // Send ACK buffer.AddRange(formSetDataBits(BUS.ADBUS, 0x00, 0x03)); buffer.Add(0x12); buffer.Add(0x00); buffer.Add(0x00); // SDA tristate, SCL low buffer.AddRange(formSetDataBits(BUS.ADBUS, 0x02, 0x01)); // Read 8 bits buffer.Add(0x20); buffer.Add(0x00); buffer.Add(0x00); buffer.Add(0x12); buffer.Add(0x00); buffer.Add(0x00); buffer.AddRange(formStop()); rawWrite(buffer.ToArray());// sent of commands uint c = 0; c = waifForRxDataCount(3); byte[] readdata = rawRead(c); byte ack = (byte)(readdata[0] & 0x01); if (ack != 0) { throw new FTI2CException("No ACK"); } Int16 value = (Int16)((readdata[1] << 8) | (readdata[2])); return(value); }
public override void CommClrBuff() { try { ftStatus = ftdi.Purge(FTDI.FT_PURGE.FT_PURGE_RX | FTDI.FT_PURGE.FT_PURGE_TX); if (ftStatus != FTDI.FT_STATUS.FT_OK) { throw new Bsl430NetException(370, ftStatus.ToString()); } } catch (Exception ex) { throw new Bsl430NetException(371, ex); } }
/* Close the device safely */ public void OnExit() { Thread.EndThreadAffinity(); // Stop acquisition myFtdiDevice.Purge(FTDI.FT_PURGE.FT_PURGE_TX | FTDI.FT_PURGE.FT_PURGE_RX); wBuffer[0] = 254; wBuffer[1] = 0; myFtdiDevice.Write(wBuffer, 2, ref writenValues); myFtdiDevice.Purge(FTDI.FT_PURGE.FT_PURGE_TX | FTDI.FT_PURGE.FT_PURGE_RX); // Close device myFtdiDevice.Close(); this.Abort(); }
/// <summary> /// Command RHA2000-EVAL board to start streaming amplifier data to PC. /// </summary> public void Start() { if (!synthDataMode) { FTDI.FT_STATUS ftStatus; // Purge receive buffer myFtdiDeviceA.Purge(FTDI.FT_PURGE.FT_PURGE_RX); // The RHA2000-EVAL board is controlled by sending one-byte ASCII command characters over // the USB interface. The 'S' character commands the board to start streaming amplifier // data to the PC. UInt32 numBytesWritten = 0; Byte[] myChars = { 83 }; // 'S' = start data transfer ftStatus = myFtdiDeviceA.Write(myChars, 1, ref numBytesWritten); if (ftStatus != FTDI.FT_STATUS.FT_OK) { UsbException e = new UsbException("Could not write to Intan USB device"); throw e; } // Resync to channel 0. this.ResyncA(); } running = true; dataJustStarted = true; }
public void sendMsg(byte[] dataToWrite) { // purge the rest of the message ftStatus = ftdi_handle.Purge(FTDI.FT_PURGE.FT_PURGE_RX); if (ftStatus != FTDI.FT_STATUS.FT_OK) { listBox1.Items.Add("Failed to Purge RX buffer (error " + ftStatus.ToString() + ")"); return; } // Write string data to the device //byte[] dataToWrite = sRN_DeviceIdent_BA; UInt32 numBytesWritten = 0; // Note that the Write method is overloaded, so can write string or byte array data ftStatus = ftdi_handle.Write(dataToWrite, dataToWrite.Length, ref numBytesWritten); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press listBox1.Items.Add("Failed to write to device (error " + ftStatus.ToString() + ")"); return; } //listBox2.Items.Add(BitConverter.ToString(dataToWrite)); return; }
public bool Connect() { FT_STATUS status; bool result; uint numberOfDevices = 0; ftdi.GetNumberOfDevices(ref numberOfDevices); if (numberOfDevices == 0) { result = false; } else if ((status = ftdi.OpenByIndex(0)) != FT_STATUS.FT_OK) { result = false; } else if ((status = ftdi.SetBaudRate(250000)) != FT_STATUS.FT_OK) { result = false; } else if ((status = ftdi.SetDataCharacteristics(FT_DATA_BITS.FT_BITS_8, FT_STOP_BITS.FT_STOP_BITS_2, FT_PARITY.FT_PARITY_NONE)) != FT_STATUS.FT_OK) { result = false; } else { status = ftdi.Purge(FT_PURGE.FT_PURGE_TX | FT_PURGE.FT_PURGE_RX); IsConnected = true; result = true; } return(result); }
private FTDI.FT_STATUS writeCmd(string command) { uint bytesWritten = 0; int bytesToWrite; FTDI.FT_STATUS ftStatus; Encoding encoding = Encoding.ASCII; byte[] cmd = encoding.GetBytes(command); bytesToWrite = cmd.Length; _flowmeter.Purge(FTDI.FT_PURGE.FT_PURGE_RX | FTDI.FT_PURGE.FT_PURGE_TX); ftStatus = _flowmeter.ResetDevice(); ftStatus = _flowmeter.Write(cmd, bytesToWrite, ref bytesWritten); System.Threading.Thread.Sleep(delayMsec); return(ftStatus); }
private void writeCoil(byte slaveId, ushort coilNumber, bool on) { // opens a coil if on is true or // closes a coil if on is false byte[] request = new byte[8]; byte[] response = new byte[8]; UInt16 CRC; uint bytesWritten = 0; request[0] = slaveId; // slave ID request[1] = 0x05; // write coil command request[2] = (byte)(coilNumber >> 8); // Hi byte of coil address request[3] = (byte)(coilNumber); // lo byte of coil address if (on) { request[4] = 0xFF; } else { request[4] = 0; } request[5] = 0; CRC = ModRTU_CRC(request, 6); request[6] = (byte)(CRC >> 8); request[7] = (byte)(CRC); _modbusMaster.Purge(FTDI.FT_PURGE.FT_PURGE_RX | FTDI.FT_PURGE.FT_PURGE_TX); System.Threading.Thread.Sleep(delayMsec); ftStatus = _modbusMaster.Write(request, request.Length, ref bytesWritten); if (ftStatus != FTDI.FT_STATUS.FT_OK) { if (on) { throw new System.Exception("Could not open coil number " + coilNumber); } else { throw new System.Exception("Could not close coil number" + coilNumber); } } else { System.Threading.Thread.Sleep(delayMsec); } }
public void purge(uint mask) { FTDI.FT_STATUS ftStatus = ftdi.Purge(mask); if (ftStatus != FTDI.FT_STATUS.FT_OK) { String errMsg = "fail to Write (error " + ftStatus.ToString() + ")"; throw new FtdiException(errMsg); } }
private void InitializeDMX() { FTDI.FT_STATUS status; status = _ftdi.ResetDevice(); if (status != FTDI.FT_STATUS.FT_OK) { throw new Exception("Unable to reset device."); } status = _ftdi.SetBaudRate(9600); if (status != FTDI.FT_STATUS.FT_OK) { throw new Exception("Unable to set baud rate on device."); } status = _ftdi.SetDataCharacteristics(FTDI.FT_DATA_BITS.FT_BITS_8, FTDI.FT_STOP_BITS.FT_STOP_BITS_2, FTDI.FT_PARITY.FT_PARITY_NONE); if (status != FTDI.FT_STATUS.FT_OK) { throw new Exception("Unable to set data characteristics on device."); } status = _ftdi.SetFlowControl(FTDI.FT_FLOW_CONTROL.FT_FLOW_NONE, 0, 0); if (status != FTDI.FT_STATUS.FT_OK) { throw new Exception("Unable to set flow control on device."); } status = _ftdi.Purge(FTDI.FT_PURGE.FT_PURGE_TX); if (status != FTDI.FT_STATUS.FT_OK) { throw new Exception("Unable to purge transmit on device."); } status = _ftdi.Purge(FTDI.FT_PURGE.FT_PURGE_RX); if (status != FTDI.FT_STATUS.FT_OK) { throw new Exception("Unable to purge receive on device."); } }
public void reset() { resetDevice(CBUS.CBUS2); FtdiDevice.Purge(FTDI.FT_PURGE.FT_PURGE_RX | FTDI.FT_PURGE.FT_PURGE_TX); serialDataMutex.WaitOne(); bufferIn.Clear(); serialDataMutex.ReleaseMutex(); valuesMutex.WaitOne(); incomingMessages.Clear(); valuesMutex.ReleaseMutex(); }
private void sync() { int x; esp.Purge(FTDI.FT_PURGE.FT_PURGE_RX); esp.Purge(FTDI.FT_PURGE.FT_PURGE_TX); cmddata[0] = 0x07; cmddata[1] = 0x07; cmddata[2] = 0x12; cmddata[3] = 0x20; for (x = 4; x < 36; x++) { cmddata[x] = 0x55; } for (x = 0; x < 7; x++) { command(ESP_SYNC, cmddata, 36, 0); } }
private void readPS_Click(object sender, EventArgs e) { if (myFtdiDevice.IsOpen) { UInt32 readedBytes = 0; uint len = 1; byte[] buf = new byte[len]; ftStatus = myFtdiDevice.Purge(FTDI.FT_PURGE.FT_PURGE_RX); Log("Clearing input buffer with status: " + ftStatus.ToString()); ftStatus = myFtdiDevice.Read(buf, len, ref readedBytes); Log("Read " + readedBytes.ToString() + " with status " + ftStatus.ToString()); bufPS = buf[0]; } else { Log("Closed!"); } }
//------------------------------------------------------------------------------------------------- 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); }
/// <summary> Connects and initializes the device. </summary> /// <param name="serialNo"> The serial no of the device. </param> /// <returns> true if it succeeds, false if it fails. </returns> public bool Connect(string serialNo) { // disconnect existing device if any if (_device != null) { _device.Close(); _device = null; } // check serial number is a real value if (string.IsNullOrEmpty(serialNo)) { return(false); } // get the device information DeviceType = _deviceInfo[serialNo].DeviceType(); // connect new device _device = new FTDI(serialNo) { DeviceInfo = _deviceInfo[serialNo] }; if (!IsConnected) { return(false); } // initialize device communications bool success = _device.SetBaudRate(115200); success &= _device.SetDataCharacteristics(FTDI.DataBits.EightBits, FTDI.StopBits.FT_STOP_BITS_1, FTDI.Parity.None); success &= _device.SetFlowControl(FTDI.FlowControl.RtsCts, 0x11, 0x13); success &= _device.ResetDevice(); success &= _device.Purge(FTDI.PurgeFlags.PurgeRx | FTDI.PurgeFlags.PurgeTx); success &= _device.ResetDevice(); success &= _device.SetTimeOuts(300, 300); //extend timeout while board finishes reset return(success); }
private void sync() { int x; #if USE_FTD_DRIVER esp.Purge(FTDI.FT_PURGE.FT_PURGE_RX); esp.Purge(FTDI.FT_PURGE.FT_PURGE_TX); #else esp_programmer.DiscardBuffers(); #endif cmddata[0] = 0x07; cmddata[1] = 0x07; cmddata[2] = 0x12; cmddata[3] = 0x20; for (x = 4; x < 36; x++) { cmddata[x] = 0x55; } for (x = 0; x < 7; x++) { command(ESP_SYNC, cmddata, 36, 0); } }
public void open() { FTDI.FT_STATUS st; /* * uint devcount = 0; * ftdi.GetNumberOfDevices(ref devcount); * if (devcount == 0) * { * throw new SystemException("Device not found"); * } */ st = ftdi.OpenByIndex(index); if (st != FTDI.FT_STATUS.FT_OK) { throw new SystemException(string.Format("Failed to open device {0}. ({1})", index, st.ToString())); } ftdi.ResetDevice(); ftdi.Purge(FTDI.FT_PURGE.FT_PURGE_RX | FTDI.FT_PURGE.FT_PURGE_TX); ftdi.SetTimeouts(ReadTimeoutMilliseconds, WriteTimeoutMilliseconds); ftdi.SetLatency(LatencyMilliseconds); }
public bool read() { uint bytesWritten; bool success = false; if (isOpen()) { _pressureDevice.Purge(FTDI.FT_PURGE.FT_PURGE_RX | FTDI.FT_PURGE.FT_PURGE_TX); _pressureDevice.ResetDevice(); bytesWritten = requestReading(); System.Threading.Thread.Sleep(delayMsec); ftStatus = _pressureDevice.GetRxBytesAvailable(ref _rxBytes); if (_rxBytes > 0) { try { _currentPressure = new byte[_rxBytes]; ftStatus = _pressureDevice.Read(_currentPressure, _rxBytes, ref _rxBytesRead); if (ftStatus == FTDI.FT_STATUS.FT_OK) { success = true; } else { success = false; } } catch { return(false); // Console.WriteLine(e.Message); } } } return(success); }
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"); }
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"); }
/// <summary> /// Opens a connection to the ledstrip controller with the specified controller number. /// </summary> /// <param name="ControllerNumber">The controller number.</param> public void Open(int ControllerNumber) { lock (FT245RLocker) { Close(); bool OK = false; string Desc = ""; this.ControllerNumber = ControllerNumber; FT245R = new FTDI(); FTDI.FT_STATUS FTStatus; //Get number of devices uint DeviceCnt = 0; FTStatus = FT245R.GetNumberOfDevices(ref DeviceCnt); if (FTStatus == FTDI.FT_STATUS.FT_OK && DeviceCnt > 0) { FTDI.FT_DEVICE_INFO_NODE[] Devices = new FTDI.FT_DEVICE_INFO_NODE[DeviceCnt]; //for (uint i = 0; i < DeviceCnt; i++) //{ // FTStatus = FT245R.OpenByIndex(i); // // Log.Write("Open {0}: Result: {1}".Build(i, FTStatus.ToString())); // if (FT245R.IsOpen) // { // string D = ""; // FT245R.GetDescription(out D); // Log.Write("Desc: {0}".Build(D)); // try // { // FTStatus = FT245R.Close(); // Log.Write("Close {i}: Result: {1}".Build(i, FTStatus.ToString())); // } // catch { } // } //} //Log.Write("All listed"); FTStatus = FT245R.GetDeviceList(Devices); if (FTStatus == FTDI.FT_STATUS.FT_OK) { foreach (FTDI.FT_DEVICE_INFO_NODE DI in Devices) { if (DI != null && DI.Type == FTDI.FT_DEVICE.FT_DEVICE_232R) { if (ControllerNameBase.Any(N => DI.Description == N.Trim() + " " + ControllerNumber)) { Desc = DI.Description; FT245R.CharReceived += new EventHandler <EventArgs>(FT245R_CharReceived); FTStatus = FT245R.OpenByLocation(DI.LocId); if (FTStatus == FTDI.FT_STATUS.FT_OK) { FTStatus = FT245R.Purge(FTDI.FT_PURGE.FT_PURGE_RX + FTDI.FT_PURGE.FT_PURGE_TX); if (FTStatus == FTDI.FT_STATUS.FT_OK) { OK = true; break; } else { Log.Exception("Purge failed for WS2811StripController {0}. Error: {1}".Build(ControllerNumber, FTStatus.ToString())); } } else { Log.Exception("Open failed for WS2811StripController {0}. Error: {1}".Build(ControllerNumber, FTStatus.ToString())); } } } } } else { Log.Exception("Could not fetch devicelist for WS2811StripControllers. Error: {0}".Build(FTStatus.ToString())); } } if (!OK) { if (!Desc.IsNullOrWhiteSpace()) { Log.Warning("{0} detected, but could not open connection.".Build(Desc)); } else { Log.Warning("Direct Strip Controller with number {0} not found.".Build(ControllerNumber)); } Close(); } else { Log.Write("{0} detected and connection opend.".Build(Desc)); } } }
public USBCntrl(string name, string serial) { this.Name = name; cts = new CancellationTokenSource(); tkn = cts.Token; rxTsk = Task.Run(async() => await ShowRxData(), tkn); txTsk = Task.Run(async() => await SendTxData(), tkn); 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); state = 0; } while (false); for (int ndx = 0; ndx < bufrPool.BoundedCapacity; ndx++) { bufrPool.Add(new USBMsg()); } logger.Info("Waiting for tasks to complete."); cts.CancelAfter(1000); Task.WhenAll(new[] { txTsk, rxTsk }); logger.Error("Done."); }
protected void WriteToChannel(FTDI channel, byte[] dataBuf, bool flush) { var writtenTotal = 0; byte[] sendbuf = dataBuf; while (writtenTotal < dataBuf.Length) { uint written = 0; FTDI.FT_STATUS status; while (true) { status = channel.Write(sendbuf, dataBuf.Length - writtenTotal, ref written); // TODO: reconnect and retry when fails // Debug.Assert(status == FTDI.FT_STATUS.FT_OK); if (status == FTDI.FT_STATUS.FT_IO_ERROR) { if (_sequentialIoErrorsTimeStart == default) { _sequentialIoErrorsTimeStart = DateTime.Now; continue; } else { if (DateTime.Now - _sequentialIoErrorsTimeStart >= _maxSequentialIoErrorsTime) { throw new Exception("Exceeded sequential IO errors time."); } else { continue; } } // current FTDI drivers wont let you do this anyway // status = _channel.Close(); // _channel = OpenChannel(_channelName, _baudrate); } else { Debug.Assert(status == FTDI.FT_STATUS.FT_OK); } _sequentialIoErrorsTimeStart = default; break; } writtenTotal += (int)written; sendbuf = new byte[dataBuf.Length]; Array.Copy(dataBuf, writtenTotal, sendbuf, 0, dataBuf.Length - writtenTotal); } if (flush) { channel.Purge(FTDI.FT_PURGE.FT_PURGE_TX); } }
// public methods /// <summary> /// Attempt to open RHA2000-EVAL board connected to USB port. /// </summary> /// <param name="firmwareID1">Board ID number (1 of 3)</param> /// <param name="firmwareID2">Board ID number (2 of 3)</param> /// <param name="firmwareID3">Board ID number (3 of 3)</param> public void Open(ref int firmwareID1, ref int firmwareID2, ref int firmwareID3) { // Open FTDI USB device. UInt32 ftdiDeviceCount = 0; FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OK; // Create new instance of the FTDI device class. myFtdiDeviceA = new FTDI(); // Determine the number of FTDI devices connected to the machine. ftStatus = myFtdiDeviceA.GetNumberOfDevices(ref ftdiDeviceCount); // Check status. if (!(ftStatus == FTDI.FT_STATUS.FT_OK)) { UsbException e = new UsbException("USB Setup Error: Failed to get number devices"); throw e; } // If no devices available, return. if (ftdiDeviceCount == 0) { UsbException e = new UsbException("No valid USB devices detected"); throw e; } // Allocate storage for device info list. FTDI.FT_DEVICE_INFO_NODE[] ftdiDeviceList = new FTDI.FT_DEVICE_INFO_NODE[ftdiDeviceCount]; // Populate our device list. ftStatus = myFtdiDeviceA.GetDeviceList(ftdiDeviceList); // There could be a status error here, but we're not checking for it... // The Intan Technologies RHA2000-EVAL board uses an FTDI FT2232H chip to provide a USB // interface to a PC. Detailed information on this chip may be found at: // // http://www.ftdichip.com/Products/ICs/FT2232H.htm // // The FT2232H supports two independent FIFO channels. The channel used by the RHA2000-EVAL // board is factory-configured with the name "Intan I/O board 1.0 A". (FTDI provides software // routines to open device by its name.) ftStatus = myFtdiDeviceA.OpenByDescription("Intan I/O Board 1.0 A"); if (ftStatus != FTDI.FT_STATUS.FT_OK) { UsbException e = new UsbException("Intan USB device A not found"); throw e; } // Set read timeout to 5 seconds, write timeout to infinite ftStatus = myFtdiDeviceA.SetTimeouts(5000, 0); // There could be status error here, but we're not checking for it... this.Stop(); // Purge receive buffer myFtdiDeviceA.Purge(FTDI.FT_PURGE.FT_PURGE_RX); // Check board ID and version number // // The RHA2000-EVAL board is controlled by sending one-byte ASCII command characters over // the USB interface. The 'I' character commands the board to return a 3-byte ID/version // number. UInt32 numBytesWritten = 0; Byte[] myChars = { 73 }; // 'I' = request board ID and version number ftStatus = myFtdiDeviceA.Write(myChars, 1, ref numBytesWritten); if (ftStatus != FTDI.FT_STATUS.FT_OK) { UsbException e = new UsbException("Could not write to Intan USB device"); throw e; } const UInt32 numBytesToRead = 3; // Wait until the desired number of bytes have been received. UInt32 numBytesAvailable = 0; while (numBytesAvailable < numBytesToRead) { ftStatus = myFtdiDeviceA.GetRxBytesAvailable(ref numBytesAvailable); if (ftStatus != FTDI.FT_STATUS.FT_OK) { UsbException e = new UsbException("Failed to get number of USB bytes available to read"); throw e; } } // Now that we have the amount of data we want available, read it. UInt32 numBytesRead = 0; ftStatus = myFtdiDeviceA.Read(readDataBufferA, numBytesToRead, ref numBytesRead); if (ftStatus != FTDI.FT_STATUS.FT_OK) { UsbException e = new UsbException("USB read error"); throw e; } firmwareID1 = Convert.ToInt32(readDataBufferA[0]); firmwareID2 = Convert.ToInt32(readDataBufferA[1]); firmwareID3 = Convert.ToInt32(readDataBufferA[2]); Debug.WriteLine("Board ID: " + readDataBufferA[0] + " " + (Convert.ToInt32(readDataBufferA[1])).ToString() + " " + (Convert.ToInt32(readDataBufferA[2])).ToString()); this.ZCheckOff(); this.SettleOff(); // Purge receive buffer. myFtdiDeviceA.Purge(FTDI.FT_PURGE.FT_PURGE_RX); dataJustStarted = true; }
protected override void ClearBuffer() { ftdi.Purge(FT_PURGE.FT_PURGE_RX); ftdi.Purge(FT_PURGE.FT_PURGE_TX); }
public void Init(int index) { _ftdi = new FTDI(); FTDI.FT_STATUS status = _ftdi.OpenByIndex((uint)index); if (status != FTDI.FT_STATUS.FT_OK) { throw new FTI2CException("Problem opening FTDI device"); } status = _ftdi.ResetDevice(); if (status != FTDI.FT_STATUS.FT_OK) { throw new FTI2CException("Problem resetting FTDI device"); } // Purge USB receive buffer first by reading out all old data from FT2232H receive buffer status = _ftdi.Purge(FTDI.FT_PURGE.FT_PURGE_RX | FTDI.FT_PURGE.FT_PURGE_TX); if (status != FTDI.FT_STATUS.FT_OK) { throw new FTI2CException("Problem purging FTDI device"); } //Set USB request transfer size status = _ftdi.InTransferSize(USB_TRANSFERE_SIZE); if (status != FTDI.FT_STATUS.FT_OK) { throw new FTI2CException("Problem setting USB transfer size"); } //Disable event and error characters status = _ftdi.SetCharacters(0, false, 0, false); if (status != FTDI.FT_STATUS.FT_OK) { throw new FTI2CException("Problem disabling event and error characters"); } //Sets the read and write timeouts in milliseconds for the FT2232H status = _ftdi.SetTimeouts(5000, 5000); if (status != FTDI.FT_STATUS.FT_OK) { throw new FTI2CException("Problem setting timeouts"); } //Set the latency timer status = _ftdi.SetLatency(16); if (status != FTDI.FT_STATUS.FT_OK) { throw new FTI2CException("Problem setting latency timer"); } //Reset controller status = _ftdi.SetBitMode(0x0, FTDI.FT_BIT_MODES.FT_BIT_MODE_RESET); if (status != FTDI.FT_STATUS.FT_OK) { throw new FTI2CException("Problem resetting controller"); } // Set IO to only drive on 0 List <byte> buffer = new List <byte>(); buffer.Add(SET_IO_TO_ONLY_DRIVE_ON_0); buffer.Add(0xFF); buffer.Add(0xFF); rawWrite(buffer.ToArray()); // Send Command // enable MPSEE mode status = _ftdi.SetBitMode(0x0, FTDI.FT_BIT_MODES.FT_BIT_MODE_MPSSE); if (status != FTDI.FT_STATUS.FT_OK) { throw new FTI2CException("Problem enabling MPSEE mode"); } /// Configure the MPSSE settings buffer = new List <byte>(); buffer.Add(DISABLE_CLOCK_DIVISOR); // Disables the clk divide by 5 to allow for a 60MHz master clock. buffer.Add(0x97); // Ensure adaptive clocking is off buffer.Add(0x8C); // Enables 3 phase data clocking. data VALID on both edges. rawWrite(buffer.ToArray()); // Send Command /* Low Byte (ADBUS) * ADBUS0 TCK/SK ---> SCL * ADBUS1 TDI/DO -+-> SDA * ADBUS2 TDO/DI -+ * ADBUS3 TMS/CS * ADBUSS GPIOL0 * ADBUS5 GPIOL1 * ADBUS6 GPIOl2 * ADBUS7 GPIOL3 */ //Command to set ADBUS state and direction //Set SDA high, SCL high //Set SDA, SCL as output with bit 1, other pins as input with bit 0 buffer.AddRange(formSetDataBits(BUS.ADBUS, 0x03, 0x03)); rawWrite(buffer.ToArray()); // Send Command // Set clock divisor buffer = new List <byte>(); buffer.Add(SET_TCK_SK_CLOCK_DIVISOR); //TCK/SK period = 12MHz*5 / ( (1 + (0xValueH << 8) | 0xValueL) ) * 2) //double frequency = (60E6) / ( (1+ ((0x00 << 8) | 0xCB)) * 2/3 ); UInt16 dwClockDivisor = 0x00CB; //(0x012B/3) =~ 100 KHz buffer.Add((byte)(dwClockDivisor & 0xFF)); // low byte buffer.Add((byte)((dwClockDivisor >> 8) & 0xFF)); // high byte rawWrite(buffer.ToArray()); // sent of commands // Turn off Loopback buffer = new List <byte>(); //buffer.Add(TURN_OFF_LOOPBACK);//Command to turn off loop back of TDI/TDO connection rawWrite(buffer.ToArray());// sent of commands }
public ThorController(ThorStageModel stageModel, string serialNumber) { stage = new ThorStage(stageModel); UInt32 deviceCount = 0; uint numBytesWritten = 0; this.serialNumber = serialNumber; deviceHandle = new FTDI(); // Determine the number of FTDI devices connected to the machine ftStatus = deviceHandle.GetNumberOfDevices(ref deviceCount); // Populate device list FTDI.FT_DEVICE_INFO_NODE[] ftdiDeviceList = new FTDI.FT_DEVICE_INFO_NODE[deviceCount]; ftStatus = deviceHandle.GetDeviceList(ftdiDeviceList); ftStatus = deviceHandle.OpenBySerialNumber(serialNumber); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press throw new Exception("Failed to open FTDI device " + ftStatus.ToString()); } // Set baud rate to 115200. ftStatus = deviceHandle.SetBaudRate(115200); // 8 data bits, 1 stop bit, no parity ftStatus = deviceHandle.SetDataCharacteristics(FTDI.FT_DATA_BITS.FT_BITS_8, FTDI.FT_STOP_BITS.FT_STOP_BITS_1, FTDI.FT_PARITY.FT_PARITY_NONE); // Pre purge dwell 50ms. Thread.Sleep(50); // Purge the device. ftStatus = deviceHandle.Purge(FTDI.FT_PURGE.FT_PURGE_RX | FTDI.FT_PURGE.FT_PURGE_TX); // Post purge dwell 50ms. Thread.Sleep(50); // Reset device. ftStatus = deviceHandle.ResetDevice(); // Set flow control to RTS/CTS. ftStatus = deviceHandle.SetFlowControl(FTDI.FT_FLOW_CONTROL.FT_FLOW_RTS_CTS, 0, 0); // Set RTS. ftStatus = deviceHandle.SetRTS(true); // Disable then enable channel byte[] change_enstate = { 0x10, 0x02, 0x01, 0x02, 0x50, 0x1 }; ftStatus = deviceHandle.Write(change_enstate, 6, ref numBytesWritten); change_enstate[3] = 0x01; ftStatus = deviceHandle.Write(change_enstate, 6, ref numBytesWritten); // Move home byte[] movehome = { 0x43, 0x04, 0x01, 0x00, 0x50, 0x01 }; /*ftStatus = deviceHandle.Write(movehome, 6, ref numBytesWritten); * Thread.Sleep(3000); * do * { * statusBits = GetStatus(); * //Console.WriteLine("{0:X}", statusbits); * } while ((statusBits & 0x400) != 0x400 || statusBits == 0);*/ }
public void ClearBuffer() { ftStatus = myFtdiDevice.Purge(0); ftStatus = myFtdiDevice.Purge(1); }
public virtual bool PurgeWriteBuffer() { var status = ftdi.Purge(FTD2XX_NET.FTDI.FT_PURGE.FT_PURGE_TX); return(status == FTDI.FT_STATUS.FT_OK); }
/// <summary> /// Очистить Tx и Rx буффер устройства. /// </summary> public void Purge() { _device.Purge(FTDI.FT_PURGE.FT_PURGE_RX | FTDI.FT_PURGE.FT_PURGE_TX); }