Making a timer (stopwatch/laptimer)

Hi guys, been a while since Ive come round here with a question.
I am using a mega328p that I am trying to turn into a stopwatch laptimer. The code posted below is how I planned on doing it, but I am getting odd results

		while (~PINB&(1<<button));  
		_delay_ms(50); 
		timer_tick=-50; //this is meant to start the timer at zero, taking account of the debounce delay above

		while (!(~PINB&(1<<button))); 
		_delay_ms(50);  
//first take 5 timings

		for (j=0;j<5;j++){

			while (~PINB&(1<<button));  
			_delay_ms(50); 
			datatable[j+2] = (double)(timer_tick-50)/1000;     

			while (!(~PINB&(1<<button))); 
			_delay_ms(50);  
		}
		timer_tick=-50; //for length of gap
//now take 1 more timing, but time the length of the gap between the above 5 timings, and the following one
		while (~PINB&(1<<button));  
		_delay_ms(50); 
		datatable[1] = (double)(timer_tick-50)/1000; //gap
		timer_tick=-50;

		while (!(~PINB&(1<<button)));  
		_delay_ms(50);  

		while (~PINB&(1<<button));  
		_delay_ms(50);  
		datatable[0] = (double)(timer_tick-50)/1000;      

		while (!(~PINB&(1<<button)));  
		_delay_ms(50);  

			printf("timings: %f, gap: %f, %f, %f, %f, %f, %f\n", datatable[0], datatable[1], datatable[2], datatable[3], datatable[4], datatable[5], datatable[6], datatable[7]);

However the timings (datatable[2]) doesnt get reset it seems, the rest should be cumulative, but when the first one is taken it should start the timer back at zero.
I thought Id covered for that.
Can anyone help me with this code.
BTW I have left out the timer setup and the timer interrupt, but basically every 10ms the variable timer_tick is increased by 10.

Thanks guys
Alex

Hello, Alex.

We already made a basic timer demo for the ATmega328p. You can see it in the time_test function of the 3pi demo program:
github.com/pololu/libpololu-avr … ram/test.c

I think you are not being careful enough with your timer_tick variable. Assuming it is more than one byte, you should disable the interrupt that modifies it before you read or write to it from your main loop.

I don’t really understand what your code is supposed to do. Maybe if you told me how you are pressing the button, and the expected behavior versus the actual behavior then I would have an idea.

–David

datatable[j+2] = (double)(timer_tick-50)/1000;

I’m not positive, but seems like this line is doing integer division before casting to double which would result in 0.0 every time regardless of the value of timer_tick… ? What if you do

( ((double) timer_tick) - 50.0 ) / 1000.0

Michael