From ac5f511bab571f1a1082b85f59a3498a7f940bc0 Mon Sep 17 00:00:00 2001
From: Keith Packard <keithp@keithp.com>
Date: Sun, 18 Nov 2012 11:07:05 -0800
Subject: [PATCH] Poll usbtiny 100 times at init time instead of twice

This lets us power up the device after starting avrdude so that the
reset line is held low, which prevents any existing code that might
slow the clock from running.

Signed-off-by: Keith Packard <keithp@keithp.com>
---
 usbtiny.c |   20 ++++++++++----------
 1 file changed, 10 insertions(+), 10 deletions(-)

diff --git a/usbtiny.c b/usbtiny.c
index 5646757..0114609 100644
--- a/usbtiny.c
+++ b/usbtiny.c
@@ -315,6 +315,7 @@ static int usbtiny_set_sck_period (PROGRAMMER *pgm, double v)
 static int usbtiny_initialize (PROGRAMMER *pgm, AVRPART *p )
 {
   unsigned char res[4];        // store the response from usbtinyisp
+  int tries;
 
   // Check for bit-clock and tell the usbtiny to adjust itself
   if (pgm->bitclock > 0.0) {
@@ -333,24 +334,23 @@ static int usbtiny_initialize (PROGRAMMER *pgm, AVRPART *p )
     usbtiny_set_chunk_size(pgm, PDATA(pgm)->sck_period);
   }
 
-  // Let the device wake up.
-  usleep(50000);
-
   // Attempt to use the underlying avrdude methods to connect (MEME: is this kosher?)
-  if (! usbtiny_avr_op(pgm, p, AVR_OP_PGM_ENABLE, res)) {
+  for (tries = 0; tries < 100; tries++) {
+    // Let the device wake up.
+    usleep(50000);
+
+    if (usbtiny_avr_op(pgm, p, AVR_OP_PGM_ENABLE, res))
+      return 0;
+
+    fprintf(stderr, "%s: waiting for device (%d)\n", progname, tries);
     // no response, RESET and try again
     if (usb_control(pgm, USBTINY_POWERUP,
 		    PDATA(pgm)->sck_period, RESET_HIGH) < 0 ||
 	usb_control(pgm, USBTINY_POWERUP,
 		    PDATA(pgm)->sck_period, RESET_LOW) < 0)
       return -1;
-    usleep(50000);
-    if	( ! usbtiny_avr_op( pgm, p, AVR_OP_PGM_ENABLE, res)) {
-      // give up
-      return -1;
-    }
   }
-  return 0;
+  return -1;
 }
 
 /* Tell the USBtiny to release the output pins, etc */
-- 
1.7.10.4

