Hi your code is right. You made a small logical mistake.. You forget to clear flag. I tried your code as it is with flag reset. It worked well.
flag = 0;