From e8333c598b22b7e6f39c0cc37e243ceab74534b1 Mon Sep 17 00:00:00 2001
From: Joerg Wunsch <j@uriah.heep.sax.de>
Date: Fri, 13 Sep 2013 14:59:15 +0000
Subject: [PATCH] patch #5708 avrdude should make 10 synchronization attempts
 instead of just one * stk500.c (stk500_getsync): Loop 10 times trying to get
 in sync with the programmer.

git-svn-id: svn://svn.savannah.nongnu.org/avrdude/trunk/avrdude@1223 81a1dc3b-b13d-400b-aceb-764788c761c2
---
 ChangeLog |  6 ++++++
 NEWS      |  1 +
 stk500.c  | 20 +++++++++++++-------
 3 files changed, 20 insertions(+), 7 deletions(-)

diff --git a/ChangeLog b/ChangeLog
index 8b4778ce..29d13d47 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,9 @@
+2013-09-13  Joerg Wunsch <j.gnu@uriah.heep.sax.de>
+
+	patch #5708 avrdude should make 10 synchronization attempts instead of just one
+	* stk500.c (stk500_getsync): Loop 10 times trying to get in
+	sync with the programmer.
+
 2013-09-13  Joerg Wunsch <j.gnu@uriah.heep.sax.de>
 
 	Contributed by Ricardo Martins:
diff --git a/NEWS b/NEWS
index 68e1bc3c..fad9fda2 100644
--- a/NEWS
+++ b/NEWS
@@ -105,6 +105,7 @@ Current:
       - bug #28344: chip_erase_delay too short for ATmega324P, 644, 644P, and 1284P
       - bug #34277: avrdude reads wrong byte order if using avr911 (aka butterfly)
       - bug #35456: The progress bar for STK500V2 programmer is "wrong".
+      - patch #5708 avrdude should make 10 synchronization attempts instead of just one
 
   * Keep track of input file contents
 
diff --git a/stk500.c b/stk500.c
index a1f502bd..83740e7a 100644
--- a/stk500.c
+++ b/stk500.c
@@ -44,6 +44,7 @@
 #include "serial.h"
 
 #define STK500_XTAL 7372800U
+#define MAX_SYNC_ATTEMPTS 10
 
 static int stk500_getparm(PROGRAMMER * pgm, unsigned parm, unsigned * value);
 static int stk500_setparm(PROGRAMMER * pgm, unsigned parm, unsigned value);
@@ -80,6 +81,7 @@ int stk500_drain(PROGRAMMER * pgm, int display)
 int stk500_getsync(PROGRAMMER * pgm)
 {
   unsigned char buf[32], resp[32];
+  int attempt;
 
   /*
    * get in sync */
@@ -95,13 +97,17 @@ int stk500_getsync(PROGRAMMER * pgm)
   stk500_send(pgm, buf, 2);
   stk500_drain(pgm, 0);
 
-  stk500_send(pgm, buf, 2);
-  if (stk500_recv(pgm, resp, 1) < 0)
-    return -1;
-  if (resp[0] != Resp_STK_INSYNC) {
-    fprintf(stderr, 
-            "%s: stk500_getsync(): not in sync: resp=0x%02x\n",
-            progname, resp[0]);
+  for (attempt = 0; attempt < MAX_SYNC_ATTEMPTS; attempt++) {
+    stk500_send(pgm, buf, 2);
+    stk500_recv(pgm, resp, 1);
+    if (resp[0] == Resp_STK_INSYNC){
+      break;
+    }
+    fprintf(stderr,
+            "%s: stk500_getsync() attempt %d of %d: not in sync: resp=0x%02x\n",
+            progname, attempt + 1, MAX_SYNC_ATTEMPTS, resp[0]);
+  }
+  if (attempt == MAX_SYNC_ATTEMPTS) {
     stk500_drain(pgm, 0);
     return -1;
   }