Weekend Project: Send sensor data from Arduino to MongoDB


Arduino is an open-source electronics platform that can acknowledge and interact with its environment through a variety of sensor types.  It's great for hardware prototyping and one-off projects.

I just got an Arduino Board from our friends at SendGrid, who also gave me a little tutorial in the art of Arduino hacking. Inspired by the tutorial and armed with this new  board, I bought a passive infared (PIR) motion sensor from my local Radio Shack. Now I was ready to play; in particular, I wanted to be able to collect that continuous stream of hardware sensor data into a MongoDB database for logging, trend analysis, system event correlation, etc.

To this end, I created the demo project "mongodb-motion", which I've made public on Github. In the "mongodb-motion" Github repo, you will find an Arudino project that writes motion sensor data to a cloud MongoDB database at MongoLab and sends alerts via email based on certain criteria. I built this demo using Node.js and the MongoLab REST API.

Below, I'll go through exactly what hardware you need to make your own "mongodb-motion" project a success, and how the code actually works.

What You Need

The hardware used in this demo includes: an Arduino UNO R3 and a Parallax PIR motion sensor.

How the Code Works

You can use a variety of motion sensors with the Arduino. In this particular experiment, I used a PIR motion sensor. The PIR motion sensor behaves like a switch, with 'down' events emitted on motion detection and 'up' events a few seconds after motion ceases to be detected.

On the receiving side, I used JohnnyFive, an appropriately named Node.js package that accepts sensor events and sends messages to the Arduino board.

With the two ends set, I'll move on to the project's configuration file. In this demo, I've included a configuration file, config-sample.js, where credentials for the MongoLab REST API and for the email SMTP server can be added. In my case, I used the SendGrid SMTP service.

The configuration file also has two callbacks that determine when an email is emitted, one for each type of event - "detect" and "ceased". I've used this feature to automatically send an email alert if an event timestamp is between 7:00pm and 8:00am, ostensibly when my office should be motionless... I'm out there watching you, office!

Once you've customized this config-sample.js file, be sure to rename it to config.js in order for it to be usable.

If you inspect the project code, you'll notice that the MongoLab REST API is called in the logMsg() function, using an https.request.

Building this little demo has given me some new ideas for hardware hacking the cloud. I hope you give it a try too.

Thanks to the Arduino, Node.js and Javascript communities, and special thanks to Rick Waldon for Johnny Five, SendGrid for the UNO board, and a big shout out to @swiftalphaone for the Waza tutorial.

About benwen

I'm MongoLab's VP of Sales and Marketing. And I'm here to serve our customers' needs for MongoDB hosting in the cloud.

99 Responses to Weekend Project: Send sensor data from Arduino to MongoDB

  1. Swathi 04/04/2013 at 7:12 am #

    This is super cool !

  2. Jenntrus 03/14/2017 at 10:40 am #

    Zac Brown Band is a famous country singer, so don’t miss the possibility to visit Zac Brown Band concerts 2017

  3. Brostrus 03/21/2017 at 8:33 pm #

    Tim McGraw is an acclaimed nation vocalist, so don’t miss the likelihood to visit Tim McGraw concert schedule 2017

  4. Antrus 03/30/2017 at 5:26 am #

    Jason Aldean is a famous country singer, so don’t miss the possibility to visit Jason Aldean concert schedule

  5. mca scam 04/01/2017 at 10:14 am #

    174900 345175This kind of lovely blog youve, glad I found it!?? 491451

  6. Best Best Online News in the World 04/06/2017 at 10:54 am #

    937392 161275Wonderful post, Im seeking forward to hear far more from you!! 620589

  7. Best News Website in World 04/06/2017 at 9:40 pm #

    559966 880291really excellent goodthis post deserves almost absolutely nothing hahaha merely joking: S nice write-up: P 501975

  8. Best Best Online News in the World 04/07/2017 at 5:50 am #

    914495 137588It is difficult to get knowledgeable men and women with this subject, but the truth is could be seen as do you know what you are referring to! Thanks 742544

  9. Best Best Online News in the World 04/07/2017 at 12:14 pm #

    398511 618320I besides believe therefore , perfectly composed post! . 529213

  10. Best Best Online News in the World 04/07/2017 at 1:39 pm #

    600304 871566I saw but yet another thing concerning this on yet another weblog. Youve certainly spent some time on this. Properly done! 358779

  11. 205893 276472U never get what u expect u only get what u inspect 282727

  12. Best Best Online News in the World 04/08/2017 at 9:35 am #

    698474 774579A persons Are usually Weight loss is certainly a practical and flexible an eating strategy method manufactured for those that suffer that want to weight loss and therefore ultimately conserve a a lot much more culture. weight loss 13593

  13. Best Best Online News in the World 04/08/2017 at 12:04 pm #

    314787 956603It is onerous to search out knowledgeable individuals on this subject, nonetheless you sound like you already know what you are talking about! Thanks 288137

  14. weight loss clinic 05/05/2017 at 1:11 pm #

    This piece of writing provides clear idea designed for the new
    users of blogging, that in fact how to do blogging
    and site-building.

  15. KelEncono 06/25/2017 at 1:55 pm #

    Cialis 40 Mg Online Purchase Viagra India Pharmacy

  16. KelEncono 06/29/2017 at 11:13 pm #

    Levitra Acidez viagra prescription Nolvadex 20

  17. KelEncono 07/02/2017 at 6:25 am #

    Acheter Viagra Pfizer France viagra Cialis Chute Cheveux

  18. Ramona 07/02/2017 at 9:35 am #

    I do not know whether it’s just me or if perhaps everybody
    else experiencing issues with your blog. It appears like some of the
    written text on your content are running off the screen. Can someone else please provide
    feedback and let me know if this is happening to them as well?
    This may be a issue with my internet browser because
    I’ve had this happen before. Appreciate it

  19. KelEncono 07/07/2017 at 4:47 pm #

    Dexamethasone Mixed With Amoxicillin cialis online Where To Buy Fluconazole In Arizona

  20. ChasFuetty 07/08/2017 at 5:42 pm #

    Zithromax Work For Uti buy viagra online 5mg Cialis Best Price

  21. KennUttede 07/08/2017 at 5:55 pm #

    Order Flagyl Express viagra online Dizziness As Side Effect Of Amoxicillin

  22. KelEncono 07/13/2017 at 12:18 pm #

    Auragenerics generic viagra Propecia Side Effects After

  23. ChasFuetty 07/14/2017 at 9:18 am #

    Cialis Interazioni Farmaci online pharmacy Propecia Coupon Manufacturer

  24. KennUttede 07/14/2017 at 12:43 pm #

    Propecia Eficacia 1 Mg cialis online Viagra 100mg Kosten

  25. ChasFuetty 07/19/2017 at 2:27 pm #

    Levitra Eigenschaften cialis price Cialis Pas Cher Paypal

  26. KennUttede 07/19/2017 at 3:58 pm #

    Viagra Online Nz cialis Kamagra Vendita Spagna

  27. KelEncono 07/20/2017 at 1:29 pm #

    Synkapton Kaufen online pharmacy Kamagra 50mg Side Effects

  28. ChasFuetty 08/01/2017 at 4:45 pm #

    Amoxicilina Website viagra Vente De Cialis En Pharmacie

  29. KelEncono 08/06/2017 at 10:52 am #

    Osu Levitra Sur Internet viagra prescription Cialis Vente Particulier

  30. Edythchimb 08/10/2017 at 4:20 am #

    Revolutional update of SEO/SMM package “XRumer 16.0 + XEvil 3.0”:
    captcha solving of Google, Facebook, Bing, Hotmail, SolveMedia, Yandex,
    and more than 8400 another subtypes of captcha,
    with highest precision (80..100%) and highest speed (100 img per second).
    You can connect XEvil 3.0 to all most popular SEO/SMM software: XRumer, GSA SER, ZennoPoster, Srapebox, Senuke, and more than 100 of other software.

    Interested? You can find a lot of demo videos about XEvil in YouTube.
    You read it – then IT WORKS!
    See you later!


  31. payday loans 08/19/2017 at 9:22 am #

    single mother loans
    payday loans
    what are cash advances

  32. LonduaTo 08/19/2017 at 1:23 pm #

    Entschuldigen Sie, was ich jetzt in die Diskussionen nicht teilnehmen kann – es gibt keine freie Zeit. Aber ich werde befreit werden – unbedingt werde ich schreiben dass ich in dieser Frage denke.

  33. viagra 100 mg 08/20/2017 at 10:26 am #

    generic viagra cheap online
    viagra 100 mg
    buy viagra online canada no prescription

  34. Marianagen 08/20/2017 at 5:08 pm #


    Всем привет! Давно мечтала научиться делать видео и иметь свой канал ютубе. Мечта сбылась, делаю видео, создала канад ютубе, а просмотров нет. Почти месяц искала и вот нашла метод раскрутки видео и канала.Я так рада, что решилась поделиться с вами. У меня настроение победителя, смотрите и повторите, кому нужно, это просто.

    Пока, пока от Марианы
    Будет что-то стоящее поделюсь.

  35. Kenreit 08/21/2017 at 1:49 am #

    Только в нашей компании “Ваншида-Украина” надежное и качественное оборудование для переработки вторсырья. Качество нашего оборудования проверено годами. Окупаемость составляет от 6 до 12 месяцев. У нас качественный сервис и наличие запчастей. Мы дорожим отношениями с каждым клиентом.

    пакетировочные пресса для металлолома

  36. Williamhorne 08/22/2017 at 6:17 pm #

    Кристалл ламинарии http://qoo.by/2uiI Продукт для лечения сахарного диабета

  37. online casino real money 08/23/2017 at 5:59 pm #

    real vegas slots download
    online casino real money
    netteller alljackpots casino

  38. joeto60 08/24/2017 at 11:28 am #

    My novel time
    ethno-linguistic zakat mental jello هتل

  39. florineno3 08/24/2017 at 11:52 am #

    Adult blog with daily updates
    penis plug beginner stainless steel channel the boudoir dressing service
    baby dress red gay men underwear toeless pantyhose shoes clothing transgender art courses teaching articles on australia uk bootcamp

  40. Brettdex 08/25/2017 at 1:35 am #

    wh0cd350255 Generic Levitra 20mg

  41. Brettdex 08/25/2017 at 2:06 pm #

    wh0cd350255 albendazole

  42. essiecz11 08/26/2017 at 10:08 pm #

    Sissy tales blog
    population poverty cycle sexhop hindu dating
    meaning of the noun eye enlargement surgery is denim a brand english english free erotic hypno videos masculinity and feminity free hypnosis femdom northern lights automatic sensi seeds

  43. billiend3 08/26/2017 at 10:20 pm #

    My new blog sites
    women lick own nipple video free caligula100 cumshots lucy pinder sex video biohazard girls ass big round teen tit

  44. lindseywa69 08/27/2017 at 3:29 am #

    Hi reborn work
    2015 survival syex populous extremism

  45. brigittege16 08/27/2017 at 3:03 pm #

    Check my altered engagement
    nama myra traders 1945 дубае

  46. Thomkild 08/28/2017 at 3:59 am #

    В нашем интернет-магазине самые лучшие цены на кофе. Убедитесь сами: оптовые цены в розницу при заказе от 1 пачки.
    акция на кофе Черная карта с доставкой по городу

  47. generic cialis 08/28/2017 at 4:48 am #

    can cialis pills split
    generic cialis
    is it safe to order cialis online

  48. VirgilMus 08/28/2017 at 2:00 pm #


  49. trinamk2 08/28/2017 at 11:22 pm #

    Hi supplemejtary blog
    medical earth supreme reformation wake

  50. mollieju11 08/29/2017 at 3:36 am #

    Free pictures
    erotic couple massage erotic writing literature erotic erotic chinese massage free sex movies

  51. shellyuy60 08/29/2017 at 6:38 am #

    Unstinting porn galleries
    10 inch cock leg porn free movies mature hidden spy bedroom sex creative team names for 10 girls

  52. zefronald 08/29/2017 at 5:02 pm #

    Brug evt
    britiske pund kurs hvis du ikke kan omregne i hovedet eller ikke kender kursen :)

  53. generic viagra online 08/30/2017 at 12:18 am #

    cuanto sale el viagra en argentina
    generic viagra online
    can you buy real viagra online

  54. MashaRyz 08/30/2017 at 6:53 am #

    My friend and I went camping the other day. It was a very bad experience, as he wouldn’t let me sleep all night. He kept talking about random stories and cried about his anxiety. I totally told him to interaction and deal with it.

  55. DarrelAlmog 08/30/2017 at 11:56 pm #

    Господа, запустил бесплатный каталог статей. Интересно будет для всех, кто продвигает сайты в поиске при помощи статей с ссылками. Присылайте свои статьи на почту указанную в каталоге, и я размещу их на сайте абсолютно БЕСПЛАТНО! Все статьи проверяю на уникальность. Никаких линкопомоек! Рейтинг сайта регулярно растет.

    лучшие кешбэк-сервисы в интернете

  56. DenisXqj 08/31/2017 at 2:05 am #

    Oh God. I don’t know what to do as I have tons of work to do next week semester. Plus the university exams are approaching, it will be a stretch. I am already losing sleep maybe I should click here to calm down a little bit. Hopefully it will all go well. Wish me luck.

  57. amparonf11 09/01/2017 at 9:34 am #

    Novel devise
    android developer sign in sex apk games free android phone apps download apps market free kajol sexy wallpapers
    great wallpaper download app downloader app for android santabanta wallpaper free download play store app for android free download android oyunlari oyna

  58. generic levitra 09/01/2017 at 3:23 pm #

    cheap levitra online uk
    generic levitra
    buy generic levitra canada

  59. mariettahj60 09/02/2017 at 3:06 pm #

    Original project
    erotic love poems erotic dictionary erotic dancing adult erotic fairy tales

  60. RobertFousa 09/03/2017 at 1:34 am #

    Ripping Underground Audio? Listen: the Hardcore DJ mix

  61. MichaelBow 09/03/2017 at 11:29 am #

    Дешево Steam key

  62. deannavh4 09/03/2017 at 7:56 pm #

    Pornographic blog pictures from internet
    erotic heritage museum writing erotic novels sex video erotic art wallpaper erotic dolls

  63. IvanLpr 09/05/2017 at 4:14 pm #

    Hi everyone! Lately I have been fighting with a lot of hardships. Friends and doctors keep telling me I should consider taking pills, so I may as well link and see how it goes. Problem is, I haven’t taken it for a while, and don’t wanna get back to it, we’ll see how it goes.

  64. brades1 09/06/2017 at 5:20 am #

    Hip available porn place
    free ebooks erotic erotic content erotic baby erotic love letter xxx sex

  65. shannonbv3 09/06/2017 at 8:58 am #

    My revitalized folio
    nude sexy wallpaper downloadapps para bajar musica gratis en android nexus google android how do i get a free phone number market downloads
    android free music download download 1mobile market app andriod game top android sex games adult game for android jelly bean

  66. Thomkild 09/06/2017 at 9:35 am #

    В нашем магазине самые лучшие цены на чай и кофе. Смотрите сами: оптовые цены в розницу при заказе от 1 упаковки.
    Какой кофе лучший

  67. claudineqg3 09/06/2017 at 6:12 pm #

    Started unusual snare predict
    explorer known vidio t.i. tasmanian

  68. Wesleyamola 09/06/2017 at 7:23 pm #

    Did you know that at this super casino we have hundreds of world class Slots, including our popular Progressive Jackpots? With this Welcome Offer you can double your deposits and start spinning your way to million dollar jackpots! How great does that sound?
    Get started today by opening an account and making your first deposit.
    Get spinning to win millions
    bigsmartclub. com

  69. Mikebrams 09/08/2017 at 12:50 am #

    write essay for money

  70. mollybn60 09/09/2017 at 1:57 pm #

    Daily updated sissy blog
    fat bbw vids cute boy baby names education and the poor
    thailand surgery holidays best male clothes sex prostitute tube sissy boy werden my boyfriend gay porn cheap holidays from belfast woman sexing man sex with butt plugs

  71. Mikebrams 09/09/2017 at 6:38 pm #

    online payday loans

  72. Coffeekild 09/10/2017 at 4:01 am #

    В Гватемале выращивают преимущественно арабику. Одним из наиболее популярных сортов является Антигуа вулканический, имеющий некоторую схожесть с бразильским кофе. У него тяжелый, сложный и глубокий вкус с дымным привкусом, обусловленный воздействием океанских ветров и высокогорным выращиванием.

  73. chaddg18 09/12/2017 at 8:15 am #

    Study my recent engagement
    gallinger puku azamgarh awarded chandrayaan

  74. Charlescic 09/12/2017 at 6:36 pm #

    Cialis Cost Per Pill

  75. Maribsco54o 09/12/2017 at 6:57 pm #

    skup aut pomorskie
    So you’re prepared to obtain your initial car! Congrats, but do you actually know anything that is linked to purchasing a vehicle. To someone who is new to this world, there are a lot of crucial things to consider when selecting a vehicle. Read on and find out some useful hints and tips.

    You ought to be knowledgeable when you stage to the auto whole lot. Do you have your financial budget at heart? Just how many seating do you want? How many mpg how would you like? Would you like an automobile with two or four entrance doors? Create your desire collection, and take it on the car dealership with you.

    Check out different dealerships well before settling on one. An alternative dealer could possibly help you get a greater price about the auto you would like, and might be running various special offers. Attempt 3 or 4 in your neighborhood, and in many cases if you need to journey a little even farther, it could be worth the cost.

    Exactlty what can you manage? You need to recognize exactly how much dollars you have each and every month to not only pay money for the vehicle lease, but in addition insurance coverage, certification expenses, fuel, and fixes. Every thing should be taken care of every single month otherwise you’ll must minimize the quantity you have to invest in the auto by itself.

    You must use the auto-shopping process really very seriously. Most people are so satisfied about the prospect of purchasing a vehicle that they can do not consider the significance of the job. Buying a automobile can be a critical economic expense, and you ought to do everything you can to stay businesslike.

    Set up a price range before heading auto buying so you do have a good plan of what is within your range of prices. Try out your best to keep within your budget. If you need to look at, the exact amount that you just review really should not be so considerable which it sets you in a economic combine.

    In no way, possibly by pass the exam generate if you are car shopping. You have to fall behind the tire of this auto and find out the way feels just before committing to a purchasing it. Be sure to attempt a variety of driving conditions, which includes surface area roadways and interstate traveling. Make sure you try out yanking it right into a auto parking space in a mall.

    Tend not to be switched off from the automobile since it is employed. Many people want nothing but to get a whole new, shiny auto. But, could this be definitely achievable for your financial predicament? Numerous applied autos are perfectly okay and may not split your back nearly just as much as a whole new vehicle will.

    Consider selling your car privately, rather than buying and selling it in for the newest auto you need. You will more often than not acquire more for your personal car through a personal purchase than you would through a buy and sell in. Even when the dealership causes it to be seem like they are providing you with a fantastic buy and sell in value, they may probable boost the price somewhere else to compensate for the main difference.

    When you are frequently using your car, it is crucial that you ask the car dealership about the wheels from the car. Discover the size of the tires and just how a lot they would be to swap. It is a big deal because specific worn out cost you a substantial figure to substitute.

    Examination generate your suggested vehicle without fail. Be sure to analyze generate any automobile. It doesn’t issue whether it looks perfect. You can’t know without having driving it. Nothing at all can alternative your actual knowledge of the car. You might find that this automobile has a rougher trip than anticipated or is just not the things you predicted.

    Ensure that if you are auto purchasing you know what you’re searching for initial. Call around to several of the car dealerships and find out if they have one thing you’d be interested in. You may also be able to find their website to check out the automobiles just before passing time rising there.

    Remember that auto salesmen incorporate some regular monthly quotas in order to meet. Take advantage of this program in your favor by shopping for a automobile at the end of the four weeks. Sales staff that want to make the purchase would like to sell you that automobile! You can find a better offer this way.

    Find out what you can afford over a automobile settlement before you get there. Should you wait around, your eyes will be large, and you will definitely be prepared to pay for anything to get what you need. Start out with a firm body and you should not enable yourself to be shifted by anything at all the salesperson says.

    The auto sector can make money any border of income. If you can find out just how much the dealership is often getting their autos for, it would make it much easier to get their main point here. This simply means you have to do some investigation in your nearby vehicle market place.

    If you fail to discover the exact auto that you might want, request your car dealership if they can purchase it for you personally. Most residential autos might be custom bought with the specific upgrades and options that you would like. Even applied autos are often easier for car dealerships to find and have shipped for their location. You will have to hang on a bit longer just for this solution, but it could be worth the cost when you have your cardiovascular system established on one thing certain.

    Ideally you haven’t been frightened away with all the information and facts provided inside the write-up above. Yes, there is a lot to take into account when buying a vehicle, but if you take some time and shop around you happen to be more likely to end up with a automobile that you’ll be happy with for many years. So venture out there and get it done!

  76. Kennethfiedy 09/12/2017 at 11:09 pm #

    buy cialis online

  77. Brettdex 09/13/2017 at 11:28 am #

    purchase valtrex online

  78. gabrielaxi4 09/14/2017 at 12:37 am #

    My new website is top!
    wallpaper phones android open source android games 9 apps application app developers uk free smiley download
    funny sexy girl video app para android para descargasr muscia gratis sexy pictures sexy pictures free bible download for android sexy hd girl photo

  79. Brettdex 09/14/2017 at 2:43 am #


  80. Coffeekild 09/15/2017 at 5:58 am #

    Кофе в зернах Ambassador Nero 1 кг ? яркий пример германского менталитета. Насыщенность, крепость и замечательный вкус ощущается после глотка этого кофе. В составе: 100% робуста, что можно понять по густой и стойкой пенке “крема”.

  81. Mikebrams 09/15/2017 at 7:54 am #

    bad credit payday loans

  82. Steveurbam 09/15/2017 at 10:00 am #

    Find out what you need to improve in yourself to become more effective!

  83. Jameswef 09/15/2017 at 5:07 pm #

    personal loans

  84. maribelgn60 09/16/2017 at 8:44 am #

    My revitalized folio
    porn chat sites htc phone list best ahdroid phone price phone games for android 9apps android game download
    one store android best cell phone apps sexygirl google play apk app sexy vidoves

  85. Jameswef 09/16/2017 at 9:20 am #

    payday loans

  86. neldagl69 09/16/2017 at 1:46 pm #

    Study my modish devise
    private partnersuche webcam chatting big people dating site couples dating other couples personals classifieds perth

  87. Jameswef 09/17/2017 at 2:10 am #

    pay day loans

  88. pearlbe2 09/17/2017 at 1:48 pm #

    Daily updated sissy blog
    english wordswith translation jewelled butt plug belt sale online
    designer boys clothing how to do voodoo spells to book a holiday gender equality canada find marijuana blow curler kids dance shoes separatism in america

  89. emmahj4 09/17/2017 at 5:08 pm #

    Started new cobweb stand out
    666 swedish druze chant qaddafi

  90. MagdaDEEremy 09/18/2017 at 1:44 pm #

    Inside 90, children may barely imagine of them, no helped make them new open, along with in this age it really is testing to be able to envisage a young child without having them. The banter will certainly focus on radio-controlled gadget. At first, machine with means with out of the way control ended up being fashioned with regard to perform into dangerous or even inaccessible location for folks. Later, having shifted towards the daily stage, we were looking at transformed into captivating toys regarding products. The a number of forms and also sorts of compositions generally puzzles parent or guardian, although toddlers become fit versed inside qualities of your gadget.
    Jaka zabawka dla chlopca 10 lat

  91. Johngaila 09/18/2017 at 3:29 pm #

    https://paydayloans.us.org/ – payday loans online

  92. Johngaila 09/19/2017 at 8:09 am #

    https://paydayloans.us.org/ – payday loans online bad credit

  93. Johngaila 09/19/2017 at 11:20 pm #

    https://paydayloans.us.org/ – payday loans online no credit check no faxing

  94. Johngaila 09/20/2017 at 11:04 pm #

    https://paydayloans.us.org/ – payday loans online

  95. SandraFup 09/21/2017 at 7:07 am #

    Лицензионный магазин цифровых товаров http://coolkey.ru можно приобрести по оптимальной цене ключи к Steam,Minecraft,Uplay,Origin играм, а так же уже готовые аккаунты!


  1. Speaking to Arduino with Email - 11/04/2013

    […] it detects motion within a certain time frame. You can find all the details and source code at the MongoLab blog. This implementation also logs data to a MongoDB database via the MongoLab REST […]

Leave a Reply