Madison didn’t believe that a bill of rights was necessary, but, having promised one during the ratification process, he thought it was essential to deliver, and he did. The Second Amendment was obviously part of that process.
The Second Amendment was a product of the issues of the day. Many Americans who opposed the Constitution were concerned that the increase in federal power would result in the creation of a large standing army, which in turn would represent a threat to individual liberty. Madison wanted to assure those people that militias would remain a viable alternative to a standing army in order to build confidence in the new system. The Second Amendment was designed for that purpose.
I think it is fair to say that Madison would be shocked at the notion that the government was powerless to protect school children from automatic weapons as a result of his hard work.