Open/close file in while loop

VI reads 3 temperature sensors connected to RS232 port ( external rs232/RS485 converter , sensors have different addresses). When VI starts , user is asked to chose location and filename of data log file for each sensor ( write to the same file or to new file).
3 START/STOP buttons controls data logging from sensors. Right now it just starts or stops data reading from sensor and writing to file. What I would like to have is that user is asked to enter file name and location not when wole VI starts, but when he START/STOP button is pressed. ( When user press button 1, he is asked to enter file name and location. When data logging from that sensor is stopped, file is closed. When data logging is started again, user again must select data log file). The same for START/STOP buttons 2 and 3.
Attachments:
GIA10N_example.vi ‏116 KB

Hello.
The short answer is that you have to put the "Open/Create/Replace File.vi" inside the case stucture, so that that executes each time a button is pressed. You should also be closing the files after you write to them, which I did not see you doing in your VI.
I am attaching a modified version of your VI which should perform what I understand you want. I am using the "Write Characters To File.vi" which is an easy top level VI for writing data to files, which opens, writes and closes the file each time it is executed.
I also removed the local variables and used the boolean buttons directly inside the sequence structure. In general, you should avoid the use of local variables unless it is absolutely necessary.
Hope this helps.
Alejandro
Attachments:
GIA10N_exampleModified.vi ‏82 KB

Similar Messages

  • Problems with opening file with while loop

    Greetings everyone,
      This is probably a quick question, but I am familiarizing myself how to open data files in Labview. The attached code works if you enter a file from the folder button on the front panel. However, if the path is blank and you hit the run (arrow) button, a dialog box comes up and asks for the file.
       I select the file, but the dialog box keeps coming up. I think this has something to do with my while loop. Can anyone tell me where I am going wrong?
      Thanks!
       TheLT
    Solved!
    Go to Solution.
    Attachments:
    ReadingfromData.vi ‏27 KB

    TheLT,
    1. crossrulz was right. The Read FromSpreadsheet File.vi opens and closes the file each time it is called. If no file path is present at the input when it is called, it will pop up a file dialog.
    2. LabVIEW uses a dataflow paradigm. In your program the effect of this is that the File path control is read almost immediately when the program is started and never again after that. So, if the program is already running when the file is selected in that control, the new value is never read and the value (empty) in the control when the rpogram started is used.
    3. The fix is to use an event structure with a file path Value Changed event to detect when the control has a value entered and then read the file.
    4. Sequence structures obscure code, make it difficult to modify and extend code, and can almost always be eliminated by effective use of dataflow.  Local variables should not be used just to pass data around.  Wire is always the best way when possible. In your program adding a few wires allows elimination of the sequence structure and the local variables.
    5.  Your graph loop should have some kind of delay or wait.  No need for it to run as fast as the processor will allow - and to hog all the CPU time - to repeatedly put the same data onto the graph.  This is another place where an event structure is appropriate. Only update the graph when the X-Axis or Y-Axis selections have changed. Note: Accepted best practice is to use only one event structure in a program, although there are a few advanced cases where multiple event structures are appropriate.  You only need one.
    6. If the slected file does not contain the "endheader" string, the program will never stop.  Add a test for EOF to stop the program if the End of File is reached without finding the flag.
    Lynn
    Attachments:
    ReadingfromData.2.vi ‏27 KB

  • Writing text file in while loop

    Here is my question about writing text data to a file in a while loop...worded best I can.
    I have an Init case where I have the user choose a file path and name. I take the ref out and then I have data that is being written to the file. The loop will take 40,000 pieces of data write them to the file and go back to the get data case to collect another 40,000 data points. But when I open the file, I only get a file as big as 430KB. I'm not sure but can somone show me an example of pulling analog data from a DAQ Assist, doing a calculatoin on it, writing it to a file and repeating that by adding it to the same file at the end of the previous data?
    Solved!
    Go to Solution.

    Take a look at the attached VI's.  Did you have your data set to append?  This could be your problem.
    CLA, CLED, CTD,CPI, LabVIEW Champion
    Platinum Alliance Partner
    Senior Engineer
    Using LV 2013, 2012
    Don't forget Kudos for Good Answers, and Mark a solution if your problem is solved.
    Attachments:
    Save Data SM.vi ‏15 KB
    File Path Prompt.vi ‏15 KB

  • When to open\close file

    Hello, 
    I have a loop with data acquisition and I would like to write this data to a file. 
    What is the best option: to open the file once, at the beginning of the acquisition and to close it when it is done, to open it and close it every time I write a line on the file or to do something else?
    If there is no best option, I would like to understand the good and bad points of each option.
    Best regards, 
    Gabriel
    Solved!
    Go to Solution.

    Hi!
    Hmmm...
    The only right way to write into file or DB is the moment in time you should. Depending on the task under consideration, ofcoarse.
    If the data you get each iteration is of no vital importance, then once a whole loop or even program is enough.
    And, if each iteration's data is to be protected, I'd sertainly tried to find some system's time to open and close the file every single iteration - why not?
    Talking about "better"? The only "better" is not to crash, suppose. 
    Regards.

  • KUP-04063: unable to open log file.. (while selecting from External table)

    Hi
    I am trying to craete an external table and then select the data from the table. However I am getting error while trying to select the data from external table.
    SQL>CREATE OR REPLACE DIRECTORY my_dir as 'C:\arun';
    Directory created.
    SQL>GRANT ALL ON DIRECTORY my_dir TO PUBLIC;
    Grant succeeded.
    SQL>DROP TABLE proj_checklists_external;
    Table dropped.
    SQL>CREATE TABLE proj_checklists_external
    2 ( checklist_submission_id NUMBER
    3 ,Lead_reviewer_name VARCHAR2(30)
    4 ,Lead_reviewer_corp_id VARCHAR2(10)
    5 ,creation_date VARCHAR2(10)
    6 ,submitted_dater VARCHAR2(10)
    7 ,approved_date VARCHAR2(10)
    8 ,status VARCHAR2(50)
    9 )
    10 ORGANIZATION EXTERNAL
    11 (
    12 TYPE ORACLE_LOADER
    13 DEFAULT DIRECTORY my_dir
    14 ACCESS PARAMETERS
    15 (
    16 RECORDS DELIMITED BY NEWLINE
    17 FIELDS TERMINATED BY ','
    18 )
    19 LOCATION ('Book1.txt')
    20 )
    21 PARALLEL 5
    22 REJECT LIMIT 200;
    Table created.
    SQL>SELECT * FROM proj_checklists_external;
    SELECT * FROM proj_checklists_external
    ERROR at line 1:
    ORA-29913: error in executing ODCIEXTTABLEOPEN callout
    ORA-29400: data cartridge error
    KUP-04063: unable to open log file PROJ_CHECKLISTS_EXTERNAL_28484.log
    OS error No such file or directory
    ORA-06512: at "SYS.ORACLE_LOADER", line 14
    ORA-06512: at line 1
    I craeted an file PROJ_CHECKLISTS_EXTERNAL_28484.log also in C:\arun and then tried to select but still got same error.
    Any idea how to overcome this error.
    Regards
    Arun

    here you go:
    SQL> CREATE OR REPLACE DIRECTORY GRATIS_LOAD as 'D:\AdvSourceData\Membership\';
    Directory created
    SQL> GRANT ALL ON DIRECTORY GRATIS_LOAD to ADVROLE;
    Grant succeeded
    SQL>
    SQL> DROP TABLE MEMB_BATCH_LOAD_ID;
    Table dropped
    SQL> CREATE TABLE MEMB_BATCH_LOAD_ID (
    2 ID_NUMBER VARCHAR2(10),
    3 STATUS CHAR(1)
    4 )
    5 ORGANIZATION EXTERNAL
    6 ( TYPE ORACLE_LOADER
    7 DEFAULT DIRECTORY GRATIS_LOAD
    8 ACCESS PARAMETERS
    9 ( records delimited by NEWLINE
    10 fields (
    11 ID_NUMBER POSITION (1:10) CHAR,
    12 STATUS POSITION (11:1) CHAR
    13 )
    14 )
    15 LOCATION
    16 ( 'GRATISID.TXT'
    17 )
    18 );
    Table created
    SQL> select * from memb_batch_load_id;
    select * from memb_batch_load_id
    ORA-29913: error in executing ODCIEXTTABLEOPEN callout
    ORA-29400: data cartridge error
    KUP-04063: unable to open log file MEMB_BATCH_LOAD_ID_1388_5552.log
    OS error The system cannot find the file specified.
    ORA-06512: at "SYS.ORACLE_LOADER", line 14
    ORA-06512: at line 1
    SQL>

  • DMEE - Error with event 25 open/close file

    Hi All,
    I have created a new format in DMEE (and in the customizing), I generate a flat file with F110.
    I have created an event 00 and 25 to have a new file when the Bill of Exchange Due Date (FPAYH-WEFAE) changed.
    In the DMEE, at header level, in the tabstrip "Sort/key field", in the first step, I put FPAYH-WAFAE as key field and "no sorting" isn't flagged.
    When I have 2 differents Bill of Exchange Due Date in the same payment, I obtain only 1 file !
    Thank you very much for your help !
    Best regards,
    Odile Mayeur.

    Hi Alexandra,
    You can catch the exception in Exceptions part and close the file. Something like,
    DECLARE
    F_VersandZahlen CLIENT_TEXT_IO.FILE_TYPE;
    BEGIN
    F_VersandZahlen := CLIENT_TEXT_IO.FOPEN (F_Dateiname,'w');
    <do your processing>
    EXCEPTION
      WHEN OTHERS THEN
       CLIENT_TEXT_IO.FCLOSE(F_VersandZahlen);
    END;-Arun

  • Writing thermocoup​le data to measuremen​t file from while loop

    Hello,
    I'm trying to write thermocouple data that has already been filtered into a measurement file.  My code works, but has many zero-time entries (probably from the filtering aspect), and some of the non-zero-time entries are even out of sequence (my output file is attached as well as my VI.)  I'd love any help regarding getting this to work!
    Thanks in advance,
    Megan
    Attachments:
    FrontPanel.jpg ‏211 KB
    ThermocoupleDAQ_IOrtiz.vi ‏67 KB
    test1.csv ‏63 KB

    Hi Megan,
    do you really need to sample thermocouple data at 1kHz? How fast does the temperature change - and how fast do thermocouples react on that temp change? (Which sample rate is recommended for your hardware?)
    Are your filter settings reasonable? "TC2 unfiltered" looks quite ok, while the "filtered" graph looks awful (atleast for a TC measurement)…
    And you should definitely fetch a constant number of samples from DAQmxRead. Usually you read 1/10th of the sample rate, so reading 100 samples for 1kHz sample rate!
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • Open and close visa inside a while loop

    Hi,
    I need to read a position from a control unit device continuously or even by click a button, for this I have to put "visa configure serial port" and" "visa close" inside a while loop. Dose it make any problem?

    You shouldn't need the VISA Event nodes.  Get rid of those.
    Why are you using Concatinate String just to build up a constant.  Just create a single string constant.  It is a lot cleaner.
    Is the antenna constantly sending data to you or only when you request it?
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • Why does while loop pause during operation

    Hi everyone,
    I have written the attached code which will eventually be a part of a bigger program. The program is intended to log some test value, in this case just the date and time  to a csv file  when a button is pressed (log in WHITE, loop1).  Loop2 is intended to read a test value from a line in the first csv file and then add an extra test value to the end of that line when the serial number matches and then saves that line to a new csv file. This all works well but loop2 seems to pause a few times before continuing when either of the log button is pressed. I tried putting the code in 1 while loop with no success. Can anybody see what I am doing wrong?
    Attachments:
    ResinV10_csv.vi ‏25 KB

    Maiz wrote:
    Can anybody see what I am doing wrong?
    In addition to waht has been said already, your code is extremely convoluted.
    How often does the "read" file change? Do you really need to read the entire file with thousands of rows every ms just to look at one row?. If the file never changes, you could read it once before the loop.
    The way do do array opearions is mind boggling. You take one row, Index out the first element twice in parallel (once is enough!), then you index out the first element, built it into an array of one element, and compare that array with a scalar. Would't comparing the orignal element with the scalar be equivalent?
    Index array is resizable, you only need one instance.
    Getting five elements in a row just to build them back into a 1D array seems rather pointless. If the array has only five elements, there is nothing to do, and if it has more elements, you cold use "array subset", and if it has fewer elements, use "reshape array" to size 5.
    The correct format for reading strings is %s (not %.10f).
    Since you want both loops to run at the same speed, why don't you put it all in one loop? (this even eliminates the local variable) Then you could use a parallel loop for the file saving, using queues in order not to slow down the main loop. In the parallel loop, open the files before the loop, use lowlevel writes inside the loop, and close the files once the program stops.
    Can you explain your setup and what the program is supposed to do? I am sure it could be done with 20% of the current code.
    LabVIEW Champion . Do more with less code and in less time .

  • Cursor without WHILE loop

    I have always seen and used CURSORs with WHILE loops.
    I am looking for great examples where CURSORs are used without WHILE loops. Thanks.
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Database Design
    New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014

    You can implement any logic that you want. We need to know what is your needs in order to post a code. If all you need is to make a loop on all the SET in the same way while do, without using while loop then here is a simple example. You can implement any
    WHILE loop with IF condition and GOTO. This is only for sake of discussion and I will not use this code in production :-) 
    use AdventureWorks2014
    GO
    SET NOCOUNT ON;
    DECLARE @vendor_name nvarchar(50)
    DECLARE vendor_cursor CURSOR SCROLL FOR
    SELECT Name
    FROM Purchasing.Vendor
    WHERE PreferredVendorStatus = 1
    OPEN vendor_cursor
    PRINT '******** Using While loop ********'
    FETCH NEXT FROM vendor_cursor INTO @vendor_name
    WHILE @@FETCH_STATUS = 0
    BEGIN
    PRINT @vendor_name
    FETCH NEXT FROM vendor_cursor INTO @vendor_name
    END
    CLOSE vendor_cursor;
    OPEN vendor_cursor
    PRINT '******** Without Using While loop! ********'
    FETCH NEXT FROM vendor_cursor INTO @vendor_name
    Starting_Read_From_Cursor:
    -- Using If with GO TO
    IF @@FETCH_STATUS = 0 BEGIN
    PRINT @vendor_name
    FETCH NEXT FROM vendor_cursor INTO @vendor_name
    GOTO Starting_Read_From_Cursor
    END
    CLOSE vendor_cursor;
    DEALLOCATE vendor_cursor;
    I hope this useful :-)
    I am not sure for what, at the moment
    [Personal Site]  [Blog]  [Facebook]

  • Error opening the file:8-Per diems upload

    Hi Experts,
    I am trying to upload the perdiems for the year 2013. I got the error "Error opening the file:8" while doing so. I tried uploading in both .txt as well .xls. Resulted with the same error. Kindly suggest to overome this.
    Regards,
    Anil Kumar P.

    Hi Anil, I experienced the same issue when uploading the file. I resolved this by removing the " characters contained when pasting in the new values.

  • While opening pdf files the menu bar, navigation bar  cracks unobviously and also close and minimise buttons  goes hidden..Facing the problem for last one month. Please help.

    while opening pdf files the menu bar, navigation bar  cracks unobviously and also close and minimise buttons  goes hidden..Facing the problem for last one month. Please help.

    The latest Kaspersky software version is 15.0.1.415 or 15.0.1.415ab.

  • Another novice question...I opened a file used "Concatenate String" to write to file creating headers and so forth...a "While Loop" routine is m

    onitoring a voltage and storing it to the same file under the associated header...What I'm having problems doing is after the loop is completed I need to write the MIN\MAX values of the voltage that was monitored in the "While Loop" once it completes. I juBefore the loop the "Concatenate String" peforms the following... line1 col.1 in an excel file is (Tester then Line1 col.2 (the testers name appears) next is a end of line. Then Line2 col.1 is (DATE)header then col.2(TIME)header then col.3(throttle voltage output)header then col.4(MAX VOUT)header then col.5(MIN VOUT) as i said this is perform before the loop with no pr
    oblem. Next during the "While Loop" the actual information for the DATE,TIME,Throttle voltage output,are inserted into Line 3 under the associated header with no problem. What I need to do is wait until the "While Loop" has completed to then store the MAX/MIN, but I can't seem to get the information to end up under the associated header. What do I need to set/use to accomplish this task? Thanks I've attached an excel spread sheet to give an example of where I need the values to be stored.
    Attachments:
    test1.txt ‏1 KB

    onitoring a voltage and storing it to the same file under the associated header...What I'm having problems doing is after the loop is completed I need to write the MIN\MAX values of the voltage that was monitored in the "While Loop" once it completes. I juThis can become hard depending on how much data you will be writing. If you could wait and write the data all at one at the end of the while loop it becomes easier. The problem is that when you write a file it writes it in rows of data not columns. I will attach an example (LabVIEW 6.0) that demonstrates how to do this. It is a hard to describe in text. Basically I create the new columns of data and write empty strings to them on each iteration of the while loop except for the first iteration. The first iteration I write a Max? and Min? into the column information. After the while loop is completed I search the array for Max? and Min? and replace it with the appropriate min and max values.
    Attachments:
    append_column.vi ‏47 KB

  • PROBLEM while using URL in order to open a file from a servlet

    Hi,
    I am having a problem while trying to open a file from my servlet by using URL connection. Following is my code sample. what happens is when I first run my project it opens the file but after that when I rerun it again and again it sometimes opens it and sometimes not. if it can't open it it gives an error saying "the file is damaged and couldn't be repaired". I don't get any exceptions. if you guys can help me I will appreciate it so much... thanks.
    here is my code :
    URL url = new URL("http://demobcs.ibm.com:81/test.pdf");
    resp.setContentType(getContentType("http://demobcs.ibm.com:81/test.pdf"));
              ServletOutputStream sos = null;
              BufferedInputStream bis = null;
              try {
                   sos = resp.getOutputStream();
              } catch (Exception e) {
                   System.out.println("exception !!!!");
                   e.printStackTrace();
              System.out.println("burada2");
              try {
                   byte[] bytes = new byte[4096];
                   //bis = new BufferedInputStream(conn.getInputStream());
                   DataInputStream in = new DataInputStream(url.openStream());
                   //DataInputStream in = new DataInputStream(conn.getInputStream());
                   bis = new BufferedInputStream(in);
                   int j;
                   while ((j = bis.read(bytes, 0, 4096)) != -1) {
                        try {
                             sos.write(bytes, 0, 4096);
                             System.out.println("file is being read ...:");
                        } catch (Exception e) {
                             e.printStackTrace();
                   in.close();
                   bis.close();          
                   //sos.close();
              } catch (Exception e) {
                   System.out.println("exception :"+e.toString());
                   e.printStackTrace();
              }

    You are writing (<filesize> mod 4096) bytes of crap at the end of the file. Use your variable j instead for the number of bytes to write in your loop.

  • How to  open the file writer for next entry after stream is close?

    import java.io.BufferedWriter;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.Scanner;
    public class TryOut {
         public static void main(String args[]) throws IOException{
              int inputQuestionnAireNum = 0;
              int inputPostCode = 0;
              int inputGender = 0;
              int inputAge = 0;
              int x=0;
              Scanner input = new Scanner(System.in);
              FileWriter fwrite = new FileWriter("tryout.txt", true);
              BufferedWriter out = new BufferedWriter(fwrite);
              boolean invalidNum = false;           
              do{
                   System.out.print("1 new entry or 0 print");
                   x = Integer.parseInt(input.nextLine());  
                   if(x == 1)
                      //Questionnaire Number
                        System.out.print("Enter Questionnaire Number [ ] ");
                        inputQuestionnAireNum = Integer.parseInt(input.nextLine());
                        out.write("NumBER OF Q: "+inputQuestionnAireNum+", ");
                        //Postal code
                        System.out.print("Enter Postal Code [ ] ");     
                        inputPostCode = Integer.parseInt(input.nextLine());
                        out.write("PostCode: "+inputPostCode+", ");
                        //Age
                        System.out.print("Enter Age [ ] ");
                        inputAge = Integer.parseInt(input.nextLine());
                        out.write("Age: "+inputAge+", ");
                        //Gender
                        System.out.print("Enter Gender '1' for Male and '2' for for female [ ] ");
                        inputGender = Integer.parseInt(input.nextLine());
                        out.write("Gender: "+inputGender+", \n");
                        out.close();          
                           } while(x != 0);
         Result:
    1 new entry or 0 print1
    Enter Questionnaire Number [ ] 2
    Enter Postal Code [ ] 1
    Enter Age [ ] 3
    Enter Gender '1' for Male and '2' for for female [ ] 4
    1 new entry or 0 print1
    Enter Questionnaire Number [ ] 2
    Exception in thread "main" java.io.IOException: Stream closed
         at java.io.BufferedWriter.ensureOpen(BufferedWriter.java:98)
         at java.io.BufferedWriter.write(BufferedWriter.java:203)
         at java.io.Writer.write(Writer.java:126)
         at TryOut.main(TryOut.java:31)
    Hi, how can i open the file writer stream again for next entry after it is has been closed? if i do not close(); all my entry will not be recorded to the text file. how can i solve this ?
    Edited by: metaroot on Feb 18, 2008 6:39 PM

    The short answer to your question: use out=new BufferedWriter(fwrite) inside the do loop as well.The only difference that would make would be to make the problem worse. It is poor practice. Stream stacks should be constructed once for the life of the stream.
    What he needs to do is close his stream outside the loop, possibly calling flush() where he presently has close().
    The more relevant answer is: Why are you not wrapping the user-friendly PrintWriter class, wrapping it around the BufferedWriter?Possibly because he doesn't like the fact that PrintWriter swallows exceptions? which makes it less user-friendly IMO.
    The println and print methods are very useful, and do not need closing between loop iterations.Neither does anything else.
    By the way,you say that without a close() the BufferedWriter doesn't output to the file.I don't know: I never used/tried it.Even if it doesn't, it will surely output after you come out of the loop.If you don't want to use a PrintWriter, why don't you investigate this?Posting guesses here isn' t really much help, especially about something you've never used. A BufferedWriter has a buffer and it doesn't write anything until the buffer is full, you flush it, or your close it.

Maybe you are looking for

  • Thunderbolt to HDMI not Detecting LG TV

    My imac is not detecting Thunderbolt to HDMI not Detecting LG TV Only did detect once and now can get it back?? Mac Version 10.7.5

  • Roaming between E3000 wireless router and WAP300N

    Hi all The Linksys router I've got in my office room at home is providing poor coverage in my living room. Thus I've purchased a WAP300N and connected it by wire to the build-in 4 port switch of my Router (E3000). The set-up is providing a significan

  • Multiple context mode, how to download the packet capture file

    Hi guys, Is there a way to download the packet capture file from a specific context? I know that I used to use https://<ASA_IP>/admin/capture/<capture> to download it if it is just one context.  The ASA uses mgmt 0/0 for management and it is connecte

  • TS1398 How can I get the verify server page to appear, again?

    Accidentally dismissed pop-up about server verification, now I cannot connect to wifi. How do I get pop-up to reappear? I have pushed "forgot this network multiple times, turned phone on and off, reset network settings, all to no avail. Suggestions?

  • CRM administrator console - Problem

    Hallo I try create a new Site for mobile client (type: mobile client), but in admin console this type does not exist (in combobox). In table SMW1SPRVDR there is an entry with this type. Can somebody help me? Thanks Jan