Timing with while loop

Hello,
How can I do a time with while loop?. I want to read a data in the While- Loop for 1 sec and then go to B .. I added a pic,
Attachments:
while- loop.GIF ‏6 KB

nichts wrote:
Hello,
How can I do a time with while loop?. I want to read a data in the While- Loop for 1 sec and then go to B .. I added a pic,
I would use as GerdW has mentioned,"elapsed time.vi" in a statement 1st case structure, after set time has elapsed> goto 2nd case structure. try not to use flat sequences....this can be done with case statements with transitional coding. I have noticed young LV programmers like to use flat sequences...I think it's a trap set up by LV developers? 

Similar Messages

  • Time not stopping with while loop

    Hello,
    I've attached my VI.  I am having trouble with while loops.
    I want to turn on LEDs. The first LED should turn on after 3s.  The second LED should turn on after 5s.  The third LED will turn on later. 
    The LEDs turn on based on the following conditions:
    Case 0: numeric control > 10 then led_1 off, led_2 off, led_3 off
    Case 1: numeric control <= 10 then led_1 on, led_2 on, led_3 on
    Case 2: numeric control <=5 then led_3 on
    Because of the way I'm delaying time, I have the following problems
    Case 1 --> case 2: led_3 doesn't come on right away
    Case 2 --> case 1: led_3 doesn't turn off right away
    Putting probes in certain areas leads me to believe that these problems are due to the way the time delay is being generated.
    Thanks in advance.
    EDIT: Looking at it more...it seems to be that when the stop condition is true, the loop runs one more iteration. Is there a way to keep it from running that "one more iteration."
    Attachments:
    timing.vi ‏15 KB

    One of the problems is that your VI is not able to "breathe" because it is sometimes trapped inside inner loops that consume all CPU and step on each others toes. All you need is an single outer loop and a few shift registers.
    May of your specifications are still not clear, for example what should happen to LED 1&2 in case #3? Should they remain in the state they are in, or should they turn off, for example.
    Here is a simple rewrite that spins the outer loop at a regular rate, has no inner loop, and does not need any local variables or value property nodes. See if it makes sense. Also note that your code can be simplified dramatically by using arrays. Since the stop button is read with each of the regular interations, we don't need to worry about sequencing.
    Most likely you need to do a few simple modofications, because your specs are not clear.
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    timingMODCA.vi ‏15 KB

  • Ending Java War game with while loop

    How would i go about ending a java war game witha while loop. I want the program to run until all of the values of one of the arrays of one of the players split decks has all null values.

    GameObject[] theArrayInQuestion;
    // populate array somehow or other
    void methodWithLoop() {
       while(arrayNotNull(theArrayInQuestion)) {
       // do stuff
    boolean arrayNotNull(Object[] array) {
      int len = array.length;
      for(int i = 0; i < len; i++) {
        if ( array[i] != null ) {
          return true;
      return false
    }

  • Probably simple problem with while loops

    I was programming something for a CS class and came across a problem I can't explain with while loops. The condition for the loop is true, but the loop doesn't continue; it terminates after executing once. The actual program was bigger than this, but I isolated my problem to a short loop:
    import java.util.Scanner;
    public class ok {
    public static void main(String[] args){
         Scanner scan = new Scanner(System.in);
         String antlol = "p";
         while(antlol == "p" || antlol == "P"){
              System.out.println("write a P so we can get this over with");
              antlol = scan.nextLine(); 
    //it terminates after this, even if I type "P", which should make the while condition true.
    }

    Thanks, that worked.
    I think my real problem with this program was my CS
    teacher, who never covered how to compare strings,Here's something important.
    This isn't just about comparing Strings. This applies to comparing ANY objects. When you use == that compares to see if two references refer to the same instance. equals compares objects for equality in the sense that equality means they have equal "content" as it were.

  • Problem with while loop in thread: starting an audiostream

    Hello guys,
    I'm doing this project for school and I'm trying to make a simple app that plays a number of samples and forms a beat, baed on which buttons on the screen are pressed, think like fruity loops. But perhaps a screenshot of my unfnished GUI makes things a bit more clear:
    [http://www.speedyshare.com/794260193.html]
    Anyway, on pressing the play button, I start building an arraylist with all the selected samples and start playing them. Once the end of the "screen" is reached it should start playing again, this is the while loop:
    public void run(){
            //System.out.println("Wavfiles.size =" + getWavfiles().size());
            System.out.println(repeatperiod);
            if (getWavfiles() == null) {
                System.out.println("Error: list of Wavfiles is empty, cannot start playing.");
            else{
                if(!active) return;
                while(active){
                    System.out.println("Wavfiles.size =" + getWavfiles().size());
                    for (int i=0; i<getWavfiles().size(); i++){
                        Wavplayer filePlayer = new Wavplayer(getWavfiles().get(i).getStream());
                        Timer timer = new Timer();
                        //timer.scheduleAtFixedRate(filePlayer, getWavfiles().get(i).getStartTime(),repeatperiod);
                        timer.schedule(filePlayer, getWavfiles().get(i).getStartTime());
                    try {
                        Thread.sleep(repeatperiod);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(LineBuilder.class.getName()).log(Level.SEVERE, null, ex);
        }But once the second iteration should begin, I'm getting nullpointerexceptions. These nullpointerexceptions come exactly when the second period starts so I suppose the sleep works :-) The nullpointerexception comes from the wavfile I try to play. Wavfile class:
    package BeatMixer.audio;
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import java.util.TimerTask;
    import javax.sound.sampled.AudioFormat;
    import javax.sound.sampled.AudioInputStream;
    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.DataLine;
    import javax.sound.sampled.LineUnavailableException;
    import javax.sound.sampled.SourceDataLine;
    import javax.sound.sampled.UnsupportedAudioFileException;
    public class Wavplayer extends TimerTask {
            private SourceDataLine auline;
            private AudioInputStream audioInputStream;
         private final int EXTERNAL_BUFFER_SIZE = 524288; // 128Kb
         public Wavplayer(ByteArrayInputStream wavstream) {
              try {
                   audioInputStream = AudioSystem.getAudioInputStream(wavstream);
              } catch (UnsupportedAudioFileException e1) {
                   e1.printStackTrace();
                   return;
              } catch (IOException e1) {
                   e1.printStackTrace();
                   return;
                    AudioFormat format = audioInputStream.getFormat();
              DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
                    try {
                   auline = (SourceDataLine) AudioSystem.getLine(info);
                   auline.open(format);
              } catch (LineUnavailableException e) {
                   e.printStackTrace();
                   return;
              } catch (Exception e) {
                   e.printStackTrace();
                   return;
        @Override
         public void run() {
                    System.out.println(auline);
              auline.start();
              int nBytesRead = 0;
              byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
              try {
                   while (nBytesRead != -1) {
                        nBytesRead = audioInputStream.read(abData, 0, abData.length);
                        if (nBytesRead >= 0)
                             auline.write(abData, 0, nBytesRead);
              } catch (IOException e) {
                   e.printStackTrace();
                   return;
              } finally {
                   auline.drain();
                   auline.close();
    }auline is null on second iteration, in fact, getAudioInputStream doesn't really work anymore, and I don't know why because I don't change anything about my list of wavfiles as far as I know... Any thoughts or extra info needed?
    Edited by: Lorre on May 26, 2008 12:22 PM

    Is my question not clear enough? Do you need more info? Or is nobody here familiar with javax.sound.sampled?
    Edited by: Lorre on May 26, 2008 2:07 PM

  • Problem with While Loop.

    Hi guys,
    i'm doing a pass exam java question, below is the question criteria.
    Write a program that allows a user to enter their mark attained in each unit and displays their grade. After all marks are entered the average mark is displayed.
    The main method should:
    Prompt the user to enter the number of units taken (check for NumberFormatException)
    Write a for loop to repeat for each subject, where each iteration
    Prompts the user to enter a mark ( a double) for unit 1, unit 2 etc. This should be in a while loop so if mark entered is less than 0 or greater than 100 the prompt will be repeated.
    Pass the mark to a method called getGrade.
    Display the returned grade
    Accumulate each mark
    Print the average mark to 2 decimal places
    The getGrade method should:
    Accept the parameter passed from the main method
    Determine the grade according to the following scale
    Return the grade
    The words that i highlighted in bold is the criteria.
    As you can see from the above question, i create an array , even though the question does not prompt me to create as what i know from tackling JavaQuestions "if it does not prompt me to add a criteria, it is ok to add it" :)
    below is my program code , in which the result i get is the same as the question result. BUT, from the above question it ask me to add a while loop, so if mark entered is less than 0 or greater than 100 the prompt will be repeated.
    But instead i use a do loop. :(
    so can anyone help me or show me how to create the while loop for mark entered is less than 0 or greater than 100 the prompt will be repeated, from my program code below. cause i want to know whether it possible to have a while loop instead of do loop for the my program and the while loop can work with an array criteria.
    thanks
    htw.
    import javax.swing.*;
    import java.text.DecimalFormat;
    public class Mark
        public static void main (String [] args)
            String unitStr;
            String markEnterStr;
            int validUnit;
            double total = 0;
            boolean validInput = true;
            DecimalFormat fmt = new DecimalFormat("#0.00");
            while (validInput)
            unitStr = JOptionPane.showInputDialog(null,"Enter number of units: ");
            try
            validUnit = Integer.parseInt(unitStr);
            double[] markArray = new double[validUnit];
            validInput = false;
            for (int index = 0;index < validUnit; index++)
                do
                markEnterStr = JOptionPane.showInputDialog("Please enter mark " +(index+1) +":");           
                markArray[index] = Double.parseDouble(markEnterStr);
                while(markArray[index] < 0 || markArray[index] >100);
                String correctMark = getGrade(markArray[index]);
                System.out.println(correctMark);
                total = total + markArray[index];       
            double average = (double)total / validUnit;
            System.out.println("Average = " +fmt.format(average));                   
            catch (NumberFormatException e)
            public static String getGrade(double x)
                String grade;
                if (x < 50)
                grade = "Fail";
                else if (x < 60)
                grade = "Pass";
                else if (x < 70)
                grade = "Credit";
                else if (x < 80)
                grade = "Distinction";
                else grade = "High distinction";
                return grade;
    }

    Hope u got it.
               markArray[index] = -1;
                while(markArray[index] < 0 || markArray[index] >100);
                markEnterStr = JOptionPane.showInputDialog("Please enter mark " +(index+1) +":");           
                markArray[index] = Double.parseDouble(markEnterStr);
                }VJ

  • Problem with while loops, please help!

    I am having quite a bit of trouble with a program im working on. What i am doing is reading files from a directory in a for loop, in this loop the files are being broken into words and entered into a while loop where they are counted, the problem is i need to count the words in each file seperately and store each count in an array list or something similar. I also want to store the words in each file onto a seperate list
    for(...)
    read in files...
         //Go through each line of the first file
              while(matchLine1.find()) {
                   CharSequence line1 = matchLine1.group();
                   //Get the words in the line
                   String words1[] = wordBreak.split(line1);
                   for (int i1 = 0, n = words1.length; i1 < n; i1++) {
                        if(words1[i1].length() > 0) {
                             int count= 0;
                                           count++;
                             list1.add(words1[i1]);
              }This is what i have been doing, but with this method count stores the number of words in all files combined, not each individual file, and similarly list1 stores the words in all the files not in each individual file. Does anybody know how i could change this or what datastructures i could use that would allow me to store each file seperately. I would appreciate any help on this topic, Thanks!

    Don't try to construct complicated nested loops, it makes things a
    tangled mess. You want a collection of words per file. You have at least
    zero files. Given a file (or its name), you want to add a word to a collection
    associated with that file, right?
    A Map is perfect for this, i.e. the file's name can be the key and the
    associated value can be the collection of words. A separate simple class
    can be a 'MapManager' (ahem) that controls the access to this master
    map. This MapManager doesn't know anything about what type of
    collection is supposed to store all those words. Maybe you want to
    store just the unique words, maybe you want to store them all, including
    the duplicates etc. etc. The MapManager depends on a CollectionBuilder,
    i.e. a simple thing that is able to deliver a new collection to be associated
    with a file name. Here's the CollectionBuilder:public interface CollectionBuilder {
       Collection getCollection();
    }Because I'm feeling lazy today, I won't design an interface for a MapManager,
    so I simply make it a class; here it is:public class MapManager {
       private Map map= new HashMap(); // file/words association
       CollectionBuilder cb; // delivers Collections per file
       // constructor
       public MapManager(CollectionBuilder cb) { this.cb= cb; }
       // add a word 'word' given a filename 'name'
       public boolean addWord(String name, String word) {
          Collection c= map.get(name);
          if (c == null) { // nothing found for this file
             c= cb.getCollection(); // get a new collection
             map.put(name, c); // and associate it with the filename
          return c.add(word); // return whatever the collection returns
       // get the collection associated with a filename
       public Collection getCollection(String name) { return map.get(name); }
    }... now simply keep adding words from a file to this MapManager and
    retrieve the collections afterwards.
    kind regards,
    Jos

  • SubVI with while loop + event structure not working in multi tab VI

    Hello Everyone,
    I am developing an interface for the control of a prober using Labview 2012, and I am stuck with some issue.
    To start with I provide you with a simplified version of my control interface VI, and with the sub-VI used to build and manage the wafer maps.
    The VI consists of several tabs: Prober Initialization, Wafer Handling, Wafer Map, Status, Error.
    The sub-VI can:
    1/ initialize the grid to display the map (sub VI Init Grid not provided here)
    2/ import XY coordinates from a txt file (sub VI Wafer Map Import)
    3/ display the coordinates and index of the die below the cursor
    4/ and when a die position is double clicked, and the boolean "Edit Wafer Map" is true, then the user can change the state (color) of the die between On-wafer die and Selected Die
    My issue:
    If I use the sub-VI by itself, it works fine. However when I use it as a sub-VI in the tab "Wafer Map", the map does not build up and I can no further use the embedded functionalities in the sub-VI.
    I suspect the while loop + event structure of the sub-VI to be the bottleneck here.
    However I don't know which way to go, that's why I'd be glad to have some advice and help here.
    Thank you.
    Florian
    Solved!
    Go to Solution.
    Attachments:
    Control Interface.zip ‏61 KB

    Hi NitzZ,
    Thank you for your reply.
    I tried to save the VIs in LV10, please tell me if you can open them now.
    Inside he event structure there is quite some code, and since I don't want to make the main vi too bulky, I would like to keep it as a sub-VI. 
    As you can see from the sub-VI, the event structure is used for extracting cursor position and tracking the double click action. These events are linked, through a property node, to the image "Wafer Map" which is passed to the main vi through connector pane.
    All values are passed this way as well (through connector pane). Is there another way?
    Maybe "refnum", but I don't really understand how to use them...
    If I use the event structure in the main vi, the wafer map is still not working. I tried it earlier.
    To implement the multi tab front panel, I used a tab control, and a for loop + case structure. For each element of the case structure, there is a corresponding action.
    For the case where I put the code (element=2) for Wafer Map, I also control the execution of the code with a case structure activated by the button "REFRESH". Otherwise I end up with a freezing of the panel right after the start.
    I hope these comments help you understand better.
    Regards,
    Florian
    Attachments:
    Control Interface.zip ‏104 KB

  • Iteration non sequencial with While Loop

    I've a SubVi in while Loop. Iteration n+1 will execute when Iteration n finish.
    Can I execute this SubVi in paralel (no sequencial)?
    In Spanish:
    Tengo una SubVi dentro de un bucle while. Pero este bucle actúa de forma secuencial. No se cargará la iteración n+1 hasta que la n acabe.
    ¿Cómo puedo hacer para que se ejecuten las iteraciones de forma no secuencial? Es decir, que no haya que espera a que acabe una para que se ejecute la siguiente.

    Hello,
    it is not possible. The while loop works as follows: 1) execute the code inside 2) check the ternimation condition 3) depending on that, continues with the following iteration or exit from the while loop. So, it is not possible what you are asking for.
    Maybe you have to use two while loops.
    Regards
    rusC

  • Noob Help with While Loop

    Sorry for the "Noob"-ness on this one. I am working on a program for class and I am having a problem with a while loop. So I opened a new document and began to code a while loop that is basic to test my while looping skill. Apparrently, I have none. Can anyone tell me why this While Loop will not work:
    public class test
         public static void main(String[] args)
         int LoanTerm = 0;
              while (LoanTerm < 3);
                   System.out.println (LoanTerm);
                   LoanTerm++;
    Thanks.
    FatherVic

    to explain, the ; means that the while loop body is empty, and you will just spin forever testing whether LoanTerm < 3, without doing anything else.

  • Need help with while loops

    Hello let me first explain what im trying to achive:
    I want a moving square that you control with the arrow keys on the keyboard. It has to be smooth ie able to move fast without looking like its jumping and it has to be able to move diagonaly aswell. Think of that arcade game Raiden ...you know the birds-eye view plane flying game...another thing! I'd prefer if it didnt use timers - i made one already using 4 timers and it works great but 4 timers is a little extreme - SO NO TIMERS !
    I was thinking while loops, but i cant seem to get it working. I dont want to put in all the code so ill just say that I have 4 booleans: up, down, left right and the following code:
    public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_UP) {
    up = true;
    if (e.getKeyCode() == KeyEvent.VK_DOWN) {
    down = true;
    if (e.getKeyCode() == KeyEvent.VK_LEFT) {
    left = true;
    if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
    right = true;
    repaint();
    For the KeyReleased part i have the same as above exept it sets the booleans to false.
    Soooo in theory if i set up a while loop like this (using the up direction as an example) :
    while (up == true) {
    [move square up]
    So therefore when i press and hold the up arrow the loop will keep going untill i realease it right? WRONG ! it just keeps repeating indefinatly and it doesnt even do the " [move square up] " bit. I put a System.out.print in the loop to test and it kept printing out the message but it still didnt do the actual " [move square up] " bit.
    Im not sure if im putting the while loop in the right place either....If anyone has any idea on how to use while loops in this way please heeeelp ! Its so annoying because it just doesnt work ive tried so many ways...
    any help would be greatly apreciated !!!!

    Maybe you want something like this? You have to pause during the loop to allow for other events to happen, like if y ou release a key or whatever.
    while( true )
       if( up ) moveUp();
       else if( down ) moveDown();
       if( left ) moveLeft();
       else if( right ) moveRight();
       try
          Thread.currentThread().sleep(10);
       catch( InterruptedException e )
          System.out.println( "Thread interrupted!");
    }

  • Help needed with while loops please :)

    I'm beginning to study java at School.
    My assignment using while loops, to ask user to input 2 numbers.
    I have to output all odd number between the two.
    I have to output the sum of all even numbers between the two.
    Output all the numbers and their squares between 1-10.
    Output the squares of the odd numbers between the 2 numbers the user entered.
    Output all uppercase letters.
    If anyone can give me any help, I would appreciate it greatly.
    Thank you.
    Kelly.

    It would help if you put aside your code, and wrote out some pseudo-code first so that you understand the steps you will need to take. for example
    get input from user
    set counter to first number entered
    while counter less than/ equal to second number
          check if number is even
               if even, add to even_sum
               else output counter, along with its square
          increment counter by one
    end while
    output sum of evensthat block, when coded, will solve 3 of the problems, the other 2 will require separate loops
    Good Luck

  • Need help with while loop and shift registers

    I have a large data set and need to read in the data at maybe 200 samples at a time, process these samples through my VI, and have it append and concatenate a separate lvm file.  The part where I am confused is the shift registers. How do I limit the number of samples read in an iteration? How do I get the while loop to stop when all the data are read in?
    I've attached my diagram, maybe there is something wrong with my technique?
    Solved!
    Go to Solution.
    Attachments:
    shiftreg.JPG ‏56 KB

    This will give you an idea.  There are plenty of other (probably more efficient) methods.  This is a basic, quick and dirty solution to help you grasp the overall concept.
    Using LabVIEW: 7.1.1, 8.5.1 & 2013
    Attachments:
    ShiftRegLoop.JPG ‏54 KB

  • Help with while loops

    Im trying to create a while loop that outputs the revers of a string, eg nice one
    would be "eno ecin" Assuming i already have declared a variable intital string that holds the string, how do i go about this does anyone have any problem solving techniques. The charAt method needs to be used.

    i have a exam on saturday and it was a previous exam question that im trying to get help with i need to understand the course material thanks, i know how to use while loops but have trouble getting my head around this question. ill show you my code however i know its completely wrong.
    now i know i hvae to use the charAt method to return a character located at the integer i
    so i must go down after each case has been tested true therefore i want i=i-1;
    until i=0;
    String initialString="tucan";
    int i=initialString.length();
    while(i>0)
         return charAt();
         i=i-1;
         }

  • Need help with while loop

    Hi,
    I'm running a while loop to run through some results of a search. Anyway I know how to list the strings but my last item is a JComboBox (drop down box.) How do I go about changing that so its right for a drop down box. Its the one with questions marks in the code below.
            while (srs.next())
            //Get the values for each field in this row
            String projectName = srs.getString("PROJECT_NAME");
            System.out.println("Project Name = " + projectName );
            String projectOfficier = srs.getString("PROJECT_OFFICER");
            System.out.println("Project Officer = " + projectOfficier );
            String projectDescription = srs.getString("PROJECT_OFFICER");
            System.out.println("Project Description = " + projectDescription );
            String paymentSchedule = srs.getString("PAYMENT_SCHEDULE");
            System.out.println("Payment Schedule = " + paymentSchedule );
            String banksInvestment = srs.getString("BANKS_INVESTMENT");
            System.out.println("Banks Investment = " + banksInvestment );
        ?   String paymentsMade = srs.getString("PAYMENTS_MADE");
        ?   System.out.println("Payments Made = " + paymentsMade );Thanks.

    Yeah the Payments Made part is a JComboBox with 3 so called strings inside it. I wanna know instead of srs.getString what should I put in to replace String to get the results from a JComboBox?

Maybe you are looking for