Stap 2: Code
Nu dat je alles setup, kunnen we wat code schrijven. Laten we springen in onze sandbox-map en vervolgens onze projectmap en aan de slag!
>> cd mySandbox/intruderAlert>> nano -$ -i intruderAlert.js
Cool bonen, nu we onze code schrijven! Wanneer u klaar bent, drukt u op control + o op te slaan en vervolgens control + x om af te sluiten Nano. De teksteditor op instructables is buggy. Als u de code bekijkt en een < br > ziet, verwijderen en te vervangen door een nieuwe regel (dwz drukt u op enter of return).
//Set up our GPIO input for pin 5 on the Arduino breakout board var mraa = require('mraa'); var motionSensor = new mraa.Gpio(5); motionSensor.dir(mraa.DIR_IN); //Set up our node mailer var nodemailer = require("nodemailer"); var smtpTransport = nodemailer.createTransport{ service: "Gmail", auth: { user: "example pass: "password" } }); //Start sensing! periodicActivity(); //Here is our sensing function: function periodicActivity() { //Read our sensor var motionSensorTriggered = motionSensor.read(); //Do stuff if our sensor is read HIGH if(motionSensorTriggered){ //Send our email message smtpTransport.sendMail({ from: "John Doe <example to: "John Doe <example subject: "Possible Intruder Alert", text: "Hey! Something activated your motion sensor!" }, function(error, response){ //Send a report of the message to the console if(error){ console.log(error); }else{ console.log("Message sent: " + response.message); } smtpTransport.close(); }); //We don't want 5 million emails, so we want to wait a few seconds //(in this case, 30 seconds) before sending another email. The timeout //is in milliseconds. So, for 1 minute, you would use 60000. setTimeout(periodicActivity, 30000); }else{ //Our motion sensor wasn't triggered, so we don't need to wait as long. // 1/10 of a second seems about right and allows our Edison to do other // things in the background. setTimeout(periodicActivity, 100); } }