# Clock: Snippets

How to make something happen every second (once).

```int s;
int lastSecond;

void setup()
{
size(200, 200);
}

//this function is called 60 times per second
void draw()
{
s = second();

//if the second was updated then do something once
if (s != lastSecond)
{
println("A second elapsed");
//update the last second
lastSecond = s;
//this variables will be the same until
//the next second change in the clock
}
}```

Common problem: second() is related to the system clock but millis() count starts as you run the applet.
Sometimes you need them to be in sync, for example if you want an analog clock with a second arm moving smoothly:

```
int millisRolloverTime;
int prevSec;

void setup()
{
size(100, 100);
millisRolloverTime = 0;
}

void draw()
{
background(0);

int H= hour ();
int M= minute ();
int S= second ();

if (prevSec != S) {
millisRolloverTime = millis();
}

prevSec = S;
int mils = millis() - millisRolloverTime;
text(second() + " " + mils, 10, 20);

}
```

Here’s a classic analog clock:

```// All Examples Written by Casey Reas and Ben Fry
// unless otherwise stated.
void setup() {
size(200, 200);
stroke(255);
smooth();
}
void draw() {
background(0);
fill(80);
noStroke();
// Angles for sin() and cos() start at 3 o'clock;
// subtract HALF_PI to make them start at the top
ellipse(100, 100, 160, 160);
float s = map(second(), 0, 60, 0, TWO_PI) - HALF_PI;
float m = map(minute(), 0, 60, 0, TWO_PI) - HALF_PI;
float h = map(hour() % 12, 0, 12, 0, TWO_PI) - HALF_PI;
stroke(255);
strokeWeight(1);
line(100, 100, cos(s) * 72 + 100, sin(s) * 72 + 100);
strokeWeight(2);
line(100, 100, cos(m) * 60 + 100, sin(m) * 60 + 100);
strokeWeight(4);
line(100, 100, cos(h) * 50 + 100, sin(h) * 50 + 100);
}```

#### Sounds

We didn’t cover this in class but playing sound files in processing is very easy:

```import ddf.minim.*;

Minim minim;
AudioPlayer song;

void setup()
{
size(100, 100);

minim = new Minim(this);

// this loads mysong.wav from the data folder
song.play();
}

void draw()
{
background(0);
}

void stop()
{
song.close();
minim.stop();

super.stop();
}```