If you’re going to rob a doughnut shop, don’t be surprised when a cop shows up.

An MBTA Transit cop’s fortuitous arrival at a Charlestown Dunkin’ Donuts at exactly the right moment thwarted an armed robbery in progress.

Officer Matthew Donovan, 29, said he was just “grabbing a cup of coffee” when he entered a crowded Dunkin’ Donuts on Cambridge Street in Charlestown at 5:30 p.m. on Saturday.

Instead, he heard an irritated voice demanding money from the cashier at the counter.

“Right when I walked in, a female who was leaving said, ‘Oh, thank God you’re here. He’s right over there.’

“At the time, he just seemed like an angry customer, yelling, ‘You owe me more money than that. Open that register,’ ” said Donovan, an Iraq war veteran. “I looked at the cashier and said, ‘Well, how much did he give you? I looked in their eyes and they were very wide and white. They looked more scared than they should be, for a man just demanding change.”

By then, Donovan said, the man had become aware of his presence.

“He stopped demanding the money, and I asked the cashier how much he gave her. She said, ‘He has a knife in his pocket. He asked for all the money in the register.’ ” Donovan, a Medford-raised Marine, sprung into action.

“I turned to him and said, ‘Where’s the knife?’ He made a very quick movement toward his right pocket. At that time, I secured his hands to his chest, and called for help.”

Donovan then discovered Wallace was carrying a spoon, not a knife.

The clerks thought it was a knife, Donovan said, “because he was holding it by the round end, and showing them the long skinny handle.”

Michael Wallace, 35, of Boston was charged with attempted armed robbery and assault by means of a dangerous weapon.

Police also said that while they were putting Wallace under arrest, he was carrying a black sock filled with women’s bracelets and necklaces.

Wallace faces arraignment today in Charlestown District Court, and Donovan is earning high praise from his bosses.

“He’s well trained and well prepared,” MBTA Police Superintendent-in-Chief Joseph O’Connor said. “We’re very proud of the work he did.”