private byte[] ReceiveResponse() { byte[] result = null; StxEtxParser parser = new StxEtxParser(); parser.PacketComplete += new StxEtxParser.PacketCompleteHandler((par, data) => { result = data; }); while (result == null) { if (_WaitHandle.WaitOne(1000) == false) { throw new Exception("Error reading data (ReceiveResponse)"); } uint rxBytes = 0; _Ftdi.GetRxBytesAvailable(ref rxBytes); if (rxBytes > 0) { byte[] readBuffer = new byte[rxBytes]; uint readBytes = 0; FT_STATUS status = _Ftdi.Read(readBuffer, (uint)readBuffer.Length, ref readBytes); if (status != FT_STATUS.FT_OK) { throw new Exception("Error reading data (ReceiveResponse)"); } parser.Parse(readBuffer, 0, (int)readBytes); } } return(result); }
public bool EmptyReceiveBuffer() // Desc: Empty receive buffer { uint num_bytes_available = 0; uint num_bytes_read = 0; byte[] data_read; // Get number of available bytes to read ftStatus = myFtdiDevice.GetRxBytesAvailable(ref num_bytes_available); if (num_bytes_available == 0) { return(true); } data_read = new byte[num_bytes_available]; // Read available bytes ftStatus = myFtdiDevice.Read(data_read, num_bytes_available, ref num_bytes_read); if (ftStatus != FTDI.FT_STATUS.FT_OK) { return(false); } else { return(true); } }
public static uint CheckQueue() { uint QueueSize = 0; USBPort.GetRxBytesAvailable(ref QueueSize); return(QueueSize); }
void FT245R_CharReceived(object sender, EventArgs e) { uint CharsToRead = 0; FT245R.GetRxBytesAvailable(ref CharsToRead); if (CharsToRead > 0) { uint BytesRead = 0; byte[] Response = new Byte[CharsToRead]; FT245R.Read(Response, CharsToRead, ref BytesRead); bool OK = true; for (int i = 0; i < BytesRead; i++) { if (Response[i] == 0x4e) { OK = false; break; } } if (!OK) { lock (FT245RLocker) { ErrorCorrectionCnt++; if (ErrorCorrectionCnt <= 30) { Log.Warning("Received unexpected answer from Direct Strip Controller with number {0}. Will try to fix problem.".Build(ControllerNumber)); if (ErrorCorrectionCnt == 30) { Log.Write("No further warnings will be recorded for unexpected answers from this unit."); } } FT245R.CharReceived -= new EventHandler <EventArgs>(FT245R_CharReceived); uint Dummy = 0; for (int i = 0; i < 2000; i++) { FT245R.Write(new byte[10], 10, ref Dummy); Thread.Sleep(10); CharsToRead = 0; FT245R.GetRxBytesAvailable(ref CharsToRead); if (CharsToRead > 0) { Thread.Sleep(10); CharsToRead = 0; FT245R.GetRxBytesAvailable(ref CharsToRead); Response = new Byte[CharsToRead]; BytesRead = 0; FT245R.Read(Response, CharsToRead, ref BytesRead); break; } } FT245R.CharReceived += new EventHandler <EventArgs>(FT245R_CharReceived); } } } }
/// <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); }
private void RxCheckTimer_Tick(object sender, EventArgs e) { RxCheckTimer.Enabled = false; uint RxCount = 0; var rx_buf = new byte[1000]; string rx_str_buf = ""; uint data_read = 0; ftStatus = myFtdiDevice.GetRxBytesAvailable(ref RxCount); if (ftStatus != FTDI.FT_STATUS.FT_OK) { textBox1.Text = "<<ERROR: " + ftStatus.ToString() + "\r\n"; } else if (RxCount > 0) { ftStatus = myFtdiDevice.Read(rx_buf, RxCount, ref data_read); //rx_str_buf = System.Text.Encoding.Default.GetString(rx_buf); rx_str_buf = BitConverter.ToString(rx_buf); textBox1.Text += "Received " + RxCount + " bytes <<" + rx_str_buf + ">>\r\n\r\n"; } else { //textBox1.Text += "<> " + RxCount + " <>" + "\r\n"; } RxCheckTimer.Enabled = true; }
private String readFTDI() { String response = ""; FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OK; if (isOpen()) { ftStatus = _flowmeter.GetRxBytesAvailable(ref _rxBytes); if (_rxBytes > 0) { try { _bytesRead = new byte[_rxBytes]; _flowmeter.Read(_bytesRead, _rxBytes, ref _rxBytesRead); response = System.Text.Encoding.ASCII.GetString(_bytesRead); } catch { return(response); // Console.WriteLine(e.Message); } } } return(response); }
private void USBReceivingRoutine() { uint numBytesAvailable = 0; uint numBytesRead = 0; while (true) { Thread.Sleep(0); if (FtdiDevice.IsOpen == true) { COMPortMutex.WaitOne(); ftStatus = FtdiDevice.GetRxBytesAvailable(ref numBytesAvailable); if (numBytesAvailable > MinimumBytesToRead && ftStatus == FTDI.FT_STATUS.FT_OK) { byte[] readData = new byte[numBytesAvailable]; ftStatus = FtdiDevice.Read(readData, numBytesAvailable, ref numBytesRead); if (ftStatus == FTDI.FT_STATUS.FT_OK) { serialDataMutex.WaitOne(); bufferIn.AddRange(readData); waitForNewSerialData.Set(); serialDataMutex.ReleaseMutex(); } } COMPortMutex.ReleaseMutex(); } } }
private void Reciever_DoWork(object sender, DoWorkEventArgs e) { UInt32 numBytesAvailable = 0; do { ftStatus = myFtdiDevice.GetRxBytesAvailable(ref numBytesAvailable); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press MessageBox.Show("Failed to get number of bytes available to read (error " + ftStatus.ToString() + ")"); } } 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 MessageBox.Show("Failed to read data (error " + ftStatus.ToString() + ")"); } textBox2.AppendText(readData); }
/// <summary> /// /// </summary> /// <param name="count"></param> /// <param name="max_read_count"></param> /// <returns>Rx bytes available</returns> uint waifForRxDataCount(uint count, uint max_read_count = 100) { FTDI.FT_STATUS status; uint read_count = 0; uint inCount = 0; while (true) { status = _ftdi.GetRxBytesAvailable(ref inCount); if (status != FTDI.FT_STATUS.FT_OK) { throw new FTI2CException("Unable to get Rx bytes available"); } if (inCount >= count) { break; } if (read_count++ > max_read_count) { throw new FTI2CException("Timeout reading Rx bytes available"); } Thread.Sleep(1); } return(inCount); }
public int[] readfromDevice() { UInt32 numBytesAvailable = 0; //ftStatus = myFtdiDevice.Purge(FTDI.FT_PURGE.FT_PURGE_RX); ftStatus = myFtdiDevice.GetRxBytesAvailable(ref numBytesAvailable); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press MessageBox.Show("Failed to get number of bytes available to read (error " + ftStatus.ToString() + ")"); //return; } //lines = Int32.Parse(RealTimeSignal_number.EditValue.ToString()); UInt32 numBytesRead = 0; byte[] buff = new byte[numBytesAvailable]; ftStatus = myFtdiDevice.Read(buff, numBytesAvailable, ref numBytesRead); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press MessageBox.Show("Failed to read data (error " + ftStatus.ToString() + ")"); // return; } return(processIntInput(buff)); }
void readThread() { try { while (serialPort != null) { try { int c = serialPort.ReadByte(); if (c >= 0) { recvProceed((byte)c); } } catch (TimeoutException) { } } while (d2xxPort != null) { try { UInt32 numBytesAvailable = 0; FTDI.FT_STATUS ftStatus; do { ftStatus = d2xxPort.GetRxBytesAvailable(ref numBytesAvailable); if (ftStatus != FTDI.FT_STATUS.FT_OK) { throw new IOException("Failed to get number of bytes available to read (error " + ftStatus.ToString() + ")"); } Thread.Sleep(10); } while (numBytesAvailable == 0); var data = new byte[numBytesAvailable]; UInt32 numBytesRead = 0; ftStatus = d2xxPort.Read(data, numBytesAvailable, ref numBytesRead); if (ftStatus != FTDI.FT_STATUS.FT_OK) { throw new IOException("Failed to read data (error " + ftStatus.ToString() + ")"); } foreach (var b in data) { recvProceed(b); } } catch (TimeoutException) { } } } catch (ThreadAbortException) { } catch (IOException) { Close(); //Console.WriteLine("Port closed: " + ex.Message); } finally { readingThread = null; } }
private void CommThread() { do { Thread.Sleep(10); if (active == false) { continue; } if (!Connected && !quit) { AttemptConnect(); } else { uint bytesRead = 0; lock (ftdi) { // read any available data uint bytesAvail = 0; FTDI.FT_STATUS stat = ftdi.GetRxBytesAvailable(ref bytesAvail); // How much data is available from the serial port? if (stat == FTDI.FT_STATUS.FT_IO_ERROR) { // If we got an error, the port has likely been closed / unplugged - go back to waiting ftdi.Close(); connected = false; if (ConnectionEnded != null) { ConnectionEnded(); } continue; } if (bytesAvail > 0 && !quit) { uint toRead = Math.Min(bytesAvail, (uint)rxBuffer.Length); if (toRead > 0) { ftdi.Read(rxBuffer, toRead, ref bytesRead); } } } for (int i = 0; i < bytesRead; i++) { ProcessByte(rxBuffer[i]); if (quit) { break; } } } } while(!quit); Disconnect(); }
private void SendDataIntoFifo() { FTDI.FT_STATUS status; uint txQueue = 0; // check buffer status = ftHandle.GetTxBytesWaiting(ref txQueue); if (txQueue == 0) { // write data uint written = 0; ftHandle.Write(data, data.Length, ref written); if (written == 0) { MessageBox.Show("No data have been written"); return; } } Thread.Sleep(20); status = ftHandle.GetRxBytesAvailable(ref rxQueue); if (rxQueue > 0 && status == FTDI.FT_STATUS.FT_OK) { // read data uint read = 0; ftHandle.Read(recData, (uint)rxQueue, ref read); if (read == 0) { MessageBox.Show("No data have been read from FIFO"); return; } } //status = ftHandle.GetTxBytesWaiting(ref txQueue); //if (txQueue == 0) //{ // // write data // uint written = 0; // ftHandle.Write(data, data.Length, ref written); // if (written == 0) // { // MessageBox.Show("No data have been written"); // return; // } //} }
private void timer1_Tick(object sender, EventArgs e) { esp.GetRxBytesAvailable(ref RxQueue); if (RxQueue > 0) { Array.Clear(data, 0, 1024); esp.Read(data, RxQueue, ref numBytesRead); var str = System.Text.Encoding.Default.GetString(data); Console.WriteLine(numBytesRead); log.AppendText(str); } }
/// <summary> /// Search for the '001111xx' byte that designates the end of a 16-channel data packet. /// </summary> /// <returns>Number of bytes we skipped trying to get back in sync.</returns> public int ResyncA() { bool inSync = false; FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OK; byte[] resyncBuffer = new byte[1]; Debug.WriteLine("Resync #" + resyncCount.ToString()); resyncCount++; int resyncBytes = 0; while (inSync == false) { // Wait until the desired number of bytes have been received. UInt32 numBytesAvailable = 0; while (numBytesAvailable < 1) { ftStatus = ftdiDeviceA.GetRxBytesAvailable(ref numBytesAvailable); if (ftStatus != FTDI.FT_STATUS.FT_OK) { IntanUsbException e = new IntanUsbException("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 = ftdiDeviceA.Read(resyncBuffer, 1, ref numBytesRead); if (ftStatus != FTDI.FT_STATUS.FT_OK) { IntanUsbException e = new IntanUsbException("USB read error"); throw e; } resyncDataBufferA[resyncBytes] = resyncBuffer[0]; resyncBytes++; // Are we back in sync? if ((resyncBuffer[0] & 0xfc) == 0x3c) { inSync = true; } } return(resyncBytes); }
//------------------------------------------------ read() public void read(byte[] dat, int len) { uint rlen = 0; sw.Start(); do { ftdi.GetRxBytesAvailable(ref rlen); if (sw.ElapsedMilliseconds > 1000) { throw (new SASEBO_G_Exception("Read timeout")); } } while (rlen < len); sw.Reset(); ftdi.Read(dat, (uint)len, ref rlen); }
private byte[] ReadPort() { var buffer = new byte[MaxReadPacketSize + 8]; if (serialPort != null) { var l = serialPort.Read(buffer, 0, buffer.Length); var result = new byte[l]; Array.Copy(buffer, result, l); return(result); } else if (d2xxPort != null) { uint numBytesAvailable = 0; FTDI.FT_STATUS ftStatus; int t = 0; do { ftStatus = d2xxPort.GetRxBytesAvailable(ref numBytesAvailable); if (ftStatus != FTDI.FT_STATUS.FT_OK) { throw new IOException("Failed to get number of bytes available to read (error " + ftStatus.ToString() + ")"); } if (numBytesAvailable > 0) { break; } Thread.Sleep(10); t += 10; if (t >= Timeout) { throw new TimeoutException("Read timeout"); } } while (numBytesAvailable == 0); uint numBytesRead = 0; ftStatus = d2xxPort.Read(buffer, Math.Min(numBytesAvailable, (uint)MaxReadPacketSize + 8), ref numBytesRead); if (ftStatus != FTDI.FT_STATUS.FT_OK) { throw new IOException("Failed to read data (error " + ftStatus.ToString() + ")"); } var result = new byte[numBytesRead]; Array.Copy(buffer, result, numBytesRead); return(result); } return(null); }
static FTDI.FT_STATUS Sync_MPSSE(ref FTDI ftdi, byte[] TransferBuffer) { /* * See FTDI AN_114 Page 10-11 Synchronize the MPSSE interface by sending bad command &xAA* * For Check MPSSE is sucsessfully running send a bad obcode (0xaa) * The request must be 0xfa and the bad obcode * In the AN make it at twice. * Im too lazy for this! */ uint NumBytesToTransfer, TxRxQ = 0; uint NumBytesTransfered = 0; FTDI.FT_STATUS s; NumBytesToTransfer = 0; TransferBuffer[NumBytesToTransfer++] = 0xaa; ftdi.Write(TransferBuffer, NumBytesToTransfer, ref NumBytesTransfered); do { Thread.Sleep(5); ftdi.GetTxBytesWaiting(ref TxRxQ); } while (TxRxQ != 0); Thread.Sleep(20); s = ftdi.GetRxBytesAvailable(ref NumBytesToTransfer); if (s == FTDI.FT_STATUS.FT_OK) { ftdi.Read(TransferBuffer, NumBytesToTransfer, ref NumBytesTransfered); //if we get 0xfa and 0xaa MPSSE should be working if (TransferBuffer[0] != 0xfa || TransferBuffer[1] != 0xaa) { return(FTDI.FT_STATUS.FT_OTHER_ERROR); } } else { return(FTDI.FT_STATUS.FT_OTHER_ERROR); } return(FTDI.FT_STATUS.FT_OK); }
//------------------------------------------------------------------------------------------------- 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); }
private void lin_raw_receive_Func(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; byte[] readbuffer = new byte[128]; byte[] pipebuffer = new byte[1024]; int pipepointer = 0; uint availableBytes = 0; uint readedBytes = 0; do { if (worker.CancellationPending) { e.Cancel = true; break; } if (ftdi.IsOpen) { availableBytes = 0; FTDI.FT_STATUS ftStatus = ftdi.GetRxBytesAvailable(ref availableBytes); if (ftStatus == FTDI.FT_STATUS.FT_OK) { if (availableBytes > 0) { ftStatus = ftdi.Read(readbuffer, availableBytes, ref readedBytes); if (ftStatus == FTDI.FT_STATUS.FT_OK) { //Utilites.CopyToByteArray(pipebuffer, readbuffer, pipepointer, 0, (int)readedBytes); //pipepointer += (int)readedBytes; } } } } else { break; } Thread.Sleep(1); }while (true); }
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); }
protected override void Work(CancellationToken cancellationToken) { myFtdiDevice.ResetDevice(); while (buffer != null) { numBytesRead = 0; numBytesAvailable = 0; if (toStart) { /* Wait for all the data */ while (numBytesAvailable < 12) { myFtdiDevice.GetRxBytesAvailable(ref numBytesAvailable); } /* Read the data */ myFtdiDevice.Read(buffer, numBytesAvailable, ref numBytesRead); if ((int)buffer[0] == 0) { /* Integrate read data */ for (int i = 0; i < 4; i++) { value[i] = ((int)buffer[2 + i] - 128); // sumValues[i] += value[i]; } tickNumber++; } else { myFtdiDevice.ResetDevice(); } } } }
public override Status CommXfer(out byte[] msg_rx, byte[] msg_tx, int rx_size) { Status status = new Status(); ftStatus = FTDI.FT_STATUS.FT_OK; msg_rx = new byte[0]; if (ftdi == null) { return(Utils.StatusCreate(333)); } try { if (msg_tx.Length > 0) { uint numBytesWritten = 0; ftStatus = ftdi.Write(msg_tx, msg_tx.Length, ref numBytesWritten); if (ftStatus != FTDI.FT_STATUS.FT_OK) { return(Utils.StatusCreate(390, ftStatus.ToString())); } if (numBytesWritten != msg_tx.Length) { return(Utils.StatusCreate(391)); } status = Utils.StatusCreate(0); } if (rx_size > 0) { byte[] buffer = Enumerable.Repeat((byte)0xFF, rx_size).ToArray(); uint numBytesAvailable = 0; uint numBytesRead = 0; int timeout = Const.TIMEOUT_READ; bool timeout_flip = false; Stopwatch sw = new Stopwatch(); sw.Start(); do { ftStatus = ftdi.GetRxBytesAvailable(ref numBytesAvailable); if (ftStatus != FTDI.FT_STATUS.FT_OK) { return(Utils.StatusCreate(392, ftStatus.ToString())); } else if (numBytesAvailable >= rx_size || (timeout_flip && numBytesAvailable > 0)) { if (numBytesAvailable > rx_size) { numBytesAvailable = (uint)rx_size; } ftStatus = ftdi.Read(buffer, numBytesAvailable, ref numBytesRead); if (ftStatus != FTDI.FT_STATUS.FT_OK) { return(Utils.StatusCreate(393, ftStatus.ToString())); } if (numBytesRead != numBytesAvailable) { return(Utils.StatusCreate(394)); } if (numBytesAvailable > rx_size) { ftdi.Purge(FTDI.FT_PURGE.FT_PURGE_RX | FTDI.FT_PURGE.FT_PURGE_TX); } msg_rx = buffer.Take(rx_size).ToArray(); status = Utils.StatusCreate(0); break; } if (BSL430NET.Interrupted) { throw new Bsl430NetException(666); } if (timeout_flip) { return(Utils.StatusCreate(395)); } if (timeout <= 0) { timeout_flip = true; } else { timeout -= (int)sw.ElapsedMilliseconds; } Task.Delay(DELAY_READ).Wait(); } while (numBytesAvailable < rx_size); } return(status); } catch (Bsl430NetException ex) { throw ex; } catch (Exception ex) { return(Utils.StatusCreate(446, ex.Message)); } }
/* * MAIN PROGRAM FUNCTIONALITY */ private void TmrPoll_Tick(object sender, EventArgs e) { // Buffer for pin status // Different array sizes have different effects; I don't understand why, but the device // will always return as many bytes as the size of your array. 256 seems to be a sweet spot. byte[] readData = new byte[256]; // Number of bytes device actually read out when queried; always the same as the array size uint bytesRead = 0; // Check whether there are bytes available // In GPIO mode, this should always return an infinite number, and indeed it seems to. The reason // this is here, more than anything, is to allow an exception if the device isn't happy. ft_status = ftdi.GetRxBytesAvailable(ref bytesRead); if (ft_status != FTDI.FT_STATUS.FT_OK) { // If anything went wrong, stop the loop but don't exit so the user can read the logs. string errorMessage = "Failed to get number of bytes available to read (error " + ft_status.ToString() + ")"; DbgW(errorMessage); DbgW("Processing halted. Restart program to continue."); MessageBox.Show(this, "An error (" + ft_status.ToString() + ") was returned when trying to read the FT232.\r\nProcessing halted. Restart the program to continue.", "Error: Device not present", MessageBoxButtons.OK, MessageBoxIcon.Error); tmrPoll.Enabled = false; return; } // Read out the buffer // readData now contains a series of bytes representing the pin state ftdi.Read(readData, bytesRead, ref bytesRead); // Uncomment this block to see the raw bytes in the debug console // It's probably -not- a good idea to modify this to use the dbgW function, since // that would hit disk IO every 16ms. /*Console.Write("Data: "); * String aa = ""; * for (int x=0;x<256;x++) * { * aa += readData[x].ToString(); * } * Console.WriteLine(aa);*/ // Check status of each pin for (int i = 0; i < btnBits.Length; i++) { // Check for bit for this button, and make sure the button isn't already pressed if (((((int)readData[0]) & btnBits[i]) != 0) && ButtonState[i] == false) { // Button was not pressed and now is // Set flag in button status table ButtonState[i].state = true; // Log event DbgW("Button " + i.ToString() + " pressed"); int delayValue = ButtonState[i].delay; // Check whether the button's action has a delay if (delayValue > 0) { // Yes; turn diagnostic light orange and set the delay value for the button buttonLights[i].BackColor = Color.Orange; ButtonState[i].remaining = delayValue; DbgW("Delay of " + (delayValue * 10).ToString() + " milliseconds"); } else { // No; Turn diagnostic light green and take action immediately buttonLights[i].BackColor = Color.LimeGreen; ButtonEvent(i); } } else if (((((int)readData[0]) & btnBits[i]) == 0) && ButtonState[i] == true) { // Button was pressed and has been released // Clear flag in button status table ButtonState[i].state = false; // Clear diagnostic light buttonLights[i].BackColor = Color.Maroon; // Log event DbgW("Button " + i.ToString() + " released"); } // No action is taken if the button state hasn't changed, so there's no else } }
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."); }
/// <summary> /// Check to see if there is at least 30 msec worth of data in the USB read buffer. /// </summary> /// <param name="plotQueue">Queue used for plotting data to screen.</param> /// <param name="saveQueue">Queue used for saving data to disk.</param> public void CheckForUsbData(Queue <USBData> plotQueue, Queue <USBData> saveQueue) { // Note: Users must call CheckForUsbData periodically during time-consuming operations (like updating graphics) // to make sure the USB read buffer doesn't overflow! FTDI.FT_STATUS ftStatus = FTDI.FT_STATUS.FT_OK; UInt32 numBytesAvailableA = 0; bool haveEnoughData = false; const UInt32 numBytesToRead = 36000; // 36000 / (3 bytes/sample x 16 channels x 25 kS/s) = 30 msec of data // It seems that the FTDI read buffer is slightly less than 64000 bytes // in size, so we must read from the buffer before it overflows. However, // if we read a small number of bytes at a time, data transfer is slow. // Empirically, waiting for 36000 bytes seems to work well. // Wait until at least 30 msec of amplifier data have been received. if (synthDataMode) { if (newSynthDataReady) { haveEnoughData = true; newSynthDataReady = false; } } else { ftStatus = myFtdiDeviceA.GetRxBytesAvailable(ref numBytesAvailableA); if (ftStatus != FTDI.FT_STATUS.FT_OK) { UsbException e = new UsbException("Failed to get number of USB bytes available to read"); throw e; } if (numBytesAvailableA >= numBytesToRead) { haveEnoughData = true; } } if (haveEnoughData) { // Support a 'synthetic neural data mode' so that users may run the software with no board attached and see simulated // spikes on each channel. (New for version 1.03.) if (synthDataMode) { int channel, i, j; Random myRand = new Random(unchecked ((int)DateTime.Now.Ticks)); for (channel = 0; channel < 16; channel++) { for (i = 0; i < 750; i++) { dataRaw[channel, i] = (float)synthSpikeOffset[channel] + 2.0F * gaussian(myRand); // create realistic offset and background of 2.0uV rms noise } i = 0; while (i < 750 - 50) { if (myRand.NextDouble() < 0.01) { for (j = 0; j < synthSpikeWidth1[channel]; j++) { dataRaw[channel, i + j] += (float)(synthSpikeAmp1[channel] * Math.Exp(-1 * (double)j / 12.5) * Math.Sin(6.28 * (double)j / synthSpikeWidth1[channel])); } i += 40 + 50; // advance by 2 msec (refractory period) } else if (myRand.NextDouble() < 0.02) { for (j = 0; j < synthSpikeWidth2[channel]; j++) { dataRaw[channel, i + j] += (float)(synthSpikeAmp2[channel] * Math.Exp(-1 * (double)j / 12.5) * Math.Sin(6.28 * (double)j / synthSpikeWidth2[channel])); } i += 40 + 50; // advance by 2 msec (refractory period) } else { i += 25; // advance by 1 msec } } } } else { // Now that we have the amount of data we want available, read it. UInt32 numBytesReadA = 0; ftStatus = myFtdiDeviceA.Read(readDataBufferA, numBytesToRead, ref numBytesReadA); if (ftStatus != FTDI.FT_STATUS.FT_OK) { UsbException e = new UsbException("USB read error"); throw e; } // The following section of code reads and parses a block of data from the RHA2000-EVAL board. // A complete sequence of single A/D samples from all 16 amplifiers uses 16 x 3 = 48 bytes in // the following three-byte format (MSB is on the left; LSB is on the right): // // Byte 1: 1 ADC6 ADC5 ADC4 ADC3 ADC2 ADC1 ADC0 // Byte 2: 1 ADC13 ADC12 ADC11 ADC10 ADC9 ADC8 ADC7 // Byte 3: 0 0 CH3 CH2 CH1 CH0 ADC15 ADC14 // // ADC0 through ADC 15 comprise the 16-bit A/D converter sample from a particular amplifier // channel. (ADC15 is the MDB; ADC0 is the LSB.) The A/D full-scale range is 2.5V. The "zero" // level of RHA2000 amplifiers is around 1.225V, although this can vary from one channel to another // due to built-in offset voltages. The use of a software high-pass filter is recommended to // remove these offsets (see the RHA2000 series datasheet for more information). With the RHA2000 // gain of 200 taken into account, each A/D step corresponds to an electrode-referred voltage of // (2.5V/200)/(2^16) = 0.19073 microvolts. // // CH0 through CH3 encode information that varies with the channel number. The following table // shows the values for these bits depending on the channel: // // Amplifier Channel CH3 CH2 CH1 CH0 // 0 0 0 0 0 // 1 0 0 0 AUX1 // 2 0 0 0 AUX2 // 3 0 0 0 AUX3 // 4 0 0 0 AUX4 // 5 0 0 0 AUX5 // 6 0 0 0 AUX6 // 7 X X X X // 8 X X X X // 9 X X X X // 10 X X X X // 11 X X X X // 12 X X X X // 13 X X X X // 14 X X X X // 15 1 1 1 1 // // AUX1 through AUX6 are bits corresponding to the Port J3 auxiliary TTL inputs shown in the // RHA2000-EVAL datasheet. Any bits listed as 'X' are not specified and should not be used. // Note that channels 0 and 15 are unambiguously marked (0000 and 1111, respectively). It is // recommended that interface software first watch for a byte that begins with '001111xx'. // This must correspond to byte 3 of channel 15. The next 48 bytes will comprise a complete // 16-channel data frame starting with channel 0 and proceeding through channel 15. // // Each amplifier channel is sampled at 25 kS/s, which gives a data rate of 25,000 x 16 x 3 = // 1.2 MByte/s. // // In our experience, the FTDI USB interface chip on the RHA2000-EVAL occasionally drops bytes // (though this seems to depend on the exact USB interface card used in the PC), requiring any // interface software to frequently look for a '001111xx' byte at the end of each 48-byte data // frame to ensure synchronization is maintained. When sync is lost, the software must search // for this byte again. // Are we out of sync due to a dropped byte over the USB link? If so, resync. if ((readDataBufferA[35999] & 0xfc) != 0x3c) // look for '001111xx' byte { // for (int j = 0; j < 36000; j++) // { // if ((readDataBufferA[j] & 0xfc) == 0x3c) // { // Debug.WriteLine("readDataBufferA[" + j + "] = 0x3C."); // break; // } // } int i = 0; int index = 0; int numExtraBytes = this.ResyncA(); Debug.WriteLine("Resync " + numExtraBytes + " bytes."); int indexError = 47 + 48; while ((readDataBufferA[indexError] & 0xfc) == 0x3c) { indexError += 48; } Debug.WriteLine("indexError = " + indexError); // Duplicate previous sample to 'patch' missing or erroneous data for (i = indexError - 47; i < indexError + 1; i++) { readDataBufferA[i] = readDataBufferA[i - 48]; } for (i = indexError - 47 + 48; i < 36000 - numExtraBytes; i++) { readDataBufferA[i] = readDataBufferA[i + numExtraBytes]; } for (i = 36000 - numExtraBytes; i < 36000; i++) { readDataBufferA[i] = resyncDataBufferA[index++]; } } // Parse data (see comments above for description of 3-byte data packet) int indexA = 0; byte byte1, byte2, byte3; for (int i = 0; i < 750; i++) { auxFrame[i] = 0; for (int channel = 0; channel < 16; channel++) { byte1 = readDataBufferA[indexA++]; byte2 = readDataBufferA[indexA++]; byte3 = readDataBufferA[indexA++]; if (channel == 1) { auxFrame[i] += (UInt16)(1 * (int)((byte3 & 0x04) >> 2)); } else if (channel == 2) { auxFrame[i] += (UInt16)(2 * (int)((byte3 & 0x04) >> 2)); } else if (channel == 3) { auxFrame[i] += (UInt16)(4 * (int)((byte3 & 0x04) >> 2)); } else if (channel == 4) { auxFrame[i] += (UInt16)(8 * (int)((byte3 & 0x04) >> 2)); } else if (channel == 5) { auxFrame[i] += (UInt16)(16 * (int)((byte3 & 0x04) >> 2)); } else if (channel == 6) { auxFrame[i] += (UInt16)(32 * (int)((byte3 & 0x04) >> 2)); } dataRaw[channel, i] = 0.1907F * (16384.0F * Convert.ToSingle(byte3 & 0x03) + 128.0F * Convert.ToSingle(byte2 & 0x7f) + Convert.ToSingle(byte1 & 0x7f)) - 6175.0F; // 6175 = 1.235 V offset divided by 200, expressed in microvolts } } } if (dataJustStarted) { for (int channel = 0; channel < 16; channel++) { dataState[channel] = dataRaw[channel, 0]; dataDelay1[channel] = dataRaw[channel, 0]; dataDelay2[channel] = dataRaw[channel, 0]; notchDelay1[channel] = dataRaw[channel, 0]; notchDelay2[channel] = dataRaw[channel, 0]; } dataJustStarted = false; } // Apply software first-order high-pass filter // (See RHA2000 series datasheet for desciption of this algorithm.) const double FSample = 25000.0; // ADC sample rate, in Hz float filtA = (float)(Math.Exp(-2.0 * Math.PI * fHPF / FSample)); // A float filtB = 1.0F - filtA; // B = 1 - A for (int channel = 0; channel < 16; channel++) { dataState[channel] = filtA * dataState[channel] + filtB * dataRaw[channel, 0]; if (enableHPF) { dataFrame[channel, 0] = dataRaw[channel, 0] - dataState[channel]; } else { dataFrame[channel, 0] = dataRaw[channel, 0]; } for (int i = 1; i < 750; i++) { dataState[channel] = filtA * dataState[channel] + filtB * dataRaw[channel, i]; if (enableHPF) { dataFrame[channel, i] = dataRaw[channel, i] - dataState[channel]; } else { dataFrame[channel, i] = dataRaw[channel, i]; } } } // Apply software notch filter // (See RHA2000 series datasheet for desciption of this algorithm.) const double NotchBW = 10.0; // notch filter bandwidth, in Hz // Note: Reducing the notch filter bandwidth will create a more frequency-selective filter, but this // can lead to a long settling time for the filter. Selecting a bandwdith of 10 Hz (e.g., filtering // out frequencies between 55 Hz and 65 Hz for the 60 Hz notch filter setting) implements a fast- // settling filter. float d = (float)Math.Exp(-1.0 * Math.PI * NotchBW / FSample); float b = (1.0F + d * d) * (float)Math.Cos(2.0 * Math.PI * fNotch / FSample); float a = 0.5F * (1.0F + d * d); float b0 = a; float b1 = a * (-2.0F) * (float)Math.Cos(2.0 * Math.PI * fNotch / FSample); float b2 = a; float a1 = -b; float a2 = d * d; for (int channel = 0; channel < 16; channel++) { dataNotch[channel, 0] = b2 * dataDelay2[channel] + b1 * dataDelay1[channel] + b0 * dataFrame[channel, 0] - a2 * notchDelay2[channel] - a1 * notchDelay1[channel]; dataNotch[channel, 1] = b2 * dataDelay1[channel] + b1 * dataFrame[channel, 0] + b0 * dataFrame[channel, 1] - a2 * notchDelay1[channel] - a1 * dataNotch[channel, 0]; for (int i = 2; i < 750; i++) { dataNotch[channel, i] = b2 * dataFrame[channel, i - 2] + b1 * dataFrame[channel, i - 1] + b0 * dataFrame[channel, i] - a2 * dataNotch[channel, i - 2] - a1 * dataNotch[channel, i - 1]; } } for (int channel = 0; channel < 16; channel++) { dataDelay2[channel] = dataFrame[channel, 748]; dataDelay1[channel] = dataFrame[channel, 749]; notchDelay2[channel] = dataNotch[channel, 748]; notchDelay1[channel] = dataNotch[channel, 749]; } if (enableNotch) { plotQueue.Enqueue(new USBData(dataNotch, auxFrame)); saveQueue.Enqueue(new USBData(dataNotch, auxFrame)); } else { plotQueue.Enqueue(new USBData(dataFrame, auxFrame)); saveQueue.Enqueue(new USBData(dataFrame, auxFrame)); } } }
// 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; }
public void receiveMsg(ref byte[] readData, uint res_length) // { UInt32 numBytesAvailable = 0; UInt32 numberOfTries = 0; do { ftStatus = ftdi_handle.GetRxBytesAvailable(ref numBytesAvailable); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press listBox1.Items.Add("Failed to get number of bytes available to read (error " + ftStatus.ToString() + ")"); return; } System.Threading.Thread.Sleep(5); numberOfTries++; } while (numBytesAvailable < res_length && numberOfTries < 100); if (numberOfTries > 99) { listBox1.Items.Add("No response received from the Device. Please check connection."); return; } UInt32 numBytesRead = 0; // Note that the Read method is overloaded, so can read string or byte array data ftStatus = ftdi_handle.Read(readData, res_length, ref numBytesRead); if (ftStatus != FTDI.FT_STATUS.FT_OK) { // Wait for a key press listBox1.Items.Add("Failed to read data (error " + ftStatus.ToString() + ")"); return; } //listBox2.Items.Add(BitConverter.ToString(readData)); return; /* * * //listBox2.Items.Add(GetBytesToString(readData)); * //listBox2.Items.Add(BitConverter.ToString(get_sRN_BA("DeviceIdent"))); * * // prepare the byte for the data * string value = ""; * foreach (byte byt in readData) * value += String.Format("{0} ", byt); * listBox2.Items.Add(value); * * * * // convert the byte array to ASCII code, HOW??? * string[] hexValuesSplit = BitConverter.ToString(readData).Split('-'); * string response = "test"; * foreach (String hex in hexValuesSplit) * { * // Convert the number expressed in base-16 to an integer. * int value = Convert.ToInt32(hex, 16); * // Get the character corresponding to the integral value. * * listBox2.Items.Add(((char)value).ToString()); * response += ((char)value).ToString(); * listBox2.Items.Add(response); * //Char.ConvertFromUtf32(value); * //listBox2.Items.Add(Char.ConvertFromUtf32(value).ToString()); * } * //listBox2.Items.Add(response); * * * * * // 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 = ftdi_handle.GetRxBytesAvailable(ref numBytesAvailable); * if (ftStatus != FTDI.FT_STATUS.FT_OK) * { * // Wait for a key press * listBox1.Items.Add("Failed to get number of bytes available to read (error " + ftStatus.ToString() + ")"); * return; * } * } while (numBytesAvailable < sRN_DeviceIdent_RES_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 = ftdi_handle.Read(out readData, numBytesAvailable, ref numBytesRead); * if (ftStatus != FTDI.FT_STATUS.FT_OK) * { * // Wait for a key press * listBox1.Items.Add("Failed to read data (error " + ftStatus.ToString() + ")"); * return; * } * listBox2.Items.Add(readData); * * // Close our device * ftStatus = ftdi_handle.Close(); */ }
private void Form1_Shown(object sender, EventArgs e) { UInt32 ftdiDeviceCount = 0; // Create new instance of the FTDI device class // Determine the number of FTDI devices connected to the machine ftStatus = myFtdiDevice.GetNumberOfDevices(ref ftdiDeviceCount); // Check status if (ftStatus == FTDI.FT_STATUS.FT_OK) { textBox1.Text += "Number of FTDI devices: " + ftdiDeviceCount.ToString() + "\r\n\r\n"; //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++) { //textBox1.Text += "Device Index: " + i.ToString() + "\r\n"; //textBox1.Text += "Flags: " + String.Format("{0:x}", ftdiDeviceList[i].Flags) + "\r\n"; textBox1.Text += "Type: " + ftdiDeviceList[i].Type.ToString() + "\r\n"; //textBox1.Text += "ID: " + String.Format("{0:x}", ftdiDeviceList[i].ID) + "\r\n"; //textBox1.Text += "Location ID: " + String.Format("{0:x}", ftdiDeviceList[i].LocId) + "\r\n"; textBox1.Text += "Serial Number: " + ftdiDeviceList[i].SerialNumber.ToString() + "\r\n"; //textBox1.Text += "Description: " + ftdiDeviceList[i].Description.ToString() + "\r\n"; //textBox1.Text += " \r\n"; } } // 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 { textBox1.Text += ftdiDeviceList[0].Description.ToString() + "\r\n"; //textBox1.Text += "Open OK: " + "\r\n"; } 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 { //textBox1.Text += "Reset OK: " + "\r\n"; } UInt32 numBytesRead = 0; UInt32 data = 0; UInt32 numBytesWritten = 5; Boolean calibrated = false; //4//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 //textBox1.Text += "Wait on calibration" + "\r\n"; //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(""); textBox1.Text += "Calibration done" + "\r\n"; //Console.WriteLine("Calibration done"); // read the offset value - the simpliest version without averaging 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; ///////////////freq offset ftStatus = myFtdiDevice.Write(cmd_rd_offset_f, 5, ref numBytesWritten); do { ftStatus = myFtdiDevice.GetRxBytesAvailable(ref numBytesRead); } while (numBytesRead < 4); ftStatus = myFtdiDevice.Read(read_buffer, 4, ref numBytesRead); data = BitConverter.ToUInt32(read_buffer, 0); // first 32-bit word //Count = (data << 12) | Count; Offset_F = data; //Console.WriteLine("Offset_F = " + Offset_F.ToString() + " Hz"); //Offset_F = Offset_F / 1000000000; button2.Visible = true; button1.Visible = false; }