We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hey,
i think you only want to execute the relevant time-logic once when the button is pressed. So you would have to move that code into the first section of your if-clause. Something like this:
void stopWatch() {
if (time.isPressed() && counterLogic == false) {
timeCounter++;
if (timeCounter == 1) {
startTime = millis();
}
if (timeCounter == 2) {
totalTime = timeT;
timeCounter = 0;
}
counterLogic = true;
} else if (!time.isPressed() && counterLogic == true) {
counterLogic = false;
}
println("Counter: " + timeCounter);
println("TimeT: " + timeT);
println("Time 2: " + totalTime);
}
Thanks. I have been looking for a guide like that but couldn't.
import controlP5.*;
ControlP5 cp5;
int timeCounter = 0;
int timeT = 0;
int totalTime = 0;
int output = 0;
int startTime = 0;
double speed;
PImage roulette;
PImage table;
PFont font;
Textfield perimeter;
Button spin;
Button time;
boolean counterLogic = false;
Textlabel headline;
void setup() {
size(540, 500);
background(0, 0, 0);
cp5 = new ControlP5(this);
font = createFont("arial", 30);
roulette = loadImage("roulette.png");
roulette.resize(200, 200);
table = loadImage("roulette-table.png");
table.resize(500, 160);
headline = cp5.addTextlabel("Headline")
.setText("Roulette Calculator")
.setPosition(85, 25)
.setColorValue(color(255))
.setFont(createFont("arial", 40));
perimeter = cp5.addTextfield("Omkreds")
.setPosition(20, 100)
.setSize(100, 45)
.setFont(font)
.setFocus(true)
.setAutoClear(false)
.setLabelVisible(false)
.setColor(color(255));
spin = cp5.addButton("Spin")
.setPosition(20, 180)
.setSize(100, 45)
.setVisible(true)
.setValue(1);
time = cp5.addButton("Time")
.setPosition(20, 240)
.setSize(100, 45)
.setVisible(true)
.setValue(2);
}
void draw() {
background(0);
image(roulette, 250, 100);
image(table, 20, 330 );
timeT = millis() - startTime;
text(timeT, 50, 50);
stopWatch();
//println(headline.getWidth());
}
private void stopWatch() {
if (time.isPressed() && counterLogic == false) {
timeCounter++;
counterLogic = true;
} else if (!time.isPressed() && counterLogic == true) {
counterLogic = false;
}
if (timeCounter == 1) {
startTime = millis();
}
if (timeCounter == 2) {
totalTime = timeT;
timeCounter = 0;
}
println("Counter: " + timeCounter);
println("TimeT: " + timeT);
println("Time 2: " + totalTime);
}
I have tried your example and it works, but I have trouble implementing it into my code. When I press the button, it stays between 16 and 18. Can't see why?
import controlP5.*;
ControlP5 cp5; int timeCounter = 0; int timeT = 0; int totalTime = 0; int output = 0; int startTime = 0; double speed; PImage roulette; PImage table; PFont font; Textfield perimeter; Button spin; Button time; boolean counterLogic = false; Textlabel headline;
void setup(){ size(540, 500); background(0, 0, 0); cp5 = new ControlP5(this);
font = createFont("arial", 30);
roulette = loadImage("roulette.png"); roulette.resize(200,200);
table = loadImage("roulette-table.png"); table.resize(500,160);
headline = cp5.addTextlabel("Headline") .setText("Roulette Calculator") .setPosition(85,25) .setColorValue(color(255)) .setFont(createFont("arial",40));
perimeter = cp5.addTextfield("Omkreds") .setPosition(20,100) .setSize(100,45) .setFont(font) .setFocus(true) .setAutoClear(false) .setLabelVisible(false) .setColor(color(255));
spin = cp5.addButton("Spin") .setPosition(20,180) .setSize(100,45) .setVisible(true) .setValue(1);
time = cp5.addButton("Time") .setPosition(20,240) .setSize(100,45) .setVisible(true) .setValue(2); }
void draw(){ background(0); image(roulette, 250, 100); image(table, 20, 330 );
timeT = millis() - startTime; text(timeT, 50,50);
stopWatch(); //println(headline.getWidth()); }
private void stopWatch(){
if(time.isPressed() && counterLogic == false){ timeCounter++; counterLogic = true;} else if (!time.isPressed() && counterLogic == true){ counterLogic = false;}
if(timeCounter == 1){ startTime = millis();}
if (timeCounter == 2){ totalTime = timeT; timeCounter = 0;}
println("Counter: " + timeCounter); println("TimeT: " + timeT); println("Time 2: " + totalTime);}
I need a stopwatch function. It has to be able to start by the press of a button and stop again, when the button is pressed again. After that the time is has counted has to be copied to another variable, so that the timer can be reset and start over. I have tried with the millis() in processing, but can't reset it. It has to be counted in miliseconds because it has to used in some precise calculations.
Can anyone help me?
My code so far...
private void stopWatch(){
if(time.isPressed() && counterLogic == false){ timeCounter++; counterLogic = true;} else if (!time.isPressed() && counterLogic == true){ counterLogic = false;}
if(timeCounter == 1){ timeEstablised = millis();}
if (timeCounter == 2){ totalTime = timeEstablised; timeCounter = 0; timeEstablised = 0;}
println("Counter: " + timeCounter); println("Time: " + timeEstablised); println("Time 2: " + totalTime);}
first of all, thank you for the consideration.
what i mean is: speed of the blue/purple rectangles filling the screen is > than the speed for the yellow/green/white rectangles.
at first i thought it was something like an optical illusion, but then i measured with a stopwatch the time span in which the screen is filled with blue/purple rectangles and it is < than the time span that it takes to the screen to get white again. the difference is circa 1 second, one second an a half (i am not a very good stopwatcher, so it may be 1 or 1 second and a half).
can it be a problem of "lag"? i tried to println() the frames but it did not look like the problem was my computer.
on paper there shouldn't be a slow down, right?
In order to properly warm-up, we gotta call the actual methods being tested! :-w
isPrime(62131125996267401L);
isPrimeJS(62131125996267401L);
isPrime(46331401803043001L);
isPrimeJS(46331401803043001L);
isPrime(38924154034357817L);
isPrimeJS(38924154034357817L);
I've replaced both isPrime() & isPrimeJS() w/ my own versions.
I've only had to modify them to use a long
iterator since 9051643576320000001L
is a 63-bit value!
If that was at most 62-bit, my unmodified int
versions coulda been used instead! :-<
Probably would net slightly better results methinks...
Indeed, isPrimeJS() is the clear winner. W/ my version slightly faster than the 1 you tested with! \m/
And my own modified isPrimeLong(), using 6
step iterator jumps is much faster than the 1 using 2
only!
P.S.: My isPrimeJS() when using |
rather than ||
in the chained check expression is a few millis faster! :P
However, it's a tiny slower for the isPrimeLong()'s case! #-o
double test1, test2;
void setup() {
println("Warming up the CPU...");
warmup(10000000); //Let's get that CPU warmed up, so all comparisons are equal.
isPrimeLong(62131125996267401L);
isPrimeJS(62131125996267401L);
isPrimeLong(46331401803043001L);
isPrimeJS(46331401803043001L);
isPrimeLong(38924154034357817L);
isPrimeJS(38924154034357817L);
println("Initializing nanosecond timer...\n");
println("Done. Prime being tested is 9051643576320000001 (19 digits long).");
println("The prime number is fairly large, so be patient as the test occurs.\n");
Stopwatch s = new Stopwatch();
println("First algorthim. The original code, isPrime().");
println("\nStart.");
s.start();
println(isPrimeLong(9051643576320000001L));
s.stop();
println("Test complete. Time taken: " + s.getNanoTime() / 1000000d + " ms.\n");
test1 = s.getNanoTime() / 1000000d;
println("Second algorthim. Modified from JavaScripter, isPrimeJS().");
println("\nStart.");
s.start();
println(isPrimeJS(9051643576320000001L));
s.stop();
println("Test complete. Time taken: " + s.getNanoTime() / 1000000d + " ms.");
test2 = s.getNanoTime() / 1000000d;
boolean test1Wins = test1 < test2;
String winner = (test1Wins ? "IsPrime()" : "IsPrimeJS()");
String runnerUp = (test1Wins ? "IsPrimeJS()." : "IsPrime().");
double time = (test1Wins ? test1 : test2);
double ratio = (test1Wins ? test2 / test1 : test1 / test2);
println("Winner: " + winner + ", with a time of: " + time
+ " milliseconds, which is " + String.format("%.5f", ratio)
+ " faster than " + runnerUp);
exit();
}
void warmup(int upperLimit) {
int[] primes = new int[(upperLimit + 1) / 2];
int index = 1;
primes[0] = 2;
loop:
for (int i = 3; i <= upperLimit; i += 2) {
for (int p : primes) {
if (p * p > i) break;
if (i % p == 0) continue loop;
}
primes[index] = i;
index++;
}
}
//The original code
static final boolean isPrimeLong(long n) {
if (n <= 3L) return n >= 2L;
if ((n&1L) == 0L | n%3L == 0L) return false;
long i = -1L, sqrtN = (long)Math.sqrt(n) + 1L;
while ((i+=6L) <= sqrtN)
if (n%i == 0L || n%(i+2L) == 0L) return false;
return true;
}
//JavaScripter's code
static final boolean isPrimeJS(long n) {
if (n <= 5L) return n >= 2L & n != 4L;
if ((n&1L) == 0L | n%3L == 0L | n%5L == 0L) return false;
long i = -23L, sqrtN = (long)Math.sqrt(n) + 1L;
while ((i+=30L) <= sqrtN) if
( n%i == 0L
| n%(i+4L) == 0L
| n%(i+6L) == 0L
| n%(i+10L) == 0L
| n%(i+12L) == 0L
| n%(i+16L) == 0L
| n%(i+22L) == 0L
| n%(i+24L) == 0L) return false;
return true;
}
class Stopwatch {
private long startTime;
private long stopTime;
public void start() {
startTime = System.nanoTime();
stopTime = startTime;
}
public void stop() {
stopTime = System.nanoTime();
}
public long getNanoTime() {
return stopTime - startTime;
}
}
Well, here's a bit of a test. An even match between the 2 algorithms.
Most of the the algorithms, excluding the one from JavaScripter, were for the most part the same, so I just took the most optimized one (feel free to replace it if you have a better one).
Here's the test code. I have a relatively high end computer, now, so isPrime() took 13.5 seconds to run, whereas isPrimeJS() to 6.7 seconds.
double test1, test2;
void setup() {
println("Warming up the CPU...");
warmup(10000000); //Let's get that CPU warmed up, so all comparisons are equal.
println("Initializing nanosecond timer...\n");
println("Done. Prime being tested is 9051643576320000001 (19 digits long).");
println("The prime number is fairly large, so be patient as the test occurs.\n");
Stopwatch s = new Stopwatch();
println("First algorthim. The original code, isPrime().");
println("\nStart.");
s.start();
println(isPrime(9051643576320000001L));
s.stop();
println("Test complete. Time taken: " + s.getNanoTime() / 1000000d + " ms.\n");
test1 = s.getNanoTime() / 1000000d;
println("Second algorthim. Modified from JavaScripter, isPrimeJS().");
println("\nStart.");
s.start();
println(isPrimeJS(9051643576320000001L));
s.stop();
println("Test complete. Time taken: " + s.getNanoTime() / 1000000d + " ms.");
test2 = s.getNanoTime() / 1000000d;
boolean test1Wins = test1 < test2;
String winner = (test1Wins ? "IsPrime()" : "IsPrimeJS()");
String runnerUp = (test1Wins ? "IsPrimeJS()." : "IsPrime().");
double time = (test1Wins ? test1 : test2);
double ratio = (test1Wins ? test2 / test1 : test1 / test2);
println("Winner: " + winner + ", with a time of: " + time + " milliseconds, which is " + String.format("%.5f", ratio) + " faster than " + runnerUp);
}
void warmup(int upperLimit) { //Sieve of Eratosthenes, used as a moderately computation intensive warm up.
int[] primes = new int[(upperLimit + 1) / 2];
int index = 1;
primes[0] = 2;
loop:
for (int i = 3; i <= upperLimit; i += 2) {
for (int p : primes) {
if (p * p > i) break;
if (i % p == 0) continue loop;
}
primes[index] = i;
index++;
}
}
//The original code
public static boolean isPrime(long num) {
if (num == 2) return true;
if ((num & 1l) == 0) return false;
for(long i = 3; i * i < num; i += 2) if(num % i == 0) return false;
return true;
}
//JavaScripter's code
public static boolean isPrimeJS(long num) {
if (num % 2 == 0) return false;
if (num % 3 == 0) return false;
if (num % 5 == 0) return false;
for (long i = 7; i * i <= num; i += 30) {
if (num % i == 0) return false;
if (num % (i + 4) == 0) return false;
if (num % (i + 6) == 0) return false;
if (num % (i + 10) == 0) return false;
if (num % (i + 12) == 0) return false;
if (num % (i + 16) == 0) return false;
if (num % (i + 22) == 0) return false;
if (num % (i + 24) == 0) return false;
}
return true;
}
class Stopwatch {
private long startTime;
private long stopTime;
public void start() {
startTime = System.nanoTime();
stopTime = startTime;
}
public void stop() {
stopTime = System.nanoTime();
}
public long getNanoTime() {
return stopTime - startTime;
}
}
The Stopwatch class is there, because it times the algorithms in nanoseconds, rather than milliseconds. This helps get a more accurate reading.
Tell us what you get.
i start program, pressing any key to sync with my stopwatch, than laser crossed and i see the time... till now its ok. i supose that timer continue 1 minute loop counting, but when next rider crossing laser it just starting timer from 0... thats the problem i cant guess..
Hi! I'm new to programming but last week we decided to make laser stopwatch system in our mtb competition.. so i decided to try. Making with Arduino (with photoresistor in analog input) with filled in Firmata, and trying to use processing to get rider's times on display. Our track is about 30sec, and starts every minute, so I need a timer, looped in a minute.. when rider cross laser - check the time and display it... As I said, I'm new in programming, so code may be stupid, but as is =) Now i have a problem with looping minute (60000ms), it just stopping the watch. Can't get it (((
import processing.serial.*;
import cc.arduino.*;
PFont font;
Arduino arduino;
int a = 8; // sets switch threshold
int bg = 200; //bg color
String txt = "Waiting...";
void setup() {
size(displayWidth, displayHeight);
background(bg);
textAlign(CENTER);
arduino = new Arduino(this, "COM3", 57600);
font = createFont("Impact",60,true);
textFont(font,80);
fill(20);
text(txt, displayWidth/2, displayHeight/2);
StopWatch.start();
}
void draw() {
if (arduino.analogRead(0)<a) { // shading trigger
StopWatch.stop();
String time = ("Time:\t " + StopWatch.time()/1e3);
background(bg);
text(time, displayWidth/2, displayHeight/2);
}
if (StopWatch.time()>60000)
{
///////////lag????
StopWatch.start();
}
if (keyPressed==true){ //restart to sync time
StopWatch.reset();
String res = ("Time:\t " + StopWatch.time()/1e3);
background(bg);
text(txt, displayWidth/2, displayHeight/2);
StopWatch.start();
}
// printArray(arduino.analogRead(0)); debug a
}
boolean sketchFullScreen() {
return true;
}
static final class StopWatch {
static long startTime, endTime;
static void start() {
startTime = System.currentTimeMillis();
}
static void stop() {
endTime = System.currentTimeMillis();
}
static long time() {
return endTime - startTime;
}
static void reset() {
startTime = endTime = 0;
}
}
I think is better we keep this public, so it may help someone else...
this is a good links about states
http://forum.processing.org/two/discussion/comment/21240#Comment_21240
and a try I made with your code... You probably will ant to add some more states, like you win one... But to get you started... I got rid of sound stuff as I don't have the sounds. You code was a little messed, like... stopWatch was never used... Try organizing your code, it's gonna be easier for you:
// adapted code
PImage photo1; //abbyw
PImage photo2; //lovelypic
//import ddf.minim.*; // sound import
//Minim minim; // sound variable
//AudioSample lovelysound; //sound audio and variable
int shapes = 1; // number of rects
int x1 ;
int x2;
int y1;
int y2 ;
int savedTime;
int totalTime = 3000;
int endTime ;
int state = 0;
void setup ( )
{
size(600, 400);
rectMode(CORNERS);
photo1 = loadImage("http:"+"//forum.processing.org/two/uploads/imageupload/463/AXDW2PAU21ZL.jpg");
photo2 = loadImage("http:"+"//forum.processing.org/two/uploads/imageupload/915/FMOO05Y7GQ3W.jpg");
background(0);
// minim = new Minim(this);
//lovelysound = minim.loadSample("lovelysound.mp3", 2048);
reset();
}
void draw ()
{
switch (state) {
case 0:
initialScreen();
break;
case 1:
game();
break;
case 2:
gameOver();
break;
}
}
void initialScreen() {
background(0);
String s = "press s to begin";
fill(255, 0, 0);
text(s, width/2 - (textWidth(s)/2), height -15);
}
void game() {
image(photo1, 0, 0);
fill(255, 0, 0);
rect(x1, y1, x2, y2);
float passedTime = millis() - savedTime;
if (mouseX>x1 && mouseX<x2 && mouseY>y1 && mouseY<y2 && mousePressed &&
passedTime < totalTime) {
fill(255);
rect(x1, y1, x2, y2);
println("You Win: Your total time is" + " " + passedTime/1000 + " " + "Seconds");
state = 0;
reset();
}
if (passedTime > totalTime) {
endTime = millis();
state = 2;
}
}
void gameOver() {
println("You reaction is too slow!");
image(photo2, 0, 0);
float passedTime = millis() - endTime;
if (passedTime > 2000) {
reset();
}
}
void reset() {
x1 = int(random(width/2)); // x for rect
x2 = x1 + 5; //x2 for rect
y1 = int(random(height/2)); //y for rect
y2 = y1 + 3; // y2 for rect
savedTime = millis();
state = 0;
}
void keyPressed() {
if (state == 0) {
if (key == 's' || key == 'S') {
state = 1;
println(state);
}
}
}
//sound off
void stop() {
//lovelysound.close();
//minim.stop();
//super.stop();
}
Sorry about that, below is the full code, and I added the files I used except the audio(I don't see a upload for files). I tried doing a reset, and it didn't work for me, (most likely a error on my end). This sketch is suppose to be that you find a little red rectangle on the screen within 3 seconds or else monster face pop up and scream. everything works fine, but if the player loses and the monster face yells, the game stops due to my noloop(). My goal was so players that was too slow, to get the option to do a keyPressed, so the sketch could restart again. I can't figured why it's not resetting (I google it and tried various methods but I must be doing something wrong)
// Template for the Reaction time project
StopWatch myTimer; // timer variable
PImage photo1; //abbyw
PImage photo2; //lovelypic
import ddf.minim.*; // sound import
Minim minim; // sound variable
AudioSample lovelysound; //sound audio and variable
int shapes = 1; // number of rects
int x1 = int(random(width/2));
int x2 = x1 + 5;
int y1 = int(random(height/2));
int y2 = y1 + 3;
int savedTime;
int totalTime = 3000;
void setup ( )
{
size(600,400);
rectMode(CORNERS);
photo1 = loadImage("abbyw.jpg");
photo2 = loadImage("lovelypic.jpg");
background(photo1);
myTimer = new StopWatch ( ) ;
minim = new Minim(this);
lovelysound = minim.loadSample("lovelysound.mp3", 2048);
x1 = int(random(width/2)); // x for rect
x2 = x1 + 5; //x2 for rect
y1 = int(random(height/2)); //y for rect
y2 = y1 + 3; // y2 for rect
savedTime = millis();
}
void draw ( )
{
background(photo1); {
fill(255,0,0);
rect(x1, y1, x2, y2);
}
myTimer.startTimer ( ) ;
float passedTime = millis() - savedTime;
if(mouseX>x1 && mouseX<x2 && mouseY>y1 && mouseY<y2 && mousePressed &&
passedTime < totalTime) {
fill(255);
rect(x1,y1,x2,y2);
noLoop();
println("You Win: Your total time is" + " " + passedTime/1000 + " " + "Seconds");
}
if (passedTime > totalTime) {
image(photo2, 0, 0);
lovelysound.trigger();
noLoop();
println("You reaction is too slow!");
}
}
//============= Void stuffs======
// Encapsulates all needed timing.
class StopWatch
{
long _startTime = 0 ;
long _diff = 0 ;
boolean _running = false ;
float _totalTime = 0 ;
float _n = 0 ;
// Starts the timer running
void startTimer ( ) {
_startTime = millis ( ) ;
_running = true ;
println ( "start=" + _startTime ) ;
}
}
//sound off
void stop() {
lovelysound.close();
minim.stop();
super.stop();
}
//void reset(){ didn't work?
// setup();
//}
void keyReleased(){
if (key=='k') setup();
}
Personally I think 1.0 millis is a little long to sort just 10 elements ;) probably because you are also measuring the time to display the list before and after the sort.
Move the watch start/stop method calls to surround JUST what you want to measure.
void setup() {
misc.makeData(list);
misc.showList(list);
stopWatch.start();
sorts.selection(list);
stopWatch.stop();
misc.showList(list); // SHOWS LIST AFTER BEING SORTED
println(stopWatch.time());
stopWatch.reset();
exit();
}
It might seem longer because there is significant overhead in launching a sketch - for example it has to create and initialise a window even if there is no draw method.
As far as I understand it, the Java one just returns the time since 1970, while the processing one returns the time since thr sketch began running. For the use of the timer, this should not matter, as you're subtracting the starting and current value anyway. However, something does not seem to be quite right:
int listLength = 10; // NUMBER OF 4 CHARACTER ELEMENTS OF RANDOM LETTERS WITHIN THE ARRAY
String[] list = new String[listLength];
StopWatch stopWatch = new StopWatch();
MiscMethods misc = new MiscMethods();
SomeSorters sorts = new SomeSorters();
void setup() {
stopWatch.start();
misc.makeData(list);
misc.showList(list);
sorts.selection(list);
misc.showList(list); // SHOWS LIST AFTER BEING SORTED
stopWatch.stop();
println(stopWatch.time());
stopWatch.reset();
exit();
}
class StopWatch {
long startTime, endTime;
void start () {
startTime = millis();
}
void stop() {
endTime = millis();
}
double time() {
return endTime - startTime;
}
void reset() {
startTime = endTime = 0;
}
}
When I time the sort it returns anywhere from 1.0 - 3.0, and that does not seem right.
I can't believe I missed actually creating the StopWatch.
Yup, you've forgotten to instantiate the class 1st!.
However, in my tweaked versions, that's not needed at all! \m/
Same tweaked version. But w/ currentTimeMillis() in place of nanoTime():
//forum.processing.org/two/discussion/4824/stop-watch-class
String[] animals = {
"Cat", "Dog", "Turtle"
};
void setup() {
StopWatch.start();
println(animals);
StopWatch.stop();
println("\nMilliseconds: " + StopWatch.time());
println("Seconds:\t " + nf(StopWatch.time()/1e3, 0, 3));
exit();
}
static final class StopWatch {
static long startTime, endTime;
static void start() {
startTime = System.currentTimeMillis();
}
static void stop() {
endTime = System.currentTimeMillis();
}
static long time() {
return endTime - startTime;
}
static void reset() {
startTime = endTime = 0;
}
}
Tweaked version: :D
//forum.processing.org/two/discussion/4824/stop-watch-class
String[] animals = {
"Cat", "Dog", "Turtle"
};
void setup() {
StopWatch.start();
println(animals);
StopWatch.stop();
println("\nNanoseconds: " + StopWatch.time());
println("Milliseconds: " + nf(StopWatch.time()/1e6, 0, 4));
println("Seconds:\t " + nf(StopWatch.time()/1e9, 0, 3));
exit();
}
static final class StopWatch {
static long startTime, endTime;
static void start() {
startTime = System.nanoTime();
}
static void stop() {
endTime = System.nanoTime();
}
static long time() {
return endTime - startTime;
}
static void reset() {
startTime = endTime = 0;
}
}
Also take a look at this thread:
http://forum.processing.org/two/discussion/1725/millis-and-timer
or so
String[] animals;
StopWatch watch = new StopWatch();
void setup() {
watch.start();
size(10, 10);
for (int i = 0; i <19000;i++) {
animals = new String[3];
animals[0] = "Cat";
animals[1] = "Dog";
animals[2] = "Turtle";
}
watch.stop();
print(watch.time());
}
//void bubbleSort (String[] ar) {
// for (int i = 0; i < ar.length-1; i++) {
// for (int j = 0; j < ar.length-1; j++) {
// if (ar[j].compareTo(ar[j+1]) > 0) {
// swap (ar, j, j+1);
// // you need a swap method
// }
// }
// }
//}
class StopWatch {
double startTime=0, endTime=0;
void start () {
startTime = millis();
}
void stop() {
endTime = millis();
}
double time() {
return (endTime - startTime);
}
void reset() {
startTime = 0;
endTime = 0;
}
}
since it's class
you need
StopWatch watch = new StopWatch();
?
Hello ladies and gents,
I am attempting to make a basic stop watch program that.
Here's the code:
String[] animals;
void setup() {
StopWatch.start();
animals = new String[3];
animals[0] = "Cat";
animals[1] = "Dog";
animals[2] = "Turtle";
StopWatch.stop();
print(StopWatch.time());
}
//void bubbleSort (String[] ar) {
// for (int i = 0; i < ar.length-1; i++) {
// for (int j = 0; j < ar.length-1; j++) {
// if (ar[j].compareTo(ar[j+1]) > 0) {
// swap (ar, j, j+1);
// // you need a swap method
// }
// }
// }
//}
class StopWatch {
long startTime, endTime;
void start () {
startTime = millis();
}
void stop() {
endTime = millis();
}
double time() {
return endTime - startTime;
}
void reset() {
startTime = 0;
endTime = 0;
}
}
I get the error: Cannot make a static reference to the non-static method start() from the type SSE.StopWatch on line 4 of the main window.
The grid background is supposed to be there during the duration of the program...below is updated code. The grid does not work any better, but there are other updates:
PFont font; //pre-setup font
static final color ON = #3F8958, OFF = 0; //Directional colors
static boolean north, south, east, west; //booleans for direction
boolean showGrid = false; //?
float servoLineX = 500;//servo line X coordinate
float servoLineY = 200; // servo line Y coordinate
char letterB = 'b';
Timer t1 = new Timer(); //class setups
Button b1 = new Button();
Button b2 = new Button();
void setup() { //Prepare screen and init Arduino connection
size(950, 1000); //about half a screen
frameRate(100);
font = createFont("ComicSansMS", 32);//stopwatch font
t1.update(); //timer class call
servoLine(); //what it sounds like
frame.setResizable(true);
}
void keyPressed() {
setDirection(keyCode, true);// when the key is pressed, a boolean value will = true
redraw();
}
void keyReleased() {
setDirection(keyCode, false);// when the key is not pressed, a boolean value will = false
redraw();
}
static final void setDirection(int k, boolean bool) {
if (k == UP) north = bool; // setting up directional booleans for easy access
else if (k == DOWN) south = bool;
else if (k == LEFT) west = bool;
else if (k == RIGHT) east = bool;
}
void draw() {
drawGridBackground();
background(255);
if (width > displayWidth) {
drawGridBackground();
servoLine();
b1.execute1(360, 490, 200, 100); //execute classes below
b2.execute2(200, 490, 100, 100);
t1.execute();
} else if (width < displayWidth) {
drawGridBackground();
servoLine();
b1.execute1(360, 490, 200, 100); //execute classes below
b2.execute2(200, 490, 100, 100);
t1.execute();
} else if (width >= displayWidth) {
drawGridBackground();
servoLine();
b1.execute1(360, 490, 200, 100); //execute classes below
b2.execute2(200, 490, 100, 100);
t1.execute();
}
if (keyPressed == true) {
if (key == '1') { //buttons for stopwatch
t1.reset();
}
else if (key == '2') {
t1.pause();
}
else if (key == '3') {
t1.unpause();
}
if (key == 'b') { //servo control
if (servoLineY > 170) {
servoLineX = servoLineX + 1;
servoLineY = servoLineY - 4;
drawGridBackground();
servoLine();
b1.execute1(360, 490, 200, 100); //execute classes below
b2.execute2(200, 490, 100, 100);
t1.execute();
}
} else if (key == 'n') {//"
if (servoLineY < 200) {
servoLineX = servoLineX - 1;
servoLineY = servoLineY + 4;
drawGridBackground();
servoLine();
b1.execute1(360, 490, 200, 100); //execute classes below
b2.execute2(200, 490, 100, 100);
t1.execute();
}
}
}
strokeWeight(0);
fill(north? ON:OFF); //directional GUI light up keys
rect(181, 121, 55, 55);
fill(south? ON:OFF);
rect(181, 191, 55, 55);
fill(west? ON:OFF);
rect(111, 191, 55, 55);
fill(east? ON:OFF);
rect(251, 191, 55, 55);
}
void drawGridBackground() {
line(0, height - 1, width, height - 1); //what it sounds like
stroke(17, 83, 137);
line(0, 0, width, 0);
line(0, 0, 0, height - 1);
line(width, 0, width, height - 1);
stroke(10, 58, 92);
for (int posX = 0; posX < (width / 5); posX++) {
line((5 * posX) + 1, 1, (5 * posX) + 1, height - 2);
}
for (int posY = 0; posY < (height / 5); posY++) {
line(1, (5 * posY) + 1, width - 1, (5 * posY) + 1);
}
}
void servoLine() { //what it sounds like
stroke(0);
strokeWeight(20);
line(servoLineX, servoLineY, 700, 200);
ellipse(700, 190, 20, 20);
loop();
}
void oct(int s, int x, int y, int X, int Y) { //octagon function
line(x - (X/2), y - (s/2), x - (X/2), y + (s/2));
line(x + (X/2), y - (s/2), x + (X/2), y + (s/2));
line(x - (s/2), y + (Y/2), x + (s/2), y + (Y/2));
line(x - (s/2), y - (Y/2), x + (s/2), y - (Y/2));
//***********************************************
line(x - (X/2), y + (s/2), x - (s/2), y + (Y/2));
line(x + (s/2), y + (Y/2), x + (X/2), y + (s/2));
line(x + (X/2), y - (s/2), x + (s/2), y - (Y/2));
line(x - (s/2), y - (Y/2), x - (X/2), y - (s/2));
//*********************************************************
noStroke();
fill(0, 0, 255); //unorthodox fill for octagon
triangle(x - (X/2), y - (s/2), x - (X/2), y + (s/2), x, y);
triangle(x + (X/2), y - (s/2), x + (X/2), y + (s/2), x, y);
triangle(x - (s/2), y + (Y/2), x + (s/2), y + (Y/2), x, y);
triangle(x - (s/2), y - (Y/2), x + (s/2), y - (Y/2), x, y);
triangle(x - (X/2), y + (s/2), x - (s/2), y + (Y/2), x, y);
triangle(x + (s/2), y + (Y/2), x + (X/2), y + (s/2), x, y);
triangle(x + (X/2), y - (s/2), x + (s/2), y - (Y/2), x, y);
triangle(x - (s/2), y - (Y/2), x - (X/2), y - (s/2), x, y);
}
void polygon(float x, float y, float radius, int npoints) { //any polygon
float angle = TWO_PI / npoints;
beginShape();
for (float a = 0; a < TWO_PI; a += angle) {
float sx = x + cos(a) * radius;
float sy = y + sin(a) * radius;
vertex(sx, sy);
}
endShape(CLOSE);
}
class Timer { //timer class
int timerStart = 0;//millis()
int offset;
int mill;
int minutes;
int seconds;
int hundredths;
boolean stopped = true;
boolean continued = false;
Timer() {
}
void execute() {
update();
textFont(font);
textSize(32);
fill(0);
text(nf(minutes, 2, 0)+":"+nf(seconds, 2, 0)+":"+nf(hundredths, 2, 0), 400, 550);//visible stopwatch
}
void update() {
if (!stopped) {
mill = (millis()-timerStart); //stopwatch #'s
if (continued) mill += offset;
seconds = mill / 1000;
minutes = seconds / 60;
seconds = seconds % 60;
hundredths = mill / 10 % 100;
}
}
void pause() {
stopped = true;
}
void unpause() {
stopped = false;
continued = true;
timerStart = millis();
offset = mill;
}
void reset() {
stopped = true;
continued = false;
mill = 0;
timerStart = millis();
mill = (millis()-timerStart);
}
int minutes() {
return minutes;
}
int seconds() {
return seconds;
}
int hundredths() {
return hundredths;
}
boolean isPaused() {
return stopped;
}
}
class Button {
color rectColor, baseColor;
color rectHighlight;
color currentColor;
boolean rectOver1 = false;
boolean rectOver2 = false;
boolean paused = false;
Button() {
}
void execute1(int rectX, int rectY, int rectSizeX, int rectSizeY) {
update1(rectX, rectY, rectSizeX, rectSizeY);
if (rectOver1) {
fill(rectHighlight);
}
else {
fill(rectColor);
}
stroke(0);
strokeWeight(20);
fill(0, 255, 0);
rect(rectX, rectY, rectSizeX, rectSizeY);
}
void update1(int rectX, int rectY, int rectSizeX, int rectSizeY) {
rectColor = color(0);
rectHighlight = color(51);
baseColor = color(255);
currentColor = baseColor;
rectOver1 = isMouseOverRect1(rectX, rectY, rectSizeX, rectSizeY);
if (rectOver1) {
currentColor = rectColor;
}
if (mousePressed && rectOver1 == true & paused == false) {
t1.pause();
paused = true;
} else if (mousePressed && rectOver1 == true & paused == true) {
t1.unpause();
paused = false;
}
}
boolean isMouseOverRect1(int x, int y, int width, int height) {
if (mouseX >= x && mouseX <= x+width && mouseY >= y && mouseY <= y+height) {
return true;
}
else {
return false;
}
}
void execute2(int rectX, int rectY, int rectSizeX, int rectSizeY) {
update2(rectX, rectY, rectSizeX, rectSizeY);
if (rectOver2) {
fill(rectHighlight);
}
else {
fill(rectColor);
}
stroke(0);
strokeWeight(20);
fill(0, 255, 0);
rect(rectX, rectY, rectSizeX, rectSizeY);
}
void update2(int rectX, int rectY, int rectSizeX, int rectSizeY) {
rectColor = color(0);
rectHighlight = color(51);
baseColor = color(255);
currentColor = baseColor;
rectOver2 = isMouseOverRect2(rectX, rectY, rectSizeX, rectSizeY);
if (rectOver2) {
currentColor = rectColor;
}
if (mousePressed && rectOver2 == true & paused == false) {
t1.reset();
}
}
boolean isMouseOverRect2(int x, int y, int width, int height) {
if (mouseX >= x && mouseX <= x+width && mouseY >= y && mouseY <= y+height) {
return true;
}
else {
return false;
}
}
}
Thanks, DebianAddict